authhero 4.46.0 → 4.47.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/authhero.cjs +4 -4
- package/dist/authhero.d.ts +64 -0
- package/dist/authhero.mjs +38 -24
- package/dist/stats.html +1 -1
- package/package.json +3 -3
package/dist/authhero.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var ix=Object.create;var am=Object.defineProperty;var ox=Object.getOwnPropertyDescriptor;var sx=Object.getOwnPropertyNames;var ax=Object.getPrototypeOf,cx=Object.prototype.hasOwnProperty;var lx=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of sx(t))!cx.call(e,i)&&i!==n&&am(e,i,{get:()=>t[i],enumerable:!(r=ox(t,i))||r.enumerable});return e};var ux=(e,t,n)=>(n=e!=null?ix(ax(e)):{},lx(t||!e||!e.__esModule?am(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@hono/zod-openapi");var I=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=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})}};const _e=e=>typeof e=="string",os=()=>{let e,t;const n=new Promise((r,i)=>{e=r,t=i});return n.resolve=e,n.reject=t,n},cm=e=>e==null?"":""+e,dx=(e,t,n)=>{e.forEach(r=>{t[r]&&(n[r]=t[r])})},px=/###/g,lm=e=>e&&e.indexOf("###")>-1?e.replace(px,"."):e,um=e=>!e||_e(e),Ts=(e,t,n)=>{const r=_e(t)?t.split("."):t;let i=0;for(;i<r.length-1;){if(um(e))return{};const s=lm(r[i]);!e[s]&&n&&(e[s]=new n),Object.prototype.hasOwnProperty.call(e,s)?e=e[s]:e={},++i}return um(e)?{}:{obj:e,k:lm(r[i])}},dm=(e,t,n)=>{const{obj:r,k:i}=Ts(e,t,Object);if(r!==void 0||t.length===1){r[i]=n;return}let s=t[t.length-1],a=t.slice(0,t.length-1),c=Ts(e,a,Object);for(;c.obj===void 0&&a.length;)s=`${a[a.length-1]}.${s}`,a=a.slice(0,a.length-1),c=Ts(e,a,Object),c?.obj&&typeof c.obj[`${c.k}.${s}`]<"u"&&(c.obj=void 0);c.obj[`${c.k}.${s}`]=n},fx=(e,t,n,r)=>{const{obj:i,k:s}=Ts(e,t,Object);i[s]=i[s]||[],i[s].push(n)},Fc=(e,t)=>{const{obj:n,k:r}=Ts(e,t);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},hx=(e,t,n)=>{const r=Fc(e,n);return r!==void 0?r:Fc(t,n)},fv=(e,t,n)=>{for(const r in t)r!=="__proto__"&&r!=="constructor"&&(r in e?_e(e[r])||e[r]instanceof String||_e(t[r])||t[r]instanceof String?n&&(e[r]=t[r]):fv(e[r],t[r],n):e[r]=t[r]);return e},Vr=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var _x={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const mx=e=>_e(e)?e.replace(/[&<>"'\/]/g,t=>_x[t]):e;class gx{constructor(t){this.capacity=t,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(t){const n=this.regExpMap.get(t);if(n!==void 0)return n;const r=new RegExp(t);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(t,r),this.regExpQueue.push(t),r}}const yx=[" ",",","?","!",";"],bx=new gx(20),vx=(e,t,n)=>{t=t||"",n=n||"";const r=yx.filter(a=>t.indexOf(a)<0&&n.indexOf(a)<0);if(r.length===0)return!0;const i=bx.getRegExp(`(${r.map(a=>a==="?"?"\\?":a).join("|")})`);let s=!i.test(e);if(!s){const a=e.indexOf(n);a>0&&!i.test(e.substring(0,a))&&(s=!0)}return s},of=(e,t,n=".")=>{if(!e)return;if(e[t])return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;const r=t.split(n);let i=e;for(let s=0;s<r.length;){if(!i||typeof i!="object")return;let a,c="";for(let l=s;l<r.length;++l)if(l!==s&&(c+=n),c+=r[l],a=i[c],a!==void 0){if(["string","number","boolean"].indexOf(typeof a)>-1&&l<r.length-1)continue;s+=l-s+1;break}i=a}return i},Ws=e=>e?.replace("_","-"),wx={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console?.[e]?.apply?.(console,t)}};class Hc{constructor(t,n={}){this.init(t,n)}init(t,n={}){this.prefix=n.prefix||"i18next:",this.logger=t||wx,this.options=n,this.debug=n.debug}log(...t){return this.forward(t,"log","",!0)}warn(...t){return this.forward(t,"warn","",!0)}error(...t){return this.forward(t,"error","")}deprecate(...t){return this.forward(t,"warn","WARNING DEPRECATED: ",!0)}forward(t,n,r,i){return i&&!this.debug?null:(_e(t[0])&&(t[0]=`${r}${this.prefix} ${t[0]}`),this.logger[n](t))}create(t){return new Hc(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return t=t||this.options,t.prefix=t.prefix||this.prefix,new Hc(this.logger,t)}}var zn=new Hc;class au{constructor(){this.observers={}}on(t,n){return t.split(" ").forEach(r=>{this.observers[r]||(this.observers[r]=new Map);const i=this.observers[r].get(n)||0;this.observers[r].set(n,i+1)}),this}off(t,n){if(this.observers[t]){if(!n){delete this.observers[t];return}this.observers[t].delete(n)}}emit(t,...n){this.observers[t]&&Array.from(this.observers[t].entries()).forEach(([i,s])=>{for(let a=0;a<s;a++)i(...n)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([i,s])=>{for(let a=0;a<s;a++)i.apply(i,[t,...n])})}}class pm extends au{constructor(t,n={ns:["translation"],defaultNS:"translation"}){super(),this.data=t||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){const n=this.options.ns.indexOf(t);n>-1&&this.options.ns.splice(n,1)}getResource(t,n,r,i={}){const s=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,a=i.ignoreJSONStructure!==void 0?i.ignoreJSONStructure:this.options.ignoreJSONStructure;let c;t.indexOf(".")>-1?c=t.split("."):(c=[t,n],r&&(Array.isArray(r)?c.push(...r):_e(r)&&s?c.push(...r.split(s)):c.push(r)));const l=Fc(this.data,c);return!l&&!n&&!r&&t.indexOf(".")>-1&&(t=c[0],n=c[1],r=c.slice(2).join(".")),l||!a||!_e(r)?l:of(this.data?.[t]?.[n],r,s)}addResource(t,n,r,i,s={silent:!1}){const a=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let c=[t,n];r&&(c=c.concat(a?r.split(a):r)),t.indexOf(".")>-1&&(c=t.split("."),i=n,n=c[1]),this.addNamespaces(n),dm(this.data,c,i),s.silent||this.emit("added",t,n,r,i)}addResources(t,n,r,i={silent:!1}){for(const s in r)(_e(r[s])||Array.isArray(r[s]))&&this.addResource(t,n,s,r[s],{silent:!0});i.silent||this.emit("added",t,n,r)}addResourceBundle(t,n,r,i,s,a={silent:!1,skipCopy:!1}){let c=[t,n];t.indexOf(".")>-1&&(c=t.split("."),i=r,r=n,n=c[1]),this.addNamespaces(n);let l=Fc(this.data,c)||{};a.skipCopy||(r=JSON.parse(JSON.stringify(r))),i?fv(l,r,s):l={...l,...r},dm(this.data,c,l),a.silent||this.emit("added",t,n,r)}removeResourceBundle(t,n){this.hasResourceBundle(t,n)&&delete this.data[t][n],this.removeNamespaces(n),this.emit("removed",t,n)}hasResourceBundle(t,n){return this.getResource(t,n)!==void 0}getResourceBundle(t,n){return n||(n=this.options.defaultNS),this.getResource(t,n)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const n=this.getDataByLanguage(t);return!!(n&&Object.keys(n)||[]).find(i=>n[i]&&Object.keys(n[i]).length>0)}toJSON(){return this.data}}var hv={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,r,i){return e.forEach(s=>{t=this.processors[s]?.process(t,n,r,i)??t}),t}};const _v=Symbol("i18next/PATH_KEY");function kx(){const e=[],t=Object.create(null);let n;return t.get=(r,i)=>(n?.revoke?.(),i===_v?e:(e.push(i),n=Proxy.revocable(r,t),n.proxy)),Proxy.revocable(Object.create(null),t).proxy}function sf(e,t){const{[_v]:n}=e(kx());return n.join(t?.keySeparator??".")}const fm={},Ud=e=>!_e(e)&&typeof e!="boolean"&&typeof e!="number";class Vc extends au{constructor(t,n={}){super(),dx(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=zn.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t,n={interpolation:{}}){const r={...n};if(t==null)return!1;const i=this.resolve(t,r);if(i?.res===void 0)return!1;const s=Ud(i.res);return!(r.returnObjects===!1&&s)}extractFromKey(t,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const i=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let s=n.ns||this.options.defaultNS||[];const a=r&&t.indexOf(r)>-1,c=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!vx(t,r,i);if(a&&!c){const l=t.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:t,namespaces:_e(s)?[s]:s};const u=t.split(r);(r!==i||r===i&&this.options.ns.indexOf(u[0])>-1)&&(s=u.shift()),t=u.join(i)}return{key:t,namespaces:_e(s)?[s]:s}}translate(t,n,r){let i=typeof n=="object"?{...n}:n;if(typeof i!="object"&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof i=="object"&&(i={...i}),i||(i={}),t==null)return"";typeof t=="function"&&(t=sf(t,{...this.options,...i})),Array.isArray(t)||(t=[String(t)]);const s=i.returnDetails!==void 0?i.returnDetails:this.options.returnDetails,a=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,{key:c,namespaces:l}=this.extractFromKey(t[t.length-1],i),u=l[l.length-1];let d=i.nsSeparator!==void 0?i.nsSeparator:this.options.nsSeparator;d===void 0&&(d=":");const f=i.lng||this.language,p=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(f?.toLowerCase()==="cimode")return p?s?{res:`${u}${d}${c}`,usedKey:c,exactUsedKey:c,usedLng:f,usedNS:u,usedParams:this.getUsedParamsDetails(i)}:`${u}${d}${c}`:s?{res:c,usedKey:c,exactUsedKey:c,usedLng:f,usedNS:u,usedParams:this.getUsedParamsDetails(i)}:c;const h=this.resolve(t,i);let _=h?.res;const g=h?.usedKey||c,y=h?.exactUsedKey||c,m=["[object Number]","[object Function]","[object RegExp]"],v=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,k=!this.i18nFormat||this.i18nFormat.handleAsObject,x=i.count!==void 0&&!_e(i.count),b=Vc.hasDefaultValue(i),S=x?this.pluralResolver.getSuffix(f,i.count,i):"",A=i.ordinal&&x?this.pluralResolver.getSuffix(f,i.count,{ordinal:!1}):"",C=x&&!i.ordinal&&i.count===0,P=C&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${S}`]||i[`defaultValue${A}`]||i.defaultValue;let R=_;k&&!_&&b&&(R=P);const E=Ud(R),L=Object.prototype.toString.apply(R);if(k&&R&&E&&m.indexOf(L)<0&&!(_e(v)&&Array.isArray(R))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const M=this.options.returnedObjectHandler?this.options.returnedObjectHandler(g,R,{...i,ns:l}):`key '${c} (${this.language})' returned an object instead of string.`;return s?(h.res=M,h.usedParams=this.getUsedParamsDetails(i),h):M}if(a){const M=Array.isArray(R),H=M?[]:{},D=M?y:g;for(const Q in R)if(Object.prototype.hasOwnProperty.call(R,Q)){const pe=`${D}${a}${Q}`;b&&!_?H[Q]=this.translate(pe,{...i,defaultValue:Ud(P)?P[Q]:void 0,joinArrays:!1,ns:l}):H[Q]=this.translate(pe,{...i,joinArrays:!1,ns:l}),H[Q]===pe&&(H[Q]=R[Q])}_=H}}else if(k&&_e(v)&&Array.isArray(_))_=_.join(v),_&&(_=this.extendTranslation(_,t,i,r));else{let M=!1,H=!1;!this.isValidLookup(_)&&b&&(M=!0,_=P),this.isValidLookup(_)||(H=!0,_=c);const Q=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&H?void 0:_,pe=b&&P!==_&&this.options.updateMissing;if(H||M||pe){if(this.logger.log(pe?"updateKey":"missingKey",f,u,c,pe?P:_),a){const be=this.resolve(c,{...i,keySeparator:!1});be&&be.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let se=[];const we=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&we&&we[0])for(let be=0;be<we.length;be++)se.push(we[be]);else this.options.saveMissingTo==="all"?se=this.languageUtils.toResolveHierarchy(i.lng||this.language):se.push(i.lng||this.language);const le=(be,Ee,V)=>{const Te=b&&V!==_?V:Q;this.options.missingKeyHandler?this.options.missingKeyHandler(be,u,Ee,Te,pe,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(be,u,Ee,Te,pe,i),this.emit("missingKey",be,u,Ee,_)};this.options.saveMissing&&(this.options.saveMissingPlurals&&x?se.forEach(be=>{const Ee=this.pluralResolver.getSuffixes(be,i);C&&i[`defaultValue${this.options.pluralSeparator}zero`]&&Ee.indexOf(`${this.options.pluralSeparator}zero`)<0&&Ee.push(`${this.options.pluralSeparator}zero`),Ee.forEach(V=>{le([be],c+V,i[`defaultValue${V}`]||P)})}):le(se,c,P))}_=this.extendTranslation(_,t,i,h,r),H&&_===c&&this.options.appendNamespaceToMissingKey&&(_=`${u}${d}${c}`),(H||M)&&this.options.parseMissingKeyHandler&&(_=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${u}${d}${c}`:c,M?_:void 0,i))}return s?(h.res=_,h.usedParams=this.getUsedParamsDetails(i),h):_}extendTranslation(t,n,r,i,s){if(this.i18nFormat?.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const l=_e(t)&&(r?.interpolation?.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let u;if(l){const f=t.match(this.interpolator.nestingRegexp);u=f&&f.length}let d=r.replace&&!_e(r.replace)?r.replace:r;if(this.options.interpolation.defaultVariables&&(d={...this.options.interpolation.defaultVariables,...d}),t=this.interpolator.interpolate(t,d,r.lng||this.language||i.usedLng,r),l){const f=t.match(this.interpolator.nestingRegexp),p=f&&f.length;u<p&&(r.nest=!1)}!r.lng&&i&&i.res&&(r.lng=this.language||i.usedLng),r.nest!==!1&&(t=this.interpolator.nest(t,(...f)=>s?.[0]===f[0]&&!r.context?(this.logger.warn(`It seems you are nesting recursively key: ${f[0]} in key: ${n[0]}`),null):this.translate(...f,n),r)),r.interpolation&&this.interpolator.reset()}const a=r.postProcess||this.options.postProcess,c=_e(a)?[a]:a;return t!=null&&c?.length&&r.applyPostProcessor!==!1&&(t=hv.handle(c,t,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(r)},...r}:r,this)),t}resolve(t,n={}){let r,i,s,a,c;return _e(t)&&(t=[t]),t.forEach(l=>{if(this.isValidLookup(r))return;const u=this.extractFromKey(l,n),d=u.key;i=d;let f=u.namespaces;this.options.fallbackNS&&(f=f.concat(this.options.fallbackNS));const p=n.count!==void 0&&!_e(n.count),h=p&&!n.ordinal&&n.count===0,_=n.context!==void 0&&(_e(n.context)||typeof n.context=="number")&&n.context!=="",g=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);f.forEach(y=>{this.isValidLookup(r)||(c=y,!fm[`${g[0]}-${y}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(c)&&(fm[`${g[0]}-${y}`]=!0,this.logger.warn(`key "${i}" for languages "${g.join(", ")}" won't get resolved as namespace "${c}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),g.forEach(m=>{if(this.isValidLookup(r))return;a=m;const v=[d];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(v,d,m,y,n);else{let x;p&&(x=this.pluralResolver.getSuffix(m,n.count,n));const b=`${this.options.pluralSeparator}zero`,S=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(n.ordinal&&x.indexOf(S)===0&&v.push(d+x.replace(S,this.options.pluralSeparator)),v.push(d+x),h&&v.push(d+b)),_){const A=`${d}${this.options.contextSeparator||"_"}${n.context}`;v.push(A),p&&(n.ordinal&&x.indexOf(S)===0&&v.push(A+x.replace(S,this.options.pluralSeparator)),v.push(A+x),h&&v.push(A+b))}}let k;for(;k=v.pop();)this.isValidLookup(r)||(s=k,r=this.getResource(m,y,k,n))}))})}),{res:r,usedKey:i,exactUsedKey:s,usedLng:a,usedNS:c}}isValidLookup(t){return t!==void 0&&!(!this.options.returnNull&&t===null)&&!(!this.options.returnEmptyString&&t==="")}getResource(t,n,r,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(t,n,r,i):this.resourceStore.getResource(t,n,r,i)}getUsedParamsDetails(t={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=t.replace&&!_e(t.replace);let i=r?t.replace:t;if(r&&typeof t.count<"u"&&(i.count=t.count),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!r){i={...i};for(const s of n)delete i[s]}return i}static hasDefaultValue(t){const n="defaultValue";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&n===r.substring(0,n.length)&&t[r]!==void 0)return!0;return!1}}class hm{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=zn.create("languageUtils")}getScriptPartFromCode(t){if(t=Ws(t),!t||t.indexOf("-")<0)return null;const n=t.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(t){if(t=Ws(t),!t||t.indexOf("-")<0)return t;const n=t.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(t){if(_e(t)&&t.indexOf("-")>-1){let n;try{n=Intl.getCanonicalLocales(t)[0]}catch{}return n&&this.options.lowerCaseLng&&(n=n.toLowerCase()),n||(this.options.lowerCaseLng?t.toLowerCase():t)}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let n;return t.forEach(r=>{if(n)return;const i=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(i))&&(n=i)}),!n&&this.options.supportedLngs&&t.forEach(r=>{if(n)return;const i=this.getScriptPartFromCode(r);if(this.isSupportedCode(i))return n=i;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(a=>{if(a===s)return a;if(!(a.indexOf("-")<0&&s.indexOf("-")<0)&&(a.indexOf("-")>0&&s.indexOf("-")<0&&a.substring(0,a.indexOf("-"))===s||a.indexOf(s)===0&&s.length>1))return a})}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(t,n){if(!t)return[];if(typeof t=="function"&&(t=t(n)),_e(t)&&(t=[t]),Array.isArray(t))return t;if(!n)return t.default||[];let r=t[n];return r||(r=t[this.getScriptPartFromCode(n)]),r||(r=t[this.formatLanguageCode(n)]),r||(r=t[this.getLanguagePartFromCode(n)]),r||(r=t.default),r||[]}toResolveHierarchy(t,n){const r=this.getFallbackCodes((n===!1?[]:n)||this.options.fallbackLng||[],t),i=[],s=a=>{a&&(this.isSupportedCode(a)?i.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return _e(t)&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&s(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&s(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&s(this.getLanguagePartFromCode(t))):_e(t)&&s(this.formatLanguageCode(t)),r.forEach(a=>{i.indexOf(a)<0&&s(this.formatLanguageCode(a))}),i}}const _m={zero:0,one:1,two:2,few:3,many:4,other:5},mm={select:e=>e===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class $x{constructor(t,n={}){this.languageUtils=t,this.options=n,this.logger=zn.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(t,n={}){const r=Ws(t==="dev"?"en":t),i=n.ordinal?"ordinal":"cardinal",s=JSON.stringify({cleanedCode:r,type:i});if(s in this.pluralRulesCache)return this.pluralRulesCache[s];let a;try{a=new Intl.PluralRules(r,{type:i})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),mm;if(!t.match(/-|_/))return mm;const l=this.languageUtils.getLanguagePartFromCode(t);a=this.getRule(l,n)}return this.pluralRulesCache[s]=a,a}needsPlural(t,n={}){let r=this.getRule(t,n);return r||(r=this.getRule("dev",n)),r?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(t,n,r={}){return this.getSuffixes(t,r).map(i=>`${n}${i}`)}getSuffixes(t,n={}){let r=this.getRule(t,n);return r||(r=this.getRule("dev",n)),r?r.resolvedOptions().pluralCategories.sort((i,s)=>_m[i]-_m[s]).map(i=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i}`):[]}getSuffix(t,n,r={}){const i=this.getRule(t,r);return i?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${i.select(n)}`:(this.logger.warn(`no plural rule found for: ${t}`),this.getSuffix("dev",n,r))}}const gm=(e,t,n,r=".",i=!0)=>{let s=hx(e,t,n);return!s&&i&&_e(n)&&(s=of(e,n,r),s===void 0&&(s=of(t,n,r))),s},Bd=e=>e.replace(/\$/g,"$$$$");class ym{constructor(t={}){this.logger=zn.create("interpolator"),this.options=t,this.format=t?.interpolation?.format||(n=>n),this.init(t)}init(t={}){t.interpolation||(t.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:i,prefix:s,prefixEscaped:a,suffix:c,suffixEscaped:l,formatSeparator:u,unescapeSuffix:d,unescapePrefix:f,nestingPrefix:p,nestingPrefixEscaped:h,nestingSuffix:_,nestingSuffixEscaped:g,nestingOptionsSeparator:y,maxReplaces:m,alwaysFormat:v}=t.interpolation;this.escape=n!==void 0?n:mx,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=s?Vr(s):a||"{{",this.suffix=c?Vr(c):l||"}}",this.formatSeparator=u||",",this.unescapePrefix=d?"":f||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=p?Vr(p):h||Vr("$t("),this.nestingSuffix=_?Vr(_):g||Vr(")"),this.nestingOptionsSeparator=y||",",this.maxReplaces=m||1e3,this.alwaysFormat=v!==void 0?v:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=(n,r)=>n?.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=t(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=t(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=t(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(t,n,r,i){let s,a,c;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},u=h=>{if(h.indexOf(this.formatSeparator)<0){const m=gm(n,l,h,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(m,void 0,r,{...i,...n,interpolationkey:h}):m}const _=h.split(this.formatSeparator),g=_.shift().trim(),y=_.join(this.formatSeparator).trim();return this.format(gm(n,l,g,this.options.keySeparator,this.options.ignoreJSONStructure),y,r,{...i,...n,interpolationkey:g})};this.resetRegExp();const d=i?.missingInterpolationHandler||this.options.missingInterpolationHandler,f=i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:h=>Bd(h)},{regex:this.regexp,safeValue:h=>this.escapeValue?Bd(this.escape(h)):Bd(h)}].forEach(h=>{for(c=0;s=h.regex.exec(t);){const _=s[1].trim();if(a=u(_),a===void 0)if(typeof d=="function"){const y=d(t,s,i);a=_e(y)?y:""}else if(i&&Object.prototype.hasOwnProperty.call(i,_))a="";else if(f){a=s[0];continue}else this.logger.warn(`missed to pass in variable ${_} for interpolating ${t}`),a="";else!_e(a)&&!this.useRawValueToEscape&&(a=cm(a));const g=h.safeValue(a);if(t=t.replace(s[0],g),f?(h.regex.lastIndex+=a.length,h.regex.lastIndex-=s[0].length):h.regex.lastIndex=0,c++,c>=this.maxReplaces)break}}),t}nest(t,n,r={}){let i,s,a;const c=(l,u)=>{const d=this.nestingOptionsSeparator;if(l.indexOf(d)<0)return l;const f=l.split(new RegExp(`${Vr(d)}[ ]*{`));let p=`{${f[1]}`;l=f[0],p=this.interpolate(p,a);const h=p.match(/'/g),_=p.match(/"/g);((h?.length??0)%2===0&&!_||(_?.length??0)%2!==0)&&(p=p.replace(/'/g,'"'));try{a=JSON.parse(p),u&&(a={...u,...a})}catch(g){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,g),`${l}${d}${p}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,l};for(;i=this.nestingRegexp.exec(t);){let l=[];a={...r},a=a.replace&&!_e(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;const u=/{.*}/.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(u!==-1&&(l=i[1].slice(u).split(this.formatSeparator).map(d=>d.trim()).filter(Boolean),i[1]=i[1].slice(0,u)),s=n(c.call(this,i[1].trim(),a),a),s&&i[0]===t&&!_e(s))return s;_e(s)||(s=cm(s)),s||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${t}`),s=""),l.length&&(s=l.reduce((d,f)=>this.format(d,f,r.lng,{...r,interpolationkey:i[1].trim()}),s.trim())),t=t.replace(i[0],s),this.regexp.lastIndex=0}return t}}const xx=e=>{let t=e.toLowerCase().trim();const n={};if(e.indexOf("(")>-1){const r=e.split("(");t=r[0].toLowerCase().trim();const i=r[1].substring(0,r[1].length-1);t==="currency"&&i.indexOf(":")<0?n.currency||(n.currency=i.trim()):t==="relativetime"&&i.indexOf(":")<0?n.range||(n.range=i.trim()):i.split(";").forEach(a=>{if(a){const[c,...l]=a.split(":"),u=l.join(":").trim().replace(/^'+|'+$/g,""),d=c.trim();n[d]||(n[d]=u),u==="false"&&(n[d]=!1),u==="true"&&(n[d]=!0),isNaN(u)||(n[d]=parseInt(u,10))}})}return{formatName:t,formatOptions:n}},bm=e=>{const t={};return(n,r,i)=>{let s=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(s={...s,[i.interpolationkey]:void 0});const a=r+JSON.stringify(s);let c=t[a];return c||(c=e(Ws(r),i),t[a]=c),c(n)}},Sx=e=>(t,n,r)=>e(Ws(n),r)(t);class zx{constructor(t={}){this.logger=zn.create("formatter"),this.options=t,this.init(t)}init(t,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const r=n.cacheInBuiltFormats?bm:Sx;this.formats={number:r((i,s)=>{const a=new Intl.NumberFormat(i,{...s});return c=>a.format(c)}),currency:r((i,s)=>{const a=new Intl.NumberFormat(i,{...s,style:"currency"});return c=>a.format(c)}),datetime:r((i,s)=>{const a=new Intl.DateTimeFormat(i,{...s});return c=>a.format(c)}),relativetime:r((i,s)=>{const a=new Intl.RelativeTimeFormat(i,{...s});return c=>a.format(c,s.range||"day")}),list:r((i,s)=>{const a=new Intl.ListFormat(i,{...s});return c=>a.format(c)})}}add(t,n){this.formats[t.toLowerCase().trim()]=n}addCached(t,n){this.formats[t.toLowerCase().trim()]=bm(n)}format(t,n,r,i={}){const s=n.split(this.formatSeparator);if(s.length>1&&s[0].indexOf("(")>1&&s[0].indexOf(")")<0&&s.find(c=>c.indexOf(")")>-1)){const c=s.findIndex(l=>l.indexOf(")")>-1);s[0]=[s[0],...s.splice(1,c)].join(this.formatSeparator)}return s.reduce((c,l)=>{const{formatName:u,formatOptions:d}=xx(l);if(this.formats[u]){let f=c;try{const p=i?.formatParams?.[i.interpolationkey]||{},h=p.locale||p.lng||i.locale||i.lng||r;f=this.formats[u](c,h,{...d,...i,...p})}catch(p){this.logger.warn(p)}return f}else this.logger.warn(`there was no format function for ${u}`);return c},t)}}const Ax=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)};class Ex extends au{constructor(t,n,r,i={}){super(),this.backend=t,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=i,this.logger=zn.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=i.maxParallelReads||10,this.readingCalls=0,this.maxRetries=i.maxRetries>=0?i.maxRetries:5,this.retryTimeout=i.retryTimeout>=1?i.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(r,i.backend,i)}queueLoad(t,n,r,i){const s={},a={},c={},l={};return t.forEach(u=>{let d=!0;n.forEach(f=>{const p=`${u}|${f}`;!r.reload&&this.store.hasResourceBundle(u,f)?this.state[p]=2:this.state[p]<0||(this.state[p]===1?a[p]===void 0&&(a[p]=!0):(this.state[p]=1,d=!1,a[p]===void 0&&(a[p]=!0),s[p]===void 0&&(s[p]=!0),l[f]===void 0&&(l[f]=!0)))}),d||(c[u]=!0)}),(Object.keys(s).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(s),pending:Object.keys(a),toLoadLanguages:Object.keys(c),toLoadNamespaces:Object.keys(l)}}loaded(t,n,r){const i=t.split("|"),s=i[0],a=i[1];n&&this.emit("failedLoading",s,a,n),!n&&r&&this.store.addResourceBundle(s,a,r,void 0,void 0,{skipCopy:!0}),this.state[t]=n?-1:2,n&&r&&(this.state[t]=0);const c={};this.queue.forEach(l=>{fx(l.loaded,[s],a),Ax(l,t),n&&l.errors.push(n),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(u=>{c[u]||(c[u]={});const d=l.loaded[u];d.length&&d.forEach(f=>{c[u][f]===void 0&&(c[u][f]=!0)})}),l.done=!0,l.errors.length?l.callback(l.errors):l.callback())}),this.emit("loaded",c),this.queue=this.queue.filter(l=>!l.done)}read(t,n,r,i=0,s=this.retryTimeout,a){if(!t.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:t,ns:n,fcName:r,tried:i,wait:s,callback:a});return}this.readingCalls++;const c=(u,d)=>{if(this.readingCalls--,this.waitingReads.length>0){const f=this.waitingReads.shift();this.read(f.lng,f.ns,f.fcName,f.tried,f.wait,f.callback)}if(u&&d&&i<this.maxRetries){setTimeout(()=>{this.read.call(this,t,n,r,i+1,s*2,a)},s);return}a(u,d)},l=this.backend[r].bind(this.backend);if(l.length===2){try{const u=l(t,n);u&&typeof u.then=="function"?u.then(d=>c(null,d)).catch(c):c(null,u)}catch(u){c(u)}return}return l(t,n,c)}prepareLoading(t,n,r={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();_e(t)&&(t=this.languageUtils.toResolveHierarchy(t)),_e(n)&&(n=[n]);const s=this.queueLoad(t,n,r,i);if(!s.toLoad.length)return s.pending.length||i(),null;s.toLoad.forEach(a=>{this.loadOne(a)})}load(t,n,r){this.prepareLoading(t,n,{},r)}reload(t,n,r){this.prepareLoading(t,n,{reload:!0},r)}loadOne(t,n=""){const r=t.split("|"),i=r[0],s=r[1];this.read(i,s,"read",void 0,void 0,(a,c)=>{a&&this.logger.warn(`${n}loading namespace ${s} for language ${i} failed`,a),!a&&c&&this.logger.log(`${n}loaded namespace ${s} for language ${i}`,c),this.loaded(t,a,c)})}saveMissing(t,n,r,i,s,a={},c=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if(this.backend?.create){const l={...a,isUpdate:s},u=this.backend.create.bind(this.backend);if(u.length<6)try{let d;u.length===5?d=u(t,n,r,i,l):d=u(t,n,r,i),d&&typeof d.then=="function"?d.then(f=>c(null,f)).catch(c):c(null,d)}catch(d){c(d)}else u(t,n,r,i,c,l)}!t||!t[0]||this.store.addResource(t[0],n,r,i)}}}const Md=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]=="object"&&(t=e[1]),_e(e[1])&&(t.defaultValue=e[1]),_e(e[2])&&(t.tDescription=e[2]),typeof e[2]=="object"||typeof e[3]=="object"){const n=e[3]||e[2];Object.keys(n).forEach(r=>{t[r]=n[r]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),vm=e=>(_e(e.ns)&&(e.ns=[e.ns]),_e(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),_e(e.fallbackNS)&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs?.indexOf?.("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),typeof e.initImmediate=="boolean"&&(e.initAsync=e.initImmediate),e),oc=()=>{},Cx=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(n=>{typeof e[n]=="function"&&(e[n]=e[n].bind(e))})},mv="__i18next_supportNoticeShown",Ix=()=>typeof globalThis<"u"&&!!globalThis[mv],jx=()=>{typeof globalThis<"u"&&(globalThis[mv]=!0)},Nx=e=>!!(e?.modules?.backend?.name?.indexOf("Locize")>0||e?.modules?.backend?.constructor?.name?.indexOf("Locize")>0||e?.options?.backend?.backends&&e.options.backend.backends.some(t=>t?.name?.indexOf("Locize")>0||t?.constructor?.name?.indexOf("Locize")>0)||e?.options?.backend?.projectId||e?.options?.backend?.backendOptions&&e.options.backend.backendOptions.some(t=>t?.projectId));class Ps extends au{constructor(t={},n){if(super(),this.options=vm(t),this.services={},this.logger=zn,this.modules={external:[]},Cx(this),n&&!this.isInitialized&&!t.isClone){if(!this.options.initAsync)return this.init(t,n),this;setTimeout(()=>{this.init(t,n)},0)}}init(t={},n){this.isInitializing=!0,typeof t=="function"&&(n=t,t={}),t.defaultNS==null&&t.ns&&(_e(t.ns)?t.defaultNS=t.ns:t.ns.indexOf("translation")<0&&(t.defaultNS=t.ns[0]));const r=Md();this.options={...r,...this.options,...vm(t)},this.options.interpolation={...r.interpolation,...this.options.interpolation},t.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=t.keySeparator),t.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=t.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=r.overloadTranslationOptionHandler),this.options.showSupportNotice!==!1&&!Nx(this)&&!Ix()&&(typeof console<"u"&&typeof console.info<"u"&&console.info("🌐 i18next is maintained with support from Locize — consider powering your project with managed localization (AI, CDN, integrations): https://locize.com 💙"),jx());const i=u=>u?typeof u=="function"?new u:u:null;if(!this.options.isClone){this.modules.logger?zn.init(i(this.modules.logger),this.options):zn.init(null,this.options);let u;this.modules.formatter?u=this.modules.formatter:u=zx;const d=new hm(this.options);this.store=new pm(this.options.resources,this.options);const f=this.services;f.logger=zn,f.resourceStore=this.store,f.languageUtils=d,f.pluralResolver=new $x(d,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==r.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),u&&(!this.options.interpolation.format||this.options.interpolation.format===r.interpolation.format)&&(f.formatter=i(u),f.formatter.init&&f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new ym(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new Ex(i(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",(h,..._)=>{this.emit(h,..._)}),this.modules.languageDetector&&(f.languageDetector=i(this.modules.languageDetector),f.languageDetector.init&&f.languageDetector.init(f,this.options.detection,this.options)),this.modules.i18nFormat&&(f.i18nFormat=i(this.modules.i18nFormat),f.i18nFormat.init&&f.i18nFormat.init(this)),this.translator=new Vc(this.services,this.options),this.translator.on("*",(h,..._)=>{this.emit(h,..._)}),this.modules.external.forEach(h=>{h.init&&h.init(this)})}if(this.format=this.options.interpolation.format,n||(n=oc),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const u=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);u.length>0&&u[0]!=="dev"&&(this.options.lng=u[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(u=>{this[u]=(...d)=>this.store[u](...d)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(u=>{this[u]=(...d)=>(this.store[u](...d),this)});const c=os(),l=()=>{const u=(d,f)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),c.resolve(f),n(d,f)};if(this.languages&&!this.isInitialized)return u(null,this.t.bind(this));this.changeLanguage(this.options.lng,u)};return this.options.resources||!this.options.initAsync?l():setTimeout(l,0),c}loadResources(t,n=oc){let r=n;const i=_e(t)?t:this.language;if(typeof t=="function"&&(r=t),!this.options.resources||this.options.partialBundledLanguages){if(i?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const s=[],a=c=>{if(!c||c==="cimode")return;this.services.languageUtils.toResolveHierarchy(c).forEach(u=>{u!=="cimode"&&s.indexOf(u)<0&&s.push(u)})};i?a(i):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(l=>a(l)),this.options.preload?.forEach?.(c=>a(c)),this.services.backendConnector.load(s,this.options.ns,c=>{!c&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(c)})}else r(null)}reloadResources(t,n,r){const i=os();return typeof t=="function"&&(r=t,t=void 0),typeof n=="function"&&(r=n,n=void 0),t||(t=this.languages),n||(n=this.options.ns),r||(r=oc),this.services.backendConnector.reload(t,n,s=>{i.resolve(),r(s)}),i}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return t.type==="backend"&&(this.modules.backend=t),(t.type==="logger"||t.log&&t.warn&&t.error)&&(this.modules.logger=t),t.type==="languageDetector"&&(this.modules.languageDetector=t),t.type==="i18nFormat"&&(this.modules.i18nFormat=t),t.type==="postProcessor"&&hv.addPostProcessor(t),t.type==="formatter"&&(this.modules.formatter=t),t.type==="3rdParty"&&this.modules.external.push(t),this}setResolvedLanguage(t){if(!(!t||!this.languages)&&!(["cimode","dev"].indexOf(t)>-1)){for(let n=0;n<this.languages.length;n++){const r=this.languages[n];if(!(["cimode","dev"].indexOf(r)>-1)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}!this.resolvedLanguage&&this.languages.indexOf(t)<0&&this.store.hasLanguageSomeTranslations(t)&&(this.resolvedLanguage=t,this.languages.unshift(t))}}changeLanguage(t,n){this.isLanguageChangingTo=t;const r=os();this.emit("languageChanging",t);const i=c=>{this.language=c,this.languages=this.services.languageUtils.toResolveHierarchy(c),this.resolvedLanguage=void 0,this.setResolvedLanguage(c)},s=(c,l)=>{l?this.isLanguageChangingTo===t&&(i(l),this.translator.changeLanguage(l),this.isLanguageChangingTo=void 0,this.emit("languageChanged",l),this.logger.log("languageChanged",l)):this.isLanguageChangingTo=void 0,r.resolve((...u)=>this.t(...u)),n&&n(c,(...u)=>this.t(...u))},a=c=>{!t&&!c&&this.services.languageDetector&&(c=[]);const l=_e(c)?c:c&&c[0],u=this.store.hasLanguageSomeTranslations(l)?l:this.services.languageUtils.getBestMatchFromCodes(_e(c)?[c]:c);u&&(this.language||i(u),this.translator.language||this.translator.changeLanguage(u),this.services.languageDetector?.cacheUserLanguage?.(u)),this.loadResources(u,d=>{s(d,u)})};return!t&&this.services.languageDetector&&!this.services.languageDetector.async?a(this.services.languageDetector.detect()):!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(t),r}getFixedT(t,n,r){const i=(s,a,...c)=>{let l;typeof a!="object"?l=this.options.overloadTranslationOptionHandler([s,a].concat(c)):l={...a},l.lng=l.lng||i.lng,l.lngs=l.lngs||i.lngs,l.ns=l.ns||i.ns,l.keyPrefix!==""&&(l.keyPrefix=l.keyPrefix||r||i.keyPrefix);const u=this.options.keySeparator||".";let d;return l.keyPrefix&&Array.isArray(s)?d=s.map(f=>(typeof f=="function"&&(f=sf(f,{...this.options,...a})),`${l.keyPrefix}${u}${f}`)):(typeof s=="function"&&(s=sf(s,{...this.options,...a})),d=l.keyPrefix?`${l.keyPrefix}${u}${s}`:s),this.t(d,l)};return _e(t)?i.lng=t:i.lngs=t,i.ns=n,i.keyPrefix=r,i}t(...t){return this.translator?.translate(...t)}exists(...t){return this.translator?.exists(...t)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t,n={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],i=this.options?this.options.fallbackLng:!1,s=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const a=(c,l)=>{const u=this.services.backendConnector.state[`${c}|${l}`];return u===-1||u===0||u===2};if(n.precheck){const c=n.precheck(this,a);if(c!==void 0)return c}return!!(this.hasResourceBundle(r,t)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(r,t)&&(!i||a(s,t)))}loadNamespaces(t,n){const r=os();return this.options.ns?(_e(t)&&(t=[t]),t.forEach(i=>{this.options.ns.indexOf(i)<0&&this.options.ns.push(i)}),this.loadResources(i=>{r.resolve(),n&&n(i)}),r):(n&&n(),Promise.resolve())}loadLanguages(t,n){const r=os();_e(t)&&(t=[t]);const i=this.options.preload||[],s=t.filter(a=>i.indexOf(a)<0&&this.services.languageUtils.isSupportedCode(a));return s.length?(this.options.preload=i.concat(s),this.loadResources(a=>{r.resolve(),n&&n(a)}),r):(n&&n(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!t)return"rtl";try{const i=new Intl.Locale(t);if(i&&i.getTextInfo){const s=i.getTextInfo();if(s&&s.direction)return s.direction}}catch{}const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=this.services?.languageUtils||new hm(Md());return t.toLowerCase().indexOf("-latn")>1?"ltr":n.indexOf(r.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(t={},n){const r=new Ps(t,n);return r.createInstance=Ps.createInstance,r}cloneInstance(t={},n=oc){const r=t.forkResourceStore;r&&delete t.forkResourceStore;const i={...this.options,...t,isClone:!0},s=new Ps(i);if((t.debug!==void 0||t.prefix!==void 0)&&(s.logger=s.logger.clone(t)),["store","services","language"].forEach(c=>{s[c]=this[c]}),s.services={...this.services},s.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},r){const c=Object.keys(this.store.data).reduce((l,u)=>(l[u]={...this.store.data[u]},l[u]=Object.keys(l[u]).reduce((d,f)=>(d[f]={...l[u][f]},d),l[u]),l),{});s.store=new pm(c,i),s.services.resourceStore=s.store}if(t.interpolation){const l={...Md().interpolation,...this.options.interpolation,...t.interpolation},u={...i,interpolation:l};s.services.interpolator=new ym(u)}return s.translator=new Vc(s.services,i),s.translator.on("*",(c,...l)=>{s.emit(c,...l)}),s.init(i,n),s.translator.options=i,s.translator.backendConnector.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},s}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const T=Ps.createInstance();T.createInstance;T.dir;T.init;T.loadResources;T.reloadResources;T.use;T.changeLanguage;T.getFixedT;const he=T.t;T.exists;T.setDefaultNamespace;T.hasLoadedNamespace;T.loadNamespaces;T.loadLanguages;const jr=o.z.object({created_at:o.z.string(),updated_at:o.z.string()}),Tx=o.z.enum(["AUTH0","EMAIL","REDIRECT"]),Px=o.z.enum(["CREATE_USER","GET_USER","UPDATE_USER","SEND_REQUEST","SEND_EMAIL"]),Ox=o.z.enum(["VERIFY_EMAIL"]),gv=o.z.object({require_mx_record:o.z.boolean().optional(),block_aliases:o.z.boolean().optional(),block_free_emails:o.z.boolean().optional(),block_disposable_emails:o.z.boolean().optional(),blocklist:o.z.array(o.z.string()).optional(),allowlist:o.z.array(o.z.string()).optional()}),yv=o.z.object({id:o.z.string(),alias:o.z.string().max(100).optional(),type:o.z.literal("AUTH0"),action:o.z.literal("UPDATE_USER"),allow_failure:o.z.boolean().optional(),mask_output:o.z.boolean().optional(),params:o.z.object({connection_id:o.z.string().optional(),user_id:o.z.string(),changes:o.z.record(o.z.string(),o.z.any())})}),bv=o.z.object({id:o.z.string(),alias:o.z.string().max(100).optional(),type:o.z.literal("EMAIL"),action:o.z.literal("VERIFY_EMAIL"),allow_failure:o.z.boolean().optional(),mask_output:o.z.boolean().optional(),params:o.z.object({email:o.z.string(),rules:gv.optional()})}),vv=o.z.enum(["change-email","account","custom"]),wv=o.z.object({id:o.z.string(),alias:o.z.string().max(100).optional(),type:o.z.literal("REDIRECT"),action:o.z.literal("REDIRECT_USER"),allow_failure:o.z.boolean().optional(),mask_output:o.z.boolean().optional(),params:o.z.object({target:vv.openapi({description:"The predefined target to redirect to, or 'custom' for a custom URL"}),custom_url:o.z.string().optional().openapi({description:"Custom URL to redirect to when target is 'custom'"})})}),kv=o.z.union([yv,bv,wv]),Kc=o.z.object({name:o.z.string().min(1).max(150).openapi({description:"The name of the flow"}),actions:o.z.array(kv).optional().default([]).openapi({description:"The list of actions to execute in sequence"})}),Qi=Kc.extend({...jr.shape,id:o.z.string().openapi({description:"Unique identifier for the flow",example:"af_12tMpdJ3iek7svMyZkSh5M"})}),Rx=o.z.object({page:o.z.string().min(0).optional().default("0").transform(e=>parseInt(e,10)).openapi({description:"The page number where 0 is the first page"}),per_page:o.z.string().min(1).optional().default("10").transform(e=>parseInt(e,10)).openapi({description:"The number of items per page"}),include_totals:o.z.string().optional().default("false").transform(e=>e==="true").openapi({description:"If the total number of items should be included in the response"}),sort:o.z.string().regex(/^.+:(-1|1)$/).optional().openapi({description:"A property that should have the format 'string:-1' or 'string:1'"}),q:o.z.string().optional().openapi({description:"A lucene query string used to filter the results"})}),It=o.z.object({start:o.z.number(),limit:o.z.number(),length:o.z.number(),total:o.z.number().optional()}),$v=o.z.object({email:o.z.string().optional(),email_verified:o.z.boolean().optional(),name:o.z.string().optional(),username:o.z.string().optional(),given_name:o.z.string().optional(),phone_number:o.z.string().optional(),phone_verified:o.z.boolean().optional(),family_name:o.z.string().optional()}).catchall(o.z.any()),Gc=o.z.object({connection:o.z.string(),user_id:o.z.string(),provider:o.z.string(),isSocial:o.z.boolean(),email:o.z.string().optional(),email_verified:o.z.boolean().optional(),phone_number:o.z.string().optional(),phone_verified:o.z.boolean().optional(),username:o.z.string().optional(),access_token:o.z.string().optional(),access_token_secret:o.z.string().optional(),refresh_token:o.z.string().optional(),profileData:$v.optional()}),xv=o.z.object({formatted:o.z.string().optional(),street_address:o.z.string().optional(),locality:o.z.string().optional(),region:o.z.string().optional(),postal_code:o.z.string().optional(),country:o.z.string().optional()}).optional(),cu=o.z.object({email:o.z.string().optional().transform(e=>e&&e.toLowerCase()),username:o.z.string().refine(e=>!e.includes("@"),{message:'Usernames must not contain "@". Use the email field for email addresses.'}).optional(),phone_number:o.z.string().optional(),phone_verified:o.z.boolean().optional(),given_name:o.z.string().optional(),family_name:o.z.string().optional(),nickname:o.z.string().optional(),name:o.z.string().optional(),picture:o.z.string().optional(),locale:o.z.string().optional(),linked_to:o.z.string().optional(),profileData:o.z.string().optional(),user_id:o.z.string().optional(),app_metadata:o.z.any().default({}).optional(),user_metadata:o.z.any().default({}).optional(),middle_name:o.z.string().optional(),preferred_username:o.z.string().optional(),profile:o.z.string().optional(),website:o.z.string().optional(),gender:o.z.string().optional(),birthdate:o.z.string().optional(),zoneinfo:o.z.string().optional(),address:xv}),Wc=cu.extend({email_verified:o.z.boolean().default(!1),verify_email:o.z.boolean().optional(),last_ip:o.z.string().optional(),last_login:o.z.string().optional(),user_id:o.z.string().optional(),provider:o.z.string().optional(),connection:o.z.string(),is_social:o.z.boolean().optional(),password:o.z.object({hash:o.z.string(),algorithm:o.z.string()}).optional()}),ch=o.z.object({...Wc.omit({password:!0}).shape,...jr.shape,user_id:o.z.string(),provider:o.z.string(),is_social:o.z.boolean(),email:o.z.string().optional(),login_count:o.z.number().default(0),identities:o.z.array(Gc).optional()}),xn=ch,Lx=cu.extend({login_count:o.z.number(),multifactor:o.z.array(o.z.string()).optional(),last_ip:o.z.string().optional(),last_login:o.z.string().optional(),user_id:o.z.string()}).catchall(o.z.any()),Dx="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let Ux=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=Dx[n[e]&63];return t};const Jc=o.z.object({client_id:o.z.string().openapi({description:"ID of this client."}),name:o.z.string().min(1).openapi({description:"Name of this client (min length: 1 character, does not allow < or >)."}),description:o.z.string().max(140).optional().openapi({description:"Free text description of this client (max length: 140 characters)."}),global:o.z.boolean().default(!1).openapi({description:"Whether this is your global 'All Applications' client representing legacy tenant settings (true) or a regular client (false)."}),client_secret:o.z.string().default(()=>Ux()).optional().openapi({description:"Client secret (which you must not make public)."}),app_type:o.z.enum(["native","spa","regular_web","non_interactive","resource_server","express_configuration","rms","box","cloudbees","concur","dropbox","mscrm","echosign","egnyte","newrelic","office365","salesforce","sentry","sharepoint","slack","springcm","zendesk","zoom","sso_integration","oag"]).default("regular_web").optional().openapi({description:"The type of application this client represents"}),logo_uri:o.z.string().url().optional().openapi({description:"URL of the logo to display for this client. Recommended size is 150x150 pixels."}),is_first_party:o.z.boolean().default(!1).openapi({description:"Whether this client a first party client (true) or not (false)."}),oidc_conformant:o.z.boolean().default(!0).openapi({description:"Whether this client conforms to strict OIDC specifications (true) or uses legacy features (false)."}),auth0_conformant:o.z.boolean().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:o.z.array(o.z.string()).default([]).optional().openapi({description:"Comma-separated list of URLs whitelisted for Auth0 to use as a callback to the client after authentication."}),allowed_origins:o.z.array(o.z.string()).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:o.z.array(o.z.string()).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:o.z.array(o.z.string()).default([]).optional().openapi({description:"List of audiences/realms for SAML protocol. Used by the wsfed addon."}),allowed_clients:o.z.array(o.z.string()).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:o.z.array(o.z.string()).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:o.z.array(o.z.string()).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:o.z.record(o.z.any()).default({}).optional().openapi({description:"Native to Web SSO Configuration"}),oidc_logout:o.z.record(o.z.any()).default({}).optional().openapi({description:"Configuration for OIDC backchannel logout"}),grant_types:o.z.array(o.z.string()).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:o.z.record(o.z.any()).default({}).optional().openapi({description:"Configuration related to JWTs for the client."}),signing_keys:o.z.array(o.z.record(o.z.any())).default([]).optional().openapi({description:"Signing certificates associated with this client."}),encryption_key:o.z.record(o.z.any()).default({}).optional().openapi({description:"Encryption used for WsFed responses with this client."}),sso:o.z.boolean().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:o.z.boolean().default(!0).openapi({description:"Whether Single Sign On is disabled (true) or enabled (true). Defaults to true."}),cross_origin_authentication:o.z.boolean().default(!1).openapi({description:"Whether this client can be used to make cross-origin authentication requests (true) or it is not allowed to make such requests (false)."}),cross_origin_loc:o.z.string().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:o.z.boolean().default(!1).openapi({description:"Whether a custom login page is to be used (true) or the default provided login page (false)."}),custom_login_page:o.z.string().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page."}),custom_login_page_preview:o.z.string().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page. (Used on Previews)"}),form_template:o.z.string().optional().openapi({description:"HTML form template to be used for WS-Federation."}),addons:o.z.record(o.z.any()).default({}).optional().openapi({description:"Addons enabled for this client and their associated configurations."}),token_endpoint_auth_method:o.z.enum(["none","client_secret_post","client_secret_basic"]).default("client_secret_basic").optional().openapi({description:"Defines the requested authentication method for the token endpoint. Can be none (public client without a client secret), client_secret_post (client uses HTTP POST parameters), or client_secret_basic (client uses HTTP Basic)."}),client_metadata:o.z.record(o.z.string().max(255)).default({}).optional().openapi({description:'Metadata associated with the client, in the form of an object with string values (max 255 chars). Maximum of 10 metadata properties allowed. Field names (max 255 chars) are alphanumeric and may only include the following special characters: :,-+=_*?"/()<>@ [Tab][Space]'}),mobile:o.z.record(o.z.any()).default({}).optional().openapi({description:"Additional configuration for native mobile apps."}),initiate_login_uri:o.z.string().url().optional().openapi({description:"Initiate login uri, must be https"}),native_social_login:o.z.record(o.z.any()).default({}).optional(),refresh_token:o.z.record(o.z.any()).default({}).optional().openapi({description:"Refresh token configuration"}),default_organization:o.z.record(o.z.any()).default({}).optional().openapi({description:"Defines the default Organization ID and flows"}),organization_usage:o.z.enum(["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:o.z.enum(["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:o.z.record(o.z.any()).default({}).optional().openapi({description:"Defines client authentication methods."}),require_pushed_authorization_requests:o.z.boolean().default(!1).openapi({description:"Makes the use of Pushed Authorization Requests mandatory for this client"}),require_proof_of_possession:o.z.boolean().default(!1).openapi({description:"Makes the use of Proof-of-Possession mandatory for this client"}),signed_request_object:o.z.record(o.z.any()).default({}).optional().openapi({description:"JWT-secured Authorization Requests (JAR) settings."}),compliance_level:o.z.enum(["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:o.z.number().optional().openapi({description:"Specifies how long, in seconds, a Pushed Authorization Request URI remains valid"}),token_quota:o.z.record(o.z.any()).default({}).optional()}),Qr=o.z.object({created_at:o.z.string(),updated_at:o.z.string(),...Jc.shape}),Zc=o.z.object({client_id:o.z.string().min(1).openapi({description:"ID of the client."}),audience:o.z.string().min(1).openapi({description:"The audience (API identifier) of this client grant."}),scope:o.z.array(o.z.string()).optional().openapi({description:"Scopes allowed for this client grant."}),organization_usage:o.z.enum(["deny","allow","require"]).optional().openapi({description:"Defines whether organizations can be used with client credentials exchanges for this grant."}),allow_any_organization:o.z.boolean().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:o.z.boolean().optional().openapi({description:"If enabled, this grant is a special grant created by Auth0. It cannot be modified or deleted directly."}),subject_type:o.z.enum(["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:o.z.array(o.z.string()).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."})}),ei=o.z.object({id:o.z.string().openapi({description:"ID of the client grant."}),...Zc.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),Bx=o.z.array(ei),Ei=o.z.object({x:o.z.number(),y:o.z.number()});var lh=(e=>(e.RICH_TEXT="RICH_TEXT",e.NEXT_BUTTON="NEXT_BUTTON",e.BACK_BUTTON="BACK_BUTTON",e.SUBMIT_BUTTON="SUBMIT_BUTTON",e.DIVIDER="DIVIDER",e.TEXT="TEXT",e.EMAIL="EMAIL",e.PASSWORD="PASSWORD",e.NUMBER="NUMBER",e.PHONE="PHONE",e.DATE="DATE",e.CHECKBOX="CHECKBOX",e.RADIO="RADIO",e.SELECT="SELECT",e.HIDDEN="HIDDEN",e.LEGAL="LEGAL",e))(lh||{}),uh=(e=>(e.BLOCK="BLOCK",e.FIELD="FIELD",e))(uh||{});const lu=o.z.object({id:o.z.string(),category:o.z.nativeEnum(uh),type:o.z.nativeEnum(lh)}),Sv=lu.extend({category:o.z.literal("BLOCK"),type:o.z.literal("RICH_TEXT"),config:o.z.object({content:o.z.string()}).passthrough()}),zv=lu.extend({category:o.z.literal("BLOCK"),type:o.z.union([o.z.literal("NEXT_BUTTON"),o.z.literal("BACK_BUTTON"),o.z.literal("SUBMIT_BUTTON")]),config:o.z.object({text:o.z.string()}).passthrough()}),Av=lu.extend({category:o.z.literal("FIELD"),type:o.z.literal("LEGAL"),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional(),config:o.z.object({text:o.z.string()}).passthrough()}),Ev=lu.extend({category:o.z.literal("FIELD"),type:o.z.union([o.z.literal("TEXT"),o.z.literal("EMAIL"),o.z.literal("PASSWORD"),o.z.literal("NUMBER"),o.z.literal("PHONE"),o.z.literal("DATE"),o.z.literal("CHECKBOX"),o.z.literal("RADIO"),o.z.literal("SELECT"),o.z.literal("HIDDEN")]),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional(),config:o.z.object({label:o.z.string().optional(),placeholder:o.z.string().optional()}).passthrough()}),Cv=o.z.object({id:o.z.string(),category:o.z.string(),type:o.z.string()}).passthrough(),Iv=o.z.union([Sv,zv,Av,Ev,Cv]);var jv=(e=>(e.STEP="STEP",e.FLOW="FLOW",e.CONDITION="CONDITION",e.ACTION="ACTION",e))(jv||{});const Nv=o.z.object({id:o.z.string(),type:o.z.literal("STEP"),coordinates:Ei,alias:o.z.string().optional(),config:o.z.object({components:o.z.array(Iv),next_node:o.z.string()}).passthrough()}),Tv=o.z.object({id:o.z.string(),type:o.z.literal("FLOW"),coordinates:Ei,alias:o.z.string().optional(),config:o.z.object({flow_id:o.z.string(),next_node:o.z.string()})}),Pv=o.z.object({id:o.z.string(),type:o.z.literal("ACTION"),coordinates:Ei,alias:o.z.string().optional(),config:o.z.object({action_type:o.z.enum(["REDIRECT"]).openapi({description:"The type of action to perform"}),target:o.z.enum(["change-email","account","custom"]).openapi({description:"The predefined target to redirect to"}),custom_url:o.z.string().optional().openapi({description:"Custom URL when target is 'custom'"}),next_node:o.z.string().openapi({description:"The next node to navigate to after action (for non-redirect actions)"})}).passthrough()}),Ov=o.z.object({id:o.z.string(),type:o.z.string(),coordinates:Ei}).passthrough(),Rv=o.z.union([Nv,Tv,Pv,Ov]),Lv=o.z.object({next_node:o.z.string(),coordinates:Ei}).passthrough(),Dv=o.z.object({resume_flow:o.z.boolean().optional(),coordinates:Ei}).passthrough(),Uv=o.z.object({id:o.z.string(),name:o.z.string(),languages:o.z.object({primary:o.z.string()}).passthrough(),nodes:o.z.array(Rv),start:Lv,ending:Dv,created_at:o.z.string(),updated_at:o.z.string(),links:o.z.object({sdkSrc:o.z.string().optional(),sdk_src:o.z.string().optional()}).passthrough()}).passthrough(),Mx=Uv.omit({id:!0,created_at:!0,updated_at:!0});var ot=(e=>(e.TOKEN="token",e.ID_TOKEN="id_token",e.TOKEN_ID_TOKEN="token id_token",e.CODE="code",e))(ot||{}),pn=(e=>(e.QUERY="query",e.FRAGMENT="fragment",e.FORM_POST="form_post",e.WEB_MESSAGE="web_message",e.SAML_POST="saml_post",e))(pn||{}),uu=(e=>(e.S256="S256",e.Plain="plain",e))(uu||{});const Js=o.z.object({client_id:o.z.string(),act_as:o.z.string().optional(),response_type:o.z.nativeEnum(ot).optional(),response_mode:o.z.nativeEnum(pn).optional(),redirect_uri:o.z.string().optional(),audience:o.z.string().optional(),organization:o.z.string().optional(),state:o.z.string().optional(),nonce:o.z.string().optional(),scope:o.z.string().optional(),prompt:o.z.string().optional(),code_challenge_method:o.z.nativeEnum(uu).optional(),code_challenge:o.z.string().optional(),username:o.z.string().optional(),ui_locales:o.z.string().optional(),max_age:o.z.number().optional(),acr_values:o.z.string().optional(),vendor_id:o.z.string().optional()}),xc=o.z.object({colors:o.z.object({primary:o.z.string(),page_background:o.z.object({type:o.z.string().optional(),start:o.z.string().optional(),end:o.z.string().optional(),angle_deg:o.z.number().optional()}).optional()}).optional(),logo_url:o.z.string().optional(),favicon_url:o.z.string().optional(),powered_by_logo_url:o.z.string().optional(),font:o.z.object({url:o.z.string()}).optional()}),Bv=o.z.enum(["password_reset","email_verification","otp","authorization_code","oauth2_state","ticket"]),Mv=o.z.object({code_id:o.z.string().openapi({description:"The code that will be used in for instance an email verification flow"}),login_id:o.z.string().openapi({description:"The id of the login session that the code is connected to"}),connection_id:o.z.string().optional().openapi({description:"The connection that the code is connected to"}),code_type:Bv,code_verifier:o.z.string().optional().openapi({description:"The code verifier used in PKCE in outbound flows"}),code_challenge:o.z.string().optional().openapi({description:"The code challenge used in PKCE in outbound flows"}),code_challenge_method:o.z.enum(["plain","S256"]).optional().openapi({description:"The code challenge method used in PKCE in outbound flows"}),redirect_uri:o.z.string().optional().openapi({description:"The redirect URI associated with the code"}),nonce:o.z.string().optional().openapi({description:"The nonce value used for security in OIDC flows"}),state:o.z.string().optional().openapi({description:"The state parameter used for CSRF protection in OAuth flows"}),expires_at:o.z.string(),used_at:o.z.string().optional(),user_id:o.z.string().optional()}),qx=o.z.object({...Mv.shape,created_at:o.z.string()}),qv=o.z.object({kid:o.z.string().optional(),team_id:o.z.string().optional(),realms:o.z.string().optional(),authentication_method:o.z.string().optional(),client_id:o.z.string().optional(),client_secret:o.z.string().optional(),app_secret:o.z.string().optional(),scope:o.z.string().optional(),authorization_endpoint:o.z.string().optional(),token_endpoint:o.z.string().optional(),userinfo_endpoint:o.z.string().optional(),jwks_uri:o.z.string().optional(),discovery_url:o.z.string().optional(),issuer:o.z.string().optional(),provider:o.z.string().optional(),from:o.z.string().optional(),twilio_sid:o.z.string().optional(),twilio_token:o.z.string().optional(),icon_url:o.z.string().optional(),passwordPolicy:o.z.enum(["none","low","fair","good","excellent"]).optional(),password_complexity_options:o.z.object({min_length:o.z.number().optional()}).optional(),password_history:o.z.object({enable:o.z.boolean().optional(),size:o.z.number().optional()}).optional(),password_no_personal_info:o.z.object({enable:o.z.boolean().optional()}).optional(),password_dictionary:o.z.object({enable:o.z.boolean().optional(),dictionary:o.z.array(o.z.string()).optional()}).optional(),disable_signup:o.z.boolean().optional(),brute_force_protection:o.z.boolean().optional(),import_mode:o.z.boolean().optional(),attributes:o.z.object({email:o.z.object({identifier:o.z.object({active:o.z.boolean().optional()}).optional(),signup:o.z.object({status:o.z.enum(["required","optional","disabled"]).optional(),verification:o.z.object({active:o.z.boolean().optional()}).optional()}).optional(),validation:o.z.object({allowed:o.z.boolean().optional()}).optional(),unique:o.z.boolean().optional(),profile_required:o.z.boolean().optional(),verification_method:o.z.enum(["link","code"]).optional()}).optional(),username:o.z.object({identifier:o.z.object({active:o.z.boolean().optional()}).optional(),signup:o.z.object({status:o.z.enum(["required","optional","disabled"]).optional()}).optional(),validation:o.z.object({max_length:o.z.number().optional(),min_length:o.z.number().optional(),allowed_types:o.z.object({email:o.z.boolean().optional(),phone_number:o.z.boolean().optional()}).optional()}).optional(),profile_required:o.z.boolean().optional()}).optional(),phone_number:o.z.object({identifier:o.z.object({active:o.z.boolean().optional()}).optional(),signup:o.z.object({status:o.z.enum(["required","optional","disabled"]).optional()}).optional()}).optional()}).optional(),authentication_methods:o.z.object({password:o.z.object({enabled:o.z.boolean().optional()}).optional(),passkey:o.z.object({enabled:o.z.boolean().optional()}).optional()}).optional(),passkey_options:o.z.object({challenge_ui:o.z.enum(["both","autofill","button"]).optional(),local_enrollment_enabled:o.z.boolean().optional(),progressive_enrollment_enabled:o.z.boolean().optional()}).optional(),requires_username:o.z.boolean().optional(),validation:o.z.object({username:o.z.object({min:o.z.number().optional(),max:o.z.number().optional()}).optional()}).optional()}),Xc=o.z.object({id:o.z.string().optional(),name:o.z.string(),display_name:o.z.string().optional(),strategy:o.z.string(),options:qv.default({}),enabled_clients:o.z.array(o.z.string()).default([]).optional(),response_type:o.z.custom().optional(),response_mode:o.z.custom().optional(),is_domain_connection:o.z.boolean().optional(),show_as_button:o.z.boolean().optional(),metadata:o.z.record(o.z.any()).optional(),is_system:o.z.boolean().optional()}),_r=o.z.object({id:o.z.string(),created_at:o.z.string().transform(e=>e===null?"":e),updated_at:o.z.string().transform(e=>e===null?"":e)}).extend(Xc.shape),dh=o.z.object({domain:o.z.string(),custom_domain_id:o.z.string().optional(),type:o.z.enum(["auth0_managed_certs","self_managed_certs"]),verification_method:o.z.enum(["txt"]).optional(),tls_policy:o.z.enum(["recommended"]).optional(),custom_client_ip_header:o.z.enum(["true-client-ip","cf-connecting-ip","x-forwarded-for","x-azure-clientip","null"]).optional(),domain_metadata:o.z.record(o.z.string().max(255)).optional()}),Fv=o.z.object({name:o.z.literal("txt"),record:o.z.string(),domain:o.z.string()}),fr=o.z.object({...dh.shape,custom_domain_id:o.z.string(),primary:o.z.boolean(),status:o.z.enum(["disabled","pending","pending_verification","ready"]),origin_domain_name:o.z.string().optional(),verification:o.z.object({methods:o.z.array(Fv)}).optional(),tls_policy:o.z.string().optional()}),Fx=fr.extend({tenant_id:o.z.string()}),ph=o.z.object({id:o.z.string(),order:o.z.number().optional(),visible:o.z.boolean().optional().default(!0)}),Nr=ph.extend({category:o.z.literal("BLOCK").optional()}),Hx=Nr.extend({type:o.z.literal("DIVIDER"),config:o.z.object({}).optional()}),Vx=Nr.extend({type:o.z.literal("HTML"),config:o.z.object({content:o.z.string().optional()}).optional()}),Kx=Nr.extend({type:o.z.literal("IMAGE"),config:o.z.object({src:o.z.string().optional(),alt:o.z.string().optional(),width:o.z.number().optional(),height:o.z.number().optional()}).optional()}),Gx=Nr.extend({type:o.z.literal("JUMP_BUTTON"),config:o.z.object({text:o.z.string().optional(),target_step:o.z.string().optional()})}),Wx=Nr.extend({type:o.z.literal("RESEND_BUTTON"),config:o.z.object({text:o.z.string().optional(),resend_action:o.z.string().optional()})}),Jx=Nr.extend({type:o.z.literal("NEXT_BUTTON"),config:o.z.object({text:o.z.string().optional()})}),Zx=Nr.extend({type:o.z.literal("PREVIOUS_BUTTON"),config:o.z.object({text:o.z.string().optional()})}),Xx=Nr.extend({type:o.z.literal("RICH_TEXT"),config:o.z.object({content:o.z.string().optional()}).optional()}),fh=ph.extend({category:o.z.literal("WIDGET").optional(),label:o.z.string().min(1).optional(),hint:o.z.string().min(1).max(500).optional(),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional()}),Yx=fh.extend({type:o.z.literal("AUTH0_VERIFIABLE_CREDENTIALS"),config:o.z.object({credential_type:o.z.string().optional()})}),Qx=fh.extend({type:o.z.literal("GMAPS_ADDRESS"),config:o.z.object({api_key:o.z.string().optional()})}),eS=fh.extend({type:o.z.literal("RECAPTCHA"),config:o.z.object({site_key:o.z.string().optional()})}),yt=ph.extend({category:o.z.literal("FIELD").optional(),label:o.z.string().min(1).optional(),hint:o.z.string().min(1).max(500).optional(),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional()}),tS=yt.extend({type:o.z.literal("BOOLEAN"),config:o.z.object({default_value:o.z.boolean().optional()}).optional()}),nS=yt.extend({type:o.z.literal("CARDS"),config:o.z.object({options:o.z.array(o.z.object({value:o.z.string(),label:o.z.string(),description:o.z.string().optional(),image:o.z.string().optional()})).optional(),multi_select:o.z.boolean().optional()}).optional()}),rS=yt.extend({type:o.z.literal("CHOICE"),config:o.z.object({options:o.z.array(o.z.object({value:o.z.string(),label:o.z.string()})).optional(),display:o.z.enum(["radio","checkbox"]).optional(),multiple:o.z.boolean().optional(),default_value:o.z.union([o.z.string(),o.z.array(o.z.string())]).optional()}).optional()}),iS=yt.extend({type:o.z.literal("CUSTOM"),config:o.z.object({component:o.z.string().optional(),props:o.z.record(o.z.any()).optional(),schema:o.z.record(o.z.any()).optional(),code:o.z.string().optional()})}),oS=yt.extend({type:o.z.literal("DATE"),config:o.z.object({format:o.z.string().optional(),min:o.z.string().optional(),max:o.z.string().optional(),default_value:o.z.string().optional()}).optional()}),sS=yt.extend({type:o.z.literal("DROPDOWN"),config:o.z.object({options:o.z.array(o.z.object({value:o.z.string(),label:o.z.string()})).optional(),placeholder:o.z.string().optional(),searchable:o.z.boolean().optional(),multiple:o.z.boolean().optional(),default_value:o.z.union([o.z.string(),o.z.array(o.z.string())]).optional()}).optional()}),aS=yt.extend({type:o.z.literal("EMAIL"),config:o.z.object({placeholder:o.z.string().optional(),default_value:o.z.string().optional()}).optional()}),cS=yt.extend({type:o.z.literal("FILE"),config:o.z.object({accept:o.z.string().optional(),max_size:o.z.number().optional(),multiple:o.z.boolean().optional()}).optional()}),lS=yt.extend({type:o.z.literal("LEGAL"),config:o.z.object({text:o.z.string(),html:o.z.boolean().optional()}).optional()}),uS=yt.extend({type:o.z.literal("NUMBER"),config:o.z.object({placeholder:o.z.string().optional(),min:o.z.number().optional(),max:o.z.number().optional(),step:o.z.number().optional(),default_value:o.z.string().optional()}).optional()}),dS=yt.extend({type:o.z.literal("PASSWORD"),config:o.z.object({placeholder:o.z.string().optional(),min_length:o.z.number().optional(),show_toggle:o.z.boolean().optional(),forgot_password_link:o.z.string().optional(),default_value:o.z.string().optional()}).optional()}),pS=yt.extend({type:o.z.literal("PAYMENT"),config:o.z.object({provider:o.z.string().optional(),currency:o.z.string().optional()}).optional()}),fS=yt.extend({type:o.z.literal("SOCIAL"),config:o.z.object({providers:o.z.array(o.z.string()).optional(),provider_details:o.z.array(o.z.object({name:o.z.string(),strategy:o.z.string().optional(),display_name:o.z.string().optional(),icon_url:o.z.string().optional()})).optional()}).optional()}),hS=yt.extend({type:o.z.literal("TEL"),config:o.z.object({placeholder:o.z.string().optional(),default_country:o.z.string().optional(),default_value:o.z.string().optional()}).optional()}),_S=yt.extend({type:o.z.literal("TEXT"),config:o.z.object({placeholder:o.z.string().optional(),multiline:o.z.boolean().optional(),max_length:o.z.number().optional(),default_value:o.z.string().optional()}).optional()}),mS=yt.extend({type:o.z.literal("URL"),config:o.z.object({placeholder:o.z.string().optional(),default_value:o.z.string().optional()}).optional()}),Hv=o.z.discriminatedUnion("type",[Hx,Vx,Kx,Gx,Wx,Jx,Zx,Xx]),Vv=o.z.discriminatedUnion("type",[Yx,Qx,eS]),Kv=o.z.discriminatedUnion("type",[tS,nS,rS,iS,oS,sS,aS,cS,lS,uS,dS,pS,fS,hS,_S,mS]),hh=o.z.union([Hv,Vv,Kv]),_h=new Set(["BOOLEAN","CARDS","CHOICE","DATE","DROPDOWN","EMAIL","LEGAL","NUMBER","PASSWORD","TEL","TEXT","URL"]),gS=o.z.object({id:o.z.string(),type:o.z.literal("submit"),label:o.z.string(),className:o.z.string().optional(),disabled:o.z.boolean().optional().default(!1),order:o.z.number().optional(),visible:o.z.boolean().optional().default(!0),customizations:o.z.record(o.z.string(),o.z.any()).optional()}),Zs=o.z.object({x:o.z.number(),y:o.z.number()}),yS=o.z.object({id:o.z.string(),type:o.z.literal("FLOW"),coordinates:Zs,alias:o.z.string().min(1).max(150).optional(),config:o.z.object({flow_id:o.z.string().max(30),next_node:o.z.string().optional()})}),bS=o.z.object({id:o.z.string(),type:o.z.literal("ROUTER"),coordinates:Zs,alias:o.z.string().min(1).max(150),config:o.z.object({rules:o.z.array(o.z.object({id:o.z.string(),alias:o.z.string().min(1).max(150).optional(),condition:o.z.any(),next_node:o.z.string()})),fallback:o.z.string()})}),vS=o.z.object({id:o.z.string(),type:o.z.literal("STEP"),coordinates:Zs,alias:o.z.string().min(1).max(150).optional(),config:o.z.object({components:o.z.array(hh),next_node:o.z.string().optional()})}),Gv=o.z.discriminatedUnion("type",[yS,bS,vS]),Yc=o.z.object({name:o.z.string().openapi({description:"The name of the form"}),messages:o.z.object({errors:o.z.record(o.z.string(),o.z.any()).optional(),custom:o.z.record(o.z.string(),o.z.any()).optional()}).optional(),languages:o.z.object({primary:o.z.string().optional(),default:o.z.string().optional()}).optional(),translations:o.z.record(o.z.string(),o.z.any()).optional(),nodes:o.z.array(Gv).optional(),start:o.z.object({hidden_fields:o.z.array(o.z.object({key:o.z.string(),value:o.z.string()})).optional(),next_node:o.z.string().optional(),coordinates:Zs.optional()}).optional(),ending:o.z.object({redirection:o.z.object({delay:o.z.number().optional(),target:o.z.string().optional()}).optional(),after_submit:o.z.object({flow_id:o.z.string().optional()}).optional(),coordinates:Zs.optional(),resume_flow:o.z.boolean().optional()}).optional(),style:o.z.object({css:o.z.string().optional()}).optional(),links:o.z.object({sdkSrc:o.z.string().optional(),sdk_src:o.z.string().optional()}).optional()}).openapi({description:"Schema for flow-based forms (matches Auth0 Forms structure)"}),eo=o.z.object({...jr.shape,...Yc.shape,id:o.z.string()}),Wv=o.z.object({id:o.z.number().optional(),text:o.z.string(),type:o.z.enum(["info","error","success","warning"])}),Jv=o.z.object({id:o.z.string().optional(),text:o.z.string(),href:o.z.string(),linkText:o.z.string().optional()}),wS=o.z.object({name:o.z.string().optional(),action:o.z.string(),method:o.z.enum(["POST","GET"]),title:o.z.string().optional(),description:o.z.string().optional(),components:o.z.array(hh),messages:o.z.array(Wv).optional(),links:o.z.array(Jv).optional(),footer:o.z.string().optional()});function kS(e){return e.category==="BLOCK"}function $S(e){return e.category==="WIDGET"}function xS(e){return e.category==="FIELD"}const Zv=o.z.enum(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Xv=o.z.enum(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Yv=o.z.enum(["post-user-login","credentials-exchange"]),mh=o.z.enum(["ensure-username","set-preferred-username"]),SS={"ensure-username":{name:"Ensure Username",description:"Automatically assigns a username to users who sign in without one. Creates a linked username account for social/email users.",trigger_id:"post-user-login"},"set-preferred-username":{name:"Set Preferred Username",description:"Sets the preferred_username claim on tokens based on the username from the primary or linked user.",trigger_id:"credentials-exchange"}},Lo={enabled:o.z.boolean().default(!1),synchronous:o.z.boolean().default(!1),priority:o.z.number().optional(),hook_id:o.z.string().optional()},zS=o.z.object({...Lo,trigger_id:Zv,url:o.z.string()}),AS=o.z.object({...Lo,trigger_id:Xv,form_id:o.z.string()}),ES=o.z.object({...Lo,trigger_id:Yv,template_id:mh}),af=o.z.union([zS,AS,ES]),CS=o.z.object({...Lo,trigger_id:Zv,...jr.shape,hook_id:o.z.string(),url:o.z.string()}),IS=o.z.object({...Lo,trigger_id:Xv,...jr.shape,hook_id:o.z.string(),form_id:o.z.string()}),jS=o.z.object({...Lo,trigger_id:Yv,...jr.shape,hook_id:o.z.string(),template_id:mh}),to=o.z.union([CS,IS,jS]),Qv=o.z.object({name:o.z.string().optional()}),ew=o.z.object({email:o.z.string().optional()}),gh=o.z.object({organization_id:o.z.string().max(50),inviter:Qv,invitee:ew,invitation_url:o.z.string().url(),client_id:o.z.string(),connection_id:o.z.string().optional(),app_metadata:o.z.record(o.z.any()).default({}).optional(),user_metadata:o.z.record(o.z.any()).default({}).optional(),ttl_sec:o.z.number().int().max(2592e3).default(604800).optional(),roles:o.z.array(o.z.string()).default([]).optional(),send_invitation_email:o.z.boolean().default(!0).optional()}),Os=o.z.object({id:o.z.string(),organization_id:o.z.string().max(50),created_at:o.z.string().datetime(),expires_at:o.z.string().datetime(),ticket_id:o.z.string().optional()}).extend(gh.shape),yh=o.z.object({alg:o.z.enum(["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512"]),e:o.z.string(),kid:o.z.string(),kty:o.z.enum(["RSA","EC","oct"]),n:o.z.string(),x5t:o.z.string().optional(),x5c:o.z.array(o.z.string()).optional(),use:o.z.enum(["sig","enc"]).optional()}),tw=o.z.object({keys:o.z.array(yh)}),cf=o.z.object({issuer:o.z.string(),authorization_endpoint:o.z.string(),token_endpoint:o.z.string(),device_authorization_endpoint:o.z.string(),userinfo_endpoint:o.z.string(),mfa_challenge_endpoint:o.z.string(),jwks_uri:o.z.string(),registration_endpoint:o.z.string(),revocation_endpoint:o.z.string(),scopes_supported:o.z.array(o.z.string()),response_types_supported:o.z.array(o.z.string()),code_challenge_methods_supported:o.z.array(o.z.string()),response_modes_supported:o.z.array(o.z.string()),subject_types_supported:o.z.array(o.z.string()),id_token_signing_alg_values_supported:o.z.array(o.z.string()),token_endpoint_auth_methods_supported:o.z.array(o.z.string()),claims_supported:o.z.array(o.z.string()),request_uri_parameter_supported:o.z.boolean(),request_parameter_supported:o.z.boolean(),token_endpoint_auth_signing_alg_values_supported:o.z.array(o.z.string())});var We=(e=>(e.PENDING="pending",e.AUTHENTICATED="authenticated",e.AWAITING_EMAIL_VERIFICATION="awaiting_email_verification",e.AWAITING_HOOK="awaiting_hook",e.AWAITING_CONTINUATION="awaiting_continuation",e.COMPLETED="completed",e.FAILED="failed",e.EXPIRED="expired",e))(We||{});const nw=o.z.nativeEnum(We),rw=o.z.object({csrf_token:o.z.string(),auth0Client:o.z.string().optional(),authParams:Js,expires_at:o.z.string(),deleted_at:o.z.string().optional(),ip:o.z.string().optional(),useragent:o.z.string().optional(),session_id:o.z.string().optional(),authorization_url:o.z.string().optional(),state:nw.optional().default("pending"),state_data:o.z.string().optional(),failure_reason:o.z.string().optional(),user_id:o.z.string().optional()}).openapi({description:"This represents a login sesion"}),NS=o.z.object({...rw.shape,id:o.z.string().openapi({description:"This is is used as the state in the universal login"}),created_at:o.z.string(),updated_at:o.z.string()}),ue={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",SUCCESS_CHANGE_EMAIL:"sce",SUCCESS_CROSS_ORIGIN_AUTHENTICATION:"scoa",SUCCESS_CHANGE_PASSWORD:"scp",SUCCESS_CHANGE_PHONE_NUMBER:"scpn",SUCCESS_CHANGE_PASSWORD_REQUEST:"scpr",SUCCESS_CHANGE_USERNAME:"scu",SUCCESS_CREDENTIAL_VALIDATION:"scv",SUCCESS_DELEGATION:"sd",SUCCESS_USER_DELETION:"sdu",SUCCESS_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN:"seacft",SUCCESS_EXCHANGE_ACCESS_TOKEN_FOR_CLIENT_CREDENTIALS:"seccft",SUCCESS_EXCHANGE_CUSTOM_TOKEN:"secte",SUCCESS_EXCHANGE_DEVICE_CODE_FOR_ACCESS_TOKEN:"sede",SUCCESS_EXCHANGE_NATIVE_SOCIAL_LOGIN:"sens",SUCCESS_EXCHANGE_PASSWORD_OOB_FOR_ACCESS_TOKEN:"seoobft",SUCCESS_EXCHANGE_PASSWORD_OTP_FOR_ACCESS_TOKEN:"seotpft",SUCCESS_EXCHANGE_PASSWORD_FOR_ACCESS_TOKEN:"sepft",SUCCESS_EXCHANGE_PASSKEY_OOB_FOR_ACCESS_TOKEN:"sepkoobft",SUCCESS_EXCHANGE_PASSKEY_OTP_FOR_ACCESS_TOKEN:"sepkotpft",SUCCESS_EXCHANGE_PASSKEY_MFA_RECOVERY_FOR_ACCESS_TOKEN:"sepkrcft",SUCCESS_EXCHANGE_PASSWORD_MFA_RECOVERY_FOR_ACCESS_TOKEN:"sercft",SUCCESS_EXCHANGE_REFRESH_TOKEN_FOR_ACCESS_TOKEN:"sertft",SUCCESS_IMPERSONATION:"simp",SUCCESSFULLY_ACCEPTED_USER_INVITE:"si",BREACHED_PASSWORD_ON_SIGNUP:"signup_pwd_leak",SUCCESS_LOGOUT:"slo",SUCCESS_REVOCATION:"srrt",SUCCESS_SIGNUP:"ss",FAILED_SS_SSO_OPERATION:"ss_sso_failure",INFORMATION_FROM_SS_SSO_OPERATION:"ss_sso_info",SUCCESS_SS_SSO_OPERATION:"ss_sso_success",SUCCESS_SILENT_AUTH:"ssa",SUCCESSFUL_SCIM_OPERATION:"sscim",SUCCESSFULLY_IMPORTED_USERS:"sui",SUCCESS_VERIFICATION_EMAIL:"sv",SUCCESS_VERIFICATION_EMAIL_REQUEST:"svr",MAX_AMOUNT_OF_AUTHENTICATORS:"too_many_records",USER_LOGIN_BLOCK_RELEASED:"ublkdu",FAILED_UNIVERSAL_LOGOUT:"universal_logout_failed",SUCCESSFUL_UNIVERSAL_LOGOUT:"universal_logout_succeeded",WARNING_DURING_LOGIN:"w",WARNING_SENDING_NOTIFICATION:"wn",WARNING_USER_MANAGEMENT:"wum"},TS=o.z.string().refine(e=>Object.values(ue).includes(e),{message:"Invalid log type"}),iw=o.z.object({name:o.z.string(),version:o.z.string(),env:o.z.object({node:o.z.string().optional()}).optional()}),ow=o.z.object({country_code:o.z.string().length(2),city_name:o.z.string(),latitude:o.z.string(),longitude:o.z.string(),time_zone:o.z.string(),continent_code:o.z.string()}),sw=o.z.object({type:TS,date:o.z.string(),description:o.z.string().optional(),ip:o.z.string().optional(),user_agent:o.z.string().optional(),details:o.z.any().optional(),isMobile:o.z.boolean(),user_id:o.z.string().optional(),user_name:o.z.string().optional(),connection:o.z.string().optional(),connection_id:o.z.string().optional(),client_id:o.z.string().optional(),client_name:o.z.string().optional(),audience:o.z.string().optional(),scope:o.z.string().optional(),strategy:o.z.string().optional(),strategy_type:o.z.string().optional(),hostname:o.z.string().optional(),auth0_client:iw.optional(),log_id:o.z.string().optional(),location_info:ow.optional()}),Qc=o.z.object({...sw.shape,log_id:o.z.string()}),aw=o.z.object({id:o.z.string().optional(),user_id:o.z.string(),password:o.z.string(),algorithm:o.z.enum(["bcrypt","argon2id"]).default("argon2id"),is_current:o.z.boolean().default(!0)}),PS=aw.extend({id:o.z.string(),created_at:o.z.string(),updated_at:o.z.string()}),cw=o.z.object({initial_user_agent:o.z.string().describe("First user agent of the device from which this user logged in"),initial_ip:o.z.string().describe("First IP address associated with this session"),initial_asn:o.z.string().describe("First autonomous system number associated with this session"),last_user_agent:o.z.string().describe("Last user agent of the device from which this user logged in"),last_ip:o.z.string().describe("Last IP address from which this user logged in"),last_asn:o.z.string().describe("Last autonomous system number from which this user logged in")}),lw=o.z.object({id:o.z.string(),revoked_at:o.z.string().optional(),used_at:o.z.string().optional(),user_id:o.z.string().describe("The user ID associated with the session"),expires_at:o.z.string().optional(),login_session_id:o.z.string(),idle_expires_at:o.z.string().optional(),device:cw.describe("Metadata related to the device used in the session"),clients:o.z.array(o.z.string()).describe("List of client details for the session")}),du=o.z.object({created_at:o.z.string(),updated_at:o.z.string(),authenticated_at:o.z.string(),last_interaction_at:o.z.string(),...lw.shape}),lf=o.z.object({kid:o.z.string().openapi({description:"The key id of the signing key"}),cert:o.z.string().openapi({description:"The public certificate of the signing key"}),fingerprint:o.z.string().openapi({description:"The cert fingerprint"}),thumbprint:o.z.string().openapi({description:"The cert thumbprint"}),pkcs7:o.z.string().optional().openapi({description:"The private key in pkcs7 format"}),current:o.z.boolean().optional().openapi({description:"True if the key is the current key"}),next:o.z.boolean().optional().openapi({description:"True if the key is the next key"}),previous:o.z.boolean().optional().openapi({description:"True if the key is the previous key"}),current_since:o.z.string().optional().openapi({description:"The date and time when the key became the current key"}),current_until:o.z.string().optional().openapi({description:"The date and time when the current key was rotated"}),revoked:o.z.boolean().optional().openapi({description:"True if the key is revoked"}),revoked_at:o.z.string().optional().openapi({description:"The date and time when the key was revoked"}),connection:o.z.string().optional().openapi({description:"The connection identifier associated with the key"}),type:o.z.enum(["jwt_signing","saml_encryption"]).openapi({description:"The type of the signing key"})}),bh=o.z.object({id:o.z.string().optional(),audience:o.z.string(),friendly_name:o.z.string(),picture_url:o.z.string().optional(),support_email:o.z.string().optional(),support_url:o.z.string().optional(),sender_email:o.z.string().email(),sender_name:o.z.string(),session_lifetime:o.z.number().optional(),idle_session_lifetime:o.z.number().optional(),ephemeral_session_lifetime:o.z.number().optional(),idle_ephemeral_session_lifetime:o.z.number().optional(),session_cookie:o.z.object({mode:o.z.enum(["persistent","non-persistent"]).optional()}).optional(),allowed_logout_urls:o.z.array(o.z.string()).optional(),default_redirection_uri:o.z.string().optional(),enabled_locales:o.z.array(o.z.string()).optional(),default_directory:o.z.string().optional(),error_page:o.z.object({html:o.z.string().optional(),show_log_link:o.z.boolean().optional(),url:o.z.string().optional()}).optional(),flags:o.z.object({allow_changing_enable_sso:o.z.boolean().optional(),allow_legacy_delegation_grant_types:o.z.boolean().optional(),allow_legacy_ro_grant_types:o.z.boolean().optional(),allow_legacy_tokeninfo_endpoint:o.z.boolean().optional(),change_pwd_flow_v1:o.z.boolean().optional(),custom_domains_provisioning:o.z.boolean().optional(),dashboard_insights_view:o.z.boolean().optional(),dashboard_log_streams_next:o.z.boolean().optional(),disable_clickjack_protection_headers:o.z.boolean().optional(),disable_fields_map_fix:o.z.boolean().optional(),disable_impersonation:o.z.boolean().optional(),disable_management_api_sms_obfuscation:o.z.boolean().optional(),enable_adfs_waad_email_verification:o.z.boolean().optional(),enable_apis_section:o.z.boolean().optional(),enable_client_connections:o.z.boolean().optional(),enable_custom_domain_in_emails:o.z.boolean().optional(),enable_dynamic_client_registration:o.z.boolean().optional(),enable_idtoken_api2:o.z.boolean().optional(),enable_legacy_logs_search_v2:o.z.boolean().optional(),enable_legacy_profile:o.z.boolean().optional(),enable_pipeline2:o.z.boolean().optional(),enable_public_signup_user_exists_error:o.z.boolean().optional(),enable_sso:o.z.boolean().optional(),enforce_client_authentication_on_passwordless_start:o.z.boolean().optional(),genai_trial:o.z.boolean().optional(),improved_signup_bot_detection_in_classic:o.z.boolean().optional(),mfa_show_factor_list_on_enrollment:o.z.boolean().optional(),no_disclose_enterprise_connections:o.z.boolean().optional(),remove_alg_from_jwks:o.z.boolean().optional(),revoke_refresh_token_grant:o.z.boolean().optional(),trust_azure_adfs_email_verified_connection_property:o.z.boolean().optional(),use_scope_descriptions_for_consent:o.z.boolean().optional(),inherit_global_permissions_in_organizations:o.z.boolean().optional()}).optional(),sandbox_version:o.z.string().optional(),legacy_sandbox_version:o.z.string().optional(),sandbox_versions_available:o.z.array(o.z.string()).optional(),change_password:o.z.object({enabled:o.z.boolean().optional(),html:o.z.string().optional()}).optional(),guardian_mfa_page:o.z.object({enabled:o.z.boolean().optional(),html:o.z.string().optional()}).optional(),device_flow:o.z.object({charset:o.z.enum(["base20","digits"]).optional(),mask:o.z.string().max(20).optional()}).optional(),default_token_quota:o.z.object({clients:o.z.object({client_credentials:o.z.record(o.z.any()).optional()}).optional(),organizations:o.z.object({client_credentials:o.z.record(o.z.any()).optional()}).optional()}).optional(),default_audience:o.z.string().optional(),default_organization:o.z.string().optional(),sessions:o.z.object({oidc_logout_prompt_enabled:o.z.boolean().optional()}).optional(),oidc_logout:o.z.object({rp_logout_end_session_endpoint_discovery:o.z.boolean().optional()}).optional(),allow_organization_name_in_authentication_api:o.z.boolean().optional(),customize_mfa_in_postlogin_action:o.z.boolean().optional(),acr_values_supported:o.z.array(o.z.string()).optional(),mtls:o.z.object({enable_endpoint_aliases:o.z.boolean().optional()}).optional(),pushed_authorization_requests_supported:o.z.boolean().optional(),authorization_response_iss_parameter_supported:o.z.boolean().optional(),mfa:o.z.object({factors:o.z.object({sms:o.z.boolean().default(!1),otp:o.z.boolean().default(!1),email:o.z.boolean().default(!1),push_notification:o.z.boolean().default(!1),webauthn_roaming:o.z.boolean().default(!1),webauthn_platform:o.z.boolean().default(!1),recovery_code:o.z.boolean().default(!1),duo:o.z.boolean().default(!1)}).optional(),sms_provider:o.z.object({provider:o.z.enum(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:o.z.object({sid:o.z.string().optional(),auth_token:o.z.string().optional(),from:o.z.string().optional(),messaging_service_sid:o.z.string().optional()}).optional(),phone_message:o.z.object({message:o.z.string().optional()}).optional()}).optional()}),el=o.z.object({created_at:o.z.string().nullable().transform(e=>e??""),updated_at:o.z.string().nullable().transform(e=>e??""),...bh.shape,id:o.z.string()});var an=(e=>(e.RefreshToken="refresh_token",e.AuthorizationCode="authorization_code",e.ClientCredential="client_credentials",e.Passwordless="passwordless",e.Password="password",e.OTP="http://auth0.com/oauth/grant-type/passwordless/otp",e))(an||{});const vh=o.z.object({access_token:o.z.string(),id_token:o.z.string().optional(),scope:o.z.string().optional(),state:o.z.string().optional(),refresh_token:o.z.string().optional(),token_type:o.z.string(),expires_in:o.z.number()});o.z.object({code:o.z.string(),state:o.z.string().optional()});const uw=o.z.object({button_border_radius:o.z.number(),button_border_weight:o.z.number(),buttons_style:o.z.enum(["pill","rounded","sharp"]),input_border_radius:o.z.number(),input_border_weight:o.z.number(),inputs_style:o.z.enum(["pill","rounded","sharp"]),show_widget_shadow:o.z.boolean(),widget_border_weight:o.z.number(),widget_corner_radius:o.z.number()}),dw=o.z.object({base_focus_color:o.z.string(),base_hover_color:o.z.string(),body_text:o.z.string(),captcha_widget_theme:o.z.enum(["auto","dark","light"]),error:o.z.string(),header:o.z.string(),icons:o.z.string(),input_background:o.z.string(),input_border:o.z.string(),input_filled_text:o.z.string(),input_labels_placeholders:o.z.string(),links_focused_components:o.z.string(),primary_button:o.z.string(),primary_button_label:o.z.string(),secondary_button_border:o.z.string(),secondary_button_label:o.z.string(),success:o.z.string(),widget_background:o.z.string(),widget_border:o.z.string()}),Zr=o.z.object({bold:o.z.boolean(),size:o.z.number()}),pw=o.z.object({body_text:Zr,buttons_text:Zr,font_url:o.z.string(),input_labels:Zr,links:Zr,links_style:o.z.enum(["normal","underlined"]),reference_text_size:o.z.number(),subtitle:Zr,title:Zr}),fw=o.z.object({background_color:o.z.string(),background_image_url:o.z.string(),page_layout:o.z.enum(["center","left","right"])}),hw=o.z.object({header_text_alignment:o.z.enum(["center","left","right"]),logo_height:o.z.number(),logo_position:o.z.enum(["center","left","none","right"]),logo_url:o.z.string(),social_buttons_layout:o.z.enum(["bottom","top"])}),_w=o.z.object({borders:uw,colors:dw,displayName:o.z.string(),fonts:pw,page_background:fw,widget:hw}),Sc=_w.extend({themeId:o.z.string()}),Rs=o.z.object({universal_login_experience:o.z.enum(["new","classic"]).default("new"),identifier_first:o.z.boolean().default(!0),password_first:o.z.boolean().default(!1),webauthn_platform_first_factor:o.z.boolean()}),zc=o.z.object({name:o.z.string(),enabled:o.z.boolean().optional().default(!0),default_from_address:o.z.string().optional(),credentials:o.z.union([o.z.object({accessKeyId:o.z.string(),secretAccessKey:o.z.string(),region:o.z.string()}),o.z.object({smtp_host:o.z.array(o.z.string()),smtp_port:o.z.number(),smtp_user:o.z.string(),smtp_pass:o.z.string()}),o.z.object({api_key:o.z.string(),domain:o.z.string().optional()}),o.z.object({connectionString:o.z.string()}),o.z.object({tenantId:o.z.string(),clientId:o.z.string(),clientSecret:o.z.string()})]),settings:o.z.object({}).optional()}),wh=o.z.object({id:o.z.string(),session_id:o.z.string(),user_id:o.z.string(),client_id:o.z.string(),expires_at:o.z.string().optional(),idle_expires_at:o.z.string().optional(),last_exchanged_at:o.z.string().optional(),device:cw,resource_servers:o.z.array(o.z.object({audience:o.z.string(),scopes:o.z.string()})),rotating:o.z.boolean()}),OS=o.z.object({created_at:o.z.string(),...wh.shape}),RS=o.z.object({to:o.z.string(),message:o.z.string()}),LS=o.z.object({name:o.z.string(),options:o.z.object({})}),mw=o.z.object({value:o.z.string(),description:o.z.string().optional()}),gw=o.z.object({token_dialect:o.z.enum(["access_token","access_token_authz"]).optional(),enforce_policies:o.z.boolean().optional(),allow_skipping_userinfo:o.z.boolean().optional(),skip_userinfo:o.z.boolean().optional(),persist_client_authorization:o.z.boolean().optional(),enable_introspection_endpoint:o.z.boolean().optional(),mtls:o.z.object({bound_access_tokens:o.z.boolean().optional()}).optional()}),tl=o.z.object({id:o.z.string().optional(),name:o.z.string(),identifier:o.z.string(),scopes:o.z.array(mw).optional(),signing_alg:o.z.string().optional(),signing_secret:o.z.string().optional(),token_lifetime:o.z.number().optional(),token_lifetime_for_web:o.z.number().optional(),skip_consent_for_verifiable_first_party_clients:o.z.boolean().optional(),allow_offline_access:o.z.boolean().optional(),verificationKey:o.z.string().optional(),options:gw.optional(),is_system:o.z.boolean().optional(),metadata:o.z.record(o.z.any()).optional()}),ti=o.z.object({...tl.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),DS=o.z.array(ti),yw=o.z.object({role_id:o.z.string(),resource_server_identifier:o.z.string(),permission_name:o.z.string()}),bw=o.z.object({...yw.shape,created_at:o.z.string()}),vw=o.z.array(bw),ww=o.z.object({user_id:o.z.string(),resource_server_identifier:o.z.string(),permission_name:o.z.string(),organization_id:o.z.string().optional()}),kw=o.z.object({...ww.shape,tenant_id:o.z.string(),created_at:o.z.string().optional()}),US=o.z.array(kw),$w=o.z.object({user_id:o.z.string(),resource_server_identifier:o.z.string(),resource_server_name:o.z.string(),permission_name:o.z.string(),description:o.z.string().nullable().optional(),created_at:o.z.string().optional(),organization_id:o.z.string().optional()}),xw=o.z.array($w),Sw=o.z.object({user_id:o.z.string(),role_id:o.z.string(),organization_id:o.z.string().optional()}),zw=o.z.object({...Sw.shape,tenant_id:o.z.string(),created_at:o.z.string().optional()}),BS=o.z.array(zw),nl=o.z.object({id:o.z.string().optional().openapi({description:"The unique identifier of the role. If not provided, one will be generated."}),name:o.z.string().min(1).max(50).openapi({description:"The name of the role. Cannot include '<' or '>'"}),description:o.z.string().max(255).optional().openapi({description:"The description of the role"}),is_system:o.z.boolean().optional(),metadata:o.z.record(o.z.any()).optional().openapi({description:"Metadata associated with the role. Can be used to control sync behavior in multi-tenancy scenarios."})}),ni=nl.extend({id:o.z.string().openapi({description:"The unique identifier of the role"}),created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),rl=o.z.array(ni),Aw=o.z.object({logo_url:o.z.string().optional().openapi({description:"URL of the organization's logo"}),colors:o.z.object({primary:o.z.string().optional().openapi({description:"Primary color in hex format (e.g., #FF0000)"}),page_background:o.z.string().optional().openapi({description:"Page background color in hex format (e.g., #FFFFFF)"})}).optional()}).optional(),Ew=o.z.object({connection_id:o.z.string().openapi({description:"ID of the connection"}),assign_membership_on_login:o.z.boolean().default(!1).openapi({description:"Whether to assign membership to the organization on login"}),show_as_button:o.z.boolean().default(!0).openapi({description:"Whether to show this connection as a button in the login screen"}),is_signup_enabled:o.z.boolean().default(!0).openapi({description:"Whether signup is enabled for this connection"})}),Cw=o.z.object({client_credentials:o.z.object({enforce:o.z.boolean().default(!1).openapi({description:"Whether to enforce token quota limits"}),per_day:o.z.number().min(0).default(0).openapi({description:"Maximum tokens per day (0 = unlimited)"}),per_hour:o.z.number().min(0).default(0).openapi({description:"Maximum tokens per hour (0 = unlimited)"})}).optional()}).optional(),il=o.z.object({id:o.z.string().optional(),name:o.z.string().min(1).regex(/^[a-z0-9_-]+$/,{message:"Organization name must be lowercase and can only contain letters, numbers, hyphens, and underscores"}).openapi({description:"The name of the organization. Must be lowercase and can only contain letters, numbers, hyphens, and underscores."}),display_name:o.z.string().optional().openapi({description:"The display name of the organization"}),branding:Aw,metadata:o.z.record(o.z.any()).default({}).optional().openapi({description:"Custom metadata for the organization"}),enabled_connections:o.z.array(Ew).default([]).optional().openapi({description:"List of enabled connections for the organization"}),token_quota:Cw}),mr=o.z.object({...il.shape,...jr.shape,id:o.z.string(),name:o.z.string().min(1).openapi({description:"The name of the organization"})}),Iw=o.z.object({user_id:o.z.string().openapi({description:"ID of the user"}),organization_id:o.z.string().openapi({description:"ID of the organization"})}),MS=o.z.object({...Iw.shape,...jr.shape,id:o.z.string()}),qS=o.z.object({idle_session_lifetime:o.z.number().optional(),session_lifetime:o.z.number().optional(),session_cookie:o.z.object({mode:o.z.enum(["persistent","non-persistent"]).optional()}).optional(),enable_client_connections:o.z.boolean().optional(),default_redirection_uri:o.z.string().optional(),enabled_locales:o.z.array(o.z.string()).optional(),default_directory:o.z.string().optional(),error_page:o.z.object({html:o.z.string().optional(),show_log_link:o.z.boolean().optional(),url:o.z.string().optional()}).optional(),flags:o.z.object({allow_legacy_delegation_grant_types:o.z.boolean().optional(),allow_legacy_ro_grant_types:o.z.boolean().optional(),allow_legacy_tokeninfo_endpoint:o.z.boolean().optional(),disable_clickjack_protection_headers:o.z.boolean().optional(),enable_apis_section:o.z.boolean().optional(),enable_client_connections:o.z.boolean().optional(),enable_custom_domain_in_emails:o.z.boolean().optional(),enable_dynamic_client_registration:o.z.boolean().optional(),enable_idtoken_api2:o.z.boolean().optional(),enable_legacy_logs_search_v2:o.z.boolean().optional(),enable_legacy_profile:o.z.boolean().optional(),enable_pipeline2:o.z.boolean().optional(),enable_public_signup_user_exists_error:o.z.boolean().optional(),use_scope_descriptions_for_consent:o.z.boolean().optional(),disable_management_api_sms_obfuscation:o.z.boolean().optional(),enable_adfs_waad_email_verification:o.z.boolean().optional(),revoke_refresh_token_grant:o.z.boolean().optional(),dashboard_log_streams_next:o.z.boolean().optional(),dashboard_insights_view:o.z.boolean().optional(),disable_fields_map_fix:o.z.boolean().optional(),mfa_show_factor_list_on_enrollment:o.z.boolean().optional()}).optional(),friendly_name:o.z.string().optional(),picture_url:o.z.string().optional(),support_email:o.z.string().optional(),support_url:o.z.string().optional(),sandbox_version:o.z.string().optional(),sandbox_versions_available:o.z.array(o.z.string()).optional(),change_password:o.z.object({enabled:o.z.boolean(),html:o.z.string()}).optional(),guardian_mfa_page:o.z.object({enabled:o.z.boolean(),html:o.z.string()}).optional(),default_audience:o.z.string().optional(),default_organization:o.z.string().optional(),sessions:o.z.object({oidc_logout_prompt_enabled:o.z.boolean().optional()}).optional(),mfa:o.z.object({factors:o.z.object({sms:o.z.boolean().default(!1),otp:o.z.boolean().default(!1),email:o.z.boolean().default(!1),push_notification:o.z.boolean().default(!1),webauthn_roaming:o.z.boolean().default(!1),webauthn_platform:o.z.boolean().default(!1),recovery_code:o.z.boolean().default(!1),duo:o.z.boolean().default(!1)}).optional(),sms_provider:o.z.object({provider:o.z.enum(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:o.z.object({sid:o.z.string().optional(),auth_token:o.z.string().optional(),from:o.z.string().optional(),messaging_service_sid:o.z.string().optional()}).optional(),phone_message:o.z.object({message:o.z.string().optional()}).optional()}).optional()}),jw=o.z.object({date:o.z.string().openapi({description:"Date these events occurred in ISO 8601 format",example:"2025-12-19"}),logins:o.z.number().openapi({description:"Number of logins on this date",example:150}),signups:o.z.number().openapi({description:"Number of signups on this date",example:25}),leaked_passwords:o.z.number().openapi({description:"Number of breached-password detections on this date (subscription required)",example:0}),updated_at:o.z.string().openapi({description:"Date and time this stats entry was last updated in ISO 8601 format",example:"2025-12-19T10:30:00.000Z"}),created_at:o.z.string().openapi({description:"Approximate date and time the first event occurred in ISO 8601 format",example:"2025-12-19T00:00:00.000Z"})}),FS=o.z.number().openapi({description:"Number of active users in the last 30 days",example:1234}),no=o.z.enum(["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-sms","mfa-email","mfa-recovery-code","status","device-flow","email-verification","email-otp-challenge","organizations","invitation","common","passkeys","captcha","custom-form"]),ro=o.z.record(o.z.string(),o.z.string()).openapi({type:"object",additionalProperties:{type:"string"}}),HS=o.z.object({prompt:no,language:o.z.string(),custom_text:ro});function VS(e){const[t,n]=e.split("|");if(!t||!n)throw new Error(`Invalid user_id: ${e}`);return{connection:t,id:n}}function KS(e){const{primary:t,secondaries:n,syncMethods:r=["create","update","remove","delete","set"]}=e,i={get(s,a){if(typeof a=="symbol")return s[a];const c=s[a];return typeof c!="function"?c:r.includes(a)?async(...l)=>{const u=await c.apply(s,l),d=[];for(const f of n){const p=f.adapter[a];if(typeof p!="function")continue;const h=(async()=>{try{await p.apply(f.adapter,l)}catch(_){try{f.onError?f.onError(_,a,l):console.error(`Passthrough adapter: secondary write failed for ${a}:`,_)}catch(g){console.error(`Passthrough adapter: onError handler threw for ${a}:`,g)}}})();f.blocking&&d.push(h)}return d.length>0&&await Promise.all(d),u}:c.bind(s)}};return new Proxy(t,i)}function GS(e){return e}function Ci(e){var t,n,r,i,s,a,c,l,u,d,f,p;const h=e?.options;if(!h)return{usernameIdentifierActive:!1,emailIdentifierActive:!0,usernameMinLength:1,usernameMaxLength:15};const _=h.attributes;if(_){const g=((n=(t=_.username)==null?void 0:t.identifier)==null?void 0:n.active)===!0,y=((i=(r=_.email)==null?void 0:r.identifier)==null?void 0:i.active)!==!1,m=((a=(s=_.username)==null?void 0:s.validation)==null?void 0:a.min_length)??1,v=((l=(c=_.username)==null?void 0:c.validation)==null?void 0:l.max_length)??15;return{usernameIdentifierActive:g,emailIdentifierActive:y,usernameMinLength:m,usernameMaxLength:v}}return{usernameIdentifierActive:h.requires_username===!0,emailIdentifierActive:!0,usernameMinLength:((d=(u=h.validation)==null?void 0:u.username)==null?void 0:d.min)??1,usernameMaxLength:((p=(f=h.validation)==null?void 0:f.username)==null?void 0:p.max)??15}}const uf={themeId:"default",borders:{button_border_radius:8,button_border_weight:1,buttons_style:"pill",input_border_radius:8,input_border_weight:1,inputs_style:"pill",show_widget_shadow:!0,widget_border_weight:1,widget_corner_radius:16},colors:{base_focus_color:"#7D68F4",base_hover_color:"#A091F2",body_text:"#000000",captcha_widget_theme:"auto",error:"#FC5A5A",header:"#000000",icons:"#666666",input_background:"#FFFFFF",input_border:"#BFBCD7",input_filled_text:"#000000",input_labels_placeholders:"#88869F",links_focused_components:"#7D68F4",primary_button:"#7D68F4",primary_button_label:"#FFFFFF",secondary_button_border:"#BFBCD7",secondary_button_label:"#000000",success:"#36BF76",widget_background:"#FFFFFF",widget_border:"#BFBCD7"},displayName:"Default Theme",fonts:{body_text:{bold:!1,size:100},buttons_text:{bold:!0,size:100},font_url:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Regular.woff2",input_labels:{bold:!1,size:100},links:{bold:!0,size:100},links_style:"normal",reference_text_size:16,subtitle:{bold:!1,size:100},title:{bold:!0,size:150}},page_background:{background_color:"#F8F9FB",background_image_url:"",page_layout:"center"},widget:{logo_url:"",header_text_alignment:"center",logo_height:36,logo_position:"center",social_buttons_layout:"bottom"}};function Nw(e,t){const n=structuredClone(e);function r(i,s){for(const a in s)s[a]!==void 0&&typeof s[a]=="object"&&!Array.isArray(s[a])&&typeof i[a]=="object"&&i[a]!==null?r(i[a],s[a]):i[a]=s[a];return i}return r(n,t)}const WS=new o.OpenAPIHono().openapi(o.createRoute({tags:["branding"],method:"get",path:"/default",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:branding","auth:read"]}],responses:{200:{content:{"application/json":{schema:Sc}},description:"Default theme settings"}}}),async e=>{const t=await e.env.data.themes.get(e.var.tenant_id,"default");return t?e.json(t):e.json(uf)}).openapi(o.createRoute({tags:["branding"],method:"patch",path:"/default",request:{body:{content:{"application/json":{schema:Sc.deepPartial()}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:branding","auth:write"]}],responses:{200:{content:{"application/json":{schema:Sc}},description:"Updated theme settings"}}}),async e=>{const t=e.req.valid("json"),n=await e.env.data.themes.get(e.var.tenant_id,"default"),i=Nw(n||uf,t);return n?await e.env.data.themes.update(e.var.tenant_id,"default",i):await e.env.data.themes.create(e.var.tenant_id,i,"default"),e.json({...i,themeId:"default"})}),wm={colors:{primary:"#7D68F4",page_background:{type:"solid",start:"#F8F9FB",end:"#F8F9FB",angle_deg:0}},logo_url:"https://assets.sesamy.com/static/images/sesamy/logos/sesamy_logo_black.svg",favicon_url:"https://assets.sesamy.com/images/favicon.ico",font:{url:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Regular.woff2"}},km=o.z.object({body:o.z.string()}),JS=new o.OpenAPIHono().openapi(o.createRoute({tags:["branding"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:branding","auth:read"]}],responses:{200:{content:{"application/json":{schema:xc}},description:"Branding settings"}}}),async e=>{const t=await e.env.data.branding.get(e.var.tenant_id);return t?e.json(t):e.json(wm)}).openapi(o.createRoute({tags:["branding"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object(xc.shape).partial()}}}},security:[{Bearer:["update:branding","auth:write"]}],responses:{200:{content:{"application/json":{schema:xc}},description:"Branding settings"}}}),async e=>{const t=e.req.valid("json");await e.env.data.branding.set(e.var.tenant_id,t);const n=await e.env.data.branding.get(e.var.tenant_id);return e.json(n||wm)}).openapi(o.createRoute({tags:["branding"],method:"get",path:"/templates/universal-login",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:branding","auth:read"]}],responses:{200:{content:{"application/json":{schema:km}},description:"Universal login template"},404:{description:"Template not found"}}}),async e=>{const t=await e.env.data.universalLoginTemplates.get(e.var.tenant_id);if(!t)throw new I(404,{message:"Template not found"});return e.json(t)}).openapi(o.createRoute({tags:["branding"],method:"put",path:"/templates/universal-login",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:km}}}},security:[{Bearer:["update:branding","auth:write"]}],responses:{204:{description:"Template updated successfully"},400:{description:"Invalid template"}}}),async e=>{const t=e.req.valid("json");if(!t.body.includes("{%- auth0:head -%}"))throw new I(400,{message:"Template must contain {%- auth0:head -%} tag"});if(!t.body.includes("{%- auth0:widget -%}"))throw new I(400,{message:"Template must contain {%- auth0:widget -%} tag"});return await e.env.data.universalLoginTemplates.set(e.var.tenant_id,t),e.body(null,204)}).openapi(o.createRoute({tags:["branding"],method:"delete",path:"/templates/universal-login",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:branding","auth:write"]}],responses:{204:{description:"Template deleted successfully"}}}),async e=>(await e.env.data.universalLoginTemplates.delete(e.var.tenant_id),e.body(null,204))).route("/themes",WS),ZS="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let XS=e=>crypto.getRandomValues(new Uint8Array(e)),YS=(e,t,n)=>{let r=(2<<Math.log2(e.length-1))-1,i=-~(1.6*r*t/e.length);return(s=t)=>{let a="";for(;;){let c=n(i),l=i|0;for(;l--;)if(a+=e[c[l]&r]||"",a.length>=s)return a}}},Tw=(e,t=21)=>YS(e,t|0,XS),Oe=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=ZS[n[e]&63];return t};const QS=24;function Ii(){return Tw("0123456789abcdef",QS)()}function df(e){if(!e.includes("|"))return console.error("Invalid user_id format"),e;const[,t]=e.split("|");return t}class W extends I{constructor(t,n){super(t,{message:JSON.stringify(n),res:new Response(JSON.stringify(n),{status:t,headers:{"Content-Type":"application/json"}})})}}function ez(e){return async(t,n)=>{const r=n.email?.toLowerCase();if(!n.linked_to&&r&&n.email_verified){const s=await Uo({userAdapter:e.users,tenant_id:t,email:r});s&&(n.linked_to=s.user_id)}if(n.linked_to&&!await e.users.get(t,n.linked_to))throw new W(400,{error:"invalid_request",error_description:"Primary user does not exist"});const i=await e.users.create(t,n);if(n.linked_to){const s=await e.users.get(t,n.linked_to);if(!s)throw new W(500,{error:"server_error",error_description:"Failed to fetch primary user after linking"});return s}return i}}var tz={deno:"Deno",bun:"Bun",workerd:"Cloudflare-Workers",node:"Node.js"},Pw=()=>{const e=globalThis;if(typeof navigator<"u"&&typeof navigator.userAgent=="string"){for(const[n,r]of Object.entries(tz))if(nz(r))return n}return typeof e?.EdgeRuntime=="string"?"edge-light":e?.fastly!==void 0?"fastly":e?.process?.release?.name==="node"?"node":"other"},nz=e=>navigator.userAgent.startsWith(e);function Ow(e,t){if(Pw()==="workerd")try{e.executionCtx.waitUntil(t)}catch{t.catch(n=>console.error("waitUntil promise error:",n))}}function rz(e){return[...e].reduce((t,[n,r])=>({...t,[n]:r}),{})}async function fe(e,t,n){const r={};if(e.req.raw?.headers){const s=rz(e.req.raw.headers);for(const[a,c]of Object.entries(s))r[a.toLowerCase()]=c}const i=async()=>{let s;if(e.env.data.geo)try{s=await e.env.data.geo.getGeoInfo(r)||void 0}catch(c){console.warn("Failed to get geo information:",c)}const a={type:n.type,description:n.description||"",ip:e.var.ip,user_agent:e.var.useragent||"",auth0_client:e.var.auth0_client,date:new Date().toISOString(),details:{request:{method:e.req.method,path:e.req.path,qs:e.req.queries(),body:n.body||e.var.body||""},...n.response&&{response:n.response}},isMobile:!1,client_id:e.var.client_id,client_name:"",user_id:n.userId||e.var.user_id||"",hostname:e.req.header("host")||"",user_name:e.var.username||"",connection_id:"",connection:n.connection||e.var.connection||"",strategy:n.strategy||"",strategy_type:n.strategy_type||"",audience:n.audience||"",scope:n.scope||"",location_info:s};await e.env.data.logs.create(t,a)};n.waitForCompletion?await i():Ow(e,i())}class ol{constructor(t,n){this.value=t,this.unit=n}value;unit;milliseconds(){return this.unit==="ms"?this.value:this.unit==="s"?this.value*1e3:this.unit==="m"?this.value*1e3*60:this.unit==="h"?this.value*1e3*60*60:this.unit==="d"?this.value*1e3*60*60*24:this.value*1e3*60*60*24*7}seconds(){return this.milliseconds()/1e3}transform(t){return new ol(Math.round(this.milliseconds()*t),"ms")}}class iz{hash;constructor(t){this.hash=t}async verify(t,n,r){const i=await crypto.subtle.importKey("spki",t,{name:"RSASSA-PKCS1-v1_5",hash:this.hash},!1,["verify"]);return await crypto.subtle.verify("RSASSA-PKCS1-v1_5",i,n,r)}async sign(t,n){const r=await crypto.subtle.importKey("pkcs8",t,{name:"RSASSA-PKCS1-v1_5",hash:this.hash},!1,["sign"]);return await crypto.subtle.sign("RSASSA-PKCS1-v1_5",r,n)}async generateKeyPair(t){const n=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",hash:this.hash,modulusLength:t??2048,publicExponent:new Uint8Array([1,0,1])},!0,["sign"]),r=await crypto.subtle.exportKey("pkcs8",n.privateKey),i=await crypto.subtle.exportKey("spki",n.publicKey);return{privateKey:r,publicKey:i}}}async function Rw(e){return await crypto.subtle.digest("SHA-256",e)}const $m="0123456789abcdef";function pf(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.length;r++){const i=t[r]>>4;n+=$m[i];const s=t[r]&15;n+=$m[s]}return n}class Lw{alphabet;padding;decodeMap=new Map;constructor(t,n){if(t.length!==32)throw new Error("Invalid alphabet");if(this.alphabet=t,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<t.length;r++)this.decodeMap.set(t[r],r)}encode(t,n){let r="",i=0,s=0;for(let c=0;c<t.length;c++)for(i=i<<8|t[c],s+=8;s>=5;)s-=5,r+=this.alphabet[i>>s&31];if(s>0&&(r+=this.alphabet[i<<5-s&31]),n?.includePadding??!0){const c=(8-r.length%8)%8;for(let l=0;l<c;l++)r+="="}return r}decode(t,n){const r=n?.strict??!0,i=Math.ceil(t.length/8),s=[];for(let a=0;a<i;a++){let c=0;const l=[];for(let d=0;d<8;d++){const f=t[a*8+d];if(f==="="){if(a+1!==i)throw new Error(`Invalid character: ${f}`);c+=1;continue}if(f===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const p=this.decodeMap.get(f)??null;if(p===null)throw new Error(`Invalid character: ${f}`);l.push(p)}if(c===8||c===7||c===5||c===2)throw new Error("Invalid padding");const u=(l[0]<<3)+(l[1]>>2);if(s.push(u),c<6){const d=((l[1]&3)<<6)+(l[2]<<1)+(l[3]>>4);s.push(d)}if(c<4){const d=((l[3]&255)<<4)+(l[4]>>1);s.push(d)}if(c<3){const d=((l[4]&1)<<7)+(l[5]<<2)+(l[6]>>3);s.push(d)}if(c<1){const d=((l[6]&7)<<5)+l[7];s.push(d)}}return Uint8Array.from(s)}}new Lw("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");new Lw("0123456789ABCDEFGHIJKLMNOPQRSTUV");class Dw{alphabet;padding;decodeMap=new Map;constructor(t,n){if(t.length!==64)throw new Error("Invalid alphabet");if(this.alphabet=t,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<t.length;r++)this.decodeMap.set(t[r],r)}encode(t,n){let r="",i=0,s=0;for(let c=0;c<t.length;c++)for(i=i<<8|t[c],s+=8;s>=6;)s+=-6,r+=this.alphabet[i>>s&63];if(s>0&&(r+=this.alphabet[i<<6-s&63]),n?.includePadding??!0){const c=(4-r.length%4)%4;for(let l=0;l<c;l++)r+="="}return r}decode(t,n){const r=n?.strict??!0,i=Math.ceil(t.length/4),s=[];for(let a=0;a<i;a++){let c=0,l=0;for(let u=0;u<4;u++){const d=t[a*4+u];if(d==="="){if(a+1!==i)throw new Error(`Invalid character: ${d}`);c+=1;continue}if(d===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const f=this.decodeMap.get(d)??null;if(f===null)throw new Error(`Invalid character: ${d}`);l+=f<<6*(3-u)}s.push(l>>16&255),c<2&&s.push(l>>8&255),c<1&&s.push(l&255)}return Uint8Array.from(s)}}const oz=new Dw("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),wr=new Dw("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");async function xm(e,t,n,r){const i={alg:e,typ:"JWT",...r?.headers},s={...n};r?.audiences!==void 0&&(s.aud=r.audiences),r?.subject!==void 0&&(s.sub=r.subject),r?.issuer!==void 0&&(s.iss=r.issuer),r?.jwtId!==void 0&&(s.jti=r.jwtId),r?.expiresIn!==void 0&&(s.exp=Math.floor(Date.now()/1e3)+r.expiresIn.seconds()),r?.notBefore!==void 0&&(s.nbf=Math.floor(r.notBefore.getTime()/1e3)),s.iat=Math.floor(Date.now()/1e3);const a=new TextEncoder,c=wr.encode(a.encode(JSON.stringify(i)),{includePadding:!1}),l=wr.encode(a.encode(JSON.stringify(s)),{includePadding:!1}),u=a.encode([c,l].join(".")),d=await az(e).sign(t,u),f=wr.encode(new Uint8Array(d),{includePadding:!1});return[c,l,f].join(".")}function sz(e){const t=e.split(".");return t.length!==3?null:t}function za(e){const t=sz(e);if(!t)return null;const n=new TextDecoder,r=wr.decode(t[0],{strict:!1}),i=wr.decode(t[1],{strict:!1}),s=JSON.parse(n.decode(r));if(typeof s!="object"||s===null||!("alg"in s)||!cz(s.alg)||"typ"in s&&s.typ!=="JWT")return null;const a=JSON.parse(n.decode(i));if(typeof a!="object"||a===null)return null;const c={algorithm:s.alg,expiresAt:null,subject:null,issuedAt:null,issuer:null,jwtId:null,audiences:null,notBefore:null};if("exp"in a){if(typeof a.exp!="number")return null;c.expiresAt=new Date(a.exp*1e3)}if("iss"in a){if(typeof a.iss!="string")return null;c.issuer=a.iss}if("sub"in a){if(typeof a.sub!="string")return null;c.subject=a.sub}if("aud"in a)if(Array.isArray(a.aud)){for(const l of a.aud)if(typeof l!="string")return null;c.audiences=a.aud}else{if(typeof a.aud!="string")return null;c.audiences=[a.aud]}if("nbf"in a){if(typeof a.nbf!="number")return null;c.notBefore=new Date(a.nbf*1e3)}if("iat"in a){if(typeof a.iat!="number")return null;c.issuedAt=new Date(a.iat*1e3)}if("jti"in a){if(typeof a.jti!="string")return null;c.jwtId=a.jti}return{value:e,header:{...s,typ:"JWT",alg:s.alg},payload:{...a},parts:t,...c}}function az(e){return new iz(lz[e])}function cz(e){return typeof e!="string"?!1:["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512","PS256","PS384","PS512"].includes(e)}const lz={RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512"};function Ac(e){const t=new Error(e);return t.source="ulid",t}const kh="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ls=kh.length,Sm=Math.pow(2,48)-1,uz=10,dz=16;function pz(e){let t=Math.floor(e()*Ls);return t===Ls&&(t=Ls-1),kh.charAt(t)}function fz(e,t){if(isNaN(e))throw new Error(e+" must be a number");if(e>Sm)throw Ac("cannot encode time greater than "+Sm);if(e<0)throw Ac("time must be positive");if(Number.isInteger(Number(e))===!1)throw Ac("time must be an integer");let n,r="";for(;t>0;t--)n=e%Ls,r=kh.charAt(n)+r,e=(e-n)/Ls;return r}function hz(e,t){let n="";for(;e>0;e--)n=pz(t)+n;return n}function _z(e=!1,t){t||(t=typeof window<"u"?window:null);const n=t&&(t.crypto||t.msCrypto);if(n)return()=>{const r=new Uint8Array(1);return n.getRandomValues(r),r[0]/255};try{const r=require("crypto");return()=>r.randomBytes(1).readUInt8()/255}catch{}if(e){try{console.error("secure crypto unusable, falling back to insecure Math.random()!")}catch{}return()=>Math.random()}throw Ac("secure crypto unusable, insecure Math.random not allowed")}function mz(e){return e||(e=_z()),function(n){return isNaN(n)&&(n=Date.now()),fz(n,uz)+hz(dz,e)}}const Uw=mz();function gz(){const e=new Uint8Array(32);return crypto.getRandomValues(e),wr.encode(e,{includePadding:!1})}function yz(e){try{const n=/-----BEGIN (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----([^-]*)-----END (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----/.exec(e);if(!n||!n[1])throw new Error("Invalid PEM format");return Uint8Array.from(atob(n[1].replace(/\s/g,"")),r=>r.charCodeAt(0)).buffer}finally{e=e.replace(/./g,"\0")}}async function bz(e,t){if(t==="plain")return e;const n=new TextEncoder().encode(e),r=await Rw(n);return wr.encode(new Uint8Array(r),{includePadding:!1})}const Pe="auth2",sc=300,pu=720*60*60,li=1440*60,vz="auth-token",Ds=1800*1e3,ff=10080*60*1e3,wz=300,kz=300,$z=1800*1e3,xz=1800*1e3,Sz=1440*60*1e3;var zm=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Bw(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function zz(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function r(){var i=!1;try{i=this instanceof r}catch{}return i?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}),n}var Yt={},Am;function Az(){if(Am)return Yt;Am=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.parseCookie=c,Yt.parse=c,Yt.stringifyCookie=l,Yt.stringifySetCookie=u,Yt.serialize=u,Yt.parseSetCookie=d,Yt.stringifySetCookie=u,Yt.serialize=u;const e=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,t=/^[\u0021-\u003A\u003C-\u007E]*$/,n=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,r=/^[\u0020-\u003A\u003D-\u007E]*$/,i=/^-?\d+$/,s=Object.prototype.toString,a=(()=>{const y=function(){};return y.prototype=Object.create(null),y})();function c(y,m){const v=new a,k=y.length;if(k<2)return v;const x=m?.decode||_;let b=0;do{const S=p(y,b,k);if(S===-1)break;const A=f(y,b,k);if(S>A){b=y.lastIndexOf(";",S-1)+1;continue}const C=h(y,b,S);v[C]===void 0&&(v[C]=x(h(y,S+1,A))),b=A+1}while(b<k);return v}function l(y,m){const v=m?.encode||encodeURIComponent,k=[];for(const x of Object.keys(y)){const b=y[x];if(b===void 0)continue;if(!e.test(x))throw new TypeError(`cookie name is invalid: ${x}`);const S=v(b);if(!t.test(S))throw new TypeError(`cookie val is invalid: ${b}`);k.push(`${x}=${S}`)}return k.join("; ")}function u(y,m,v){const k=typeof y=="object"?y:{...v,name:y,value:String(m)},b=(typeof m=="object"?m:v)?.encode||encodeURIComponent;if(!e.test(k.name))throw new TypeError(`argument name is invalid: ${k.name}`);const S=k.value?b(k.value):"";if(!t.test(S))throw new TypeError(`argument val is invalid: ${k.value}`);let A=k.name+"="+S;if(k.maxAge!==void 0){if(!Number.isInteger(k.maxAge))throw new TypeError(`option maxAge is invalid: ${k.maxAge}`);A+="; Max-Age="+k.maxAge}if(k.domain){if(!n.test(k.domain))throw new TypeError(`option domain is invalid: ${k.domain}`);A+="; Domain="+k.domain}if(k.path){if(!r.test(k.path))throw new TypeError(`option path is invalid: ${k.path}`);A+="; Path="+k.path}if(k.expires){if(!g(k.expires)||!Number.isFinite(k.expires.valueOf()))throw new TypeError(`option expires is invalid: ${k.expires}`);A+="; Expires="+k.expires.toUTCString()}if(k.httpOnly&&(A+="; HttpOnly"),k.secure&&(A+="; Secure"),k.partitioned&&(A+="; Partitioned"),k.priority)switch(typeof k.priority=="string"?k.priority.toLowerCase():void 0){case"low":A+="; Priority=Low";break;case"medium":A+="; Priority=Medium";break;case"high":A+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${k.priority}`)}if(k.sameSite)switch(typeof k.sameSite=="string"?k.sameSite.toLowerCase():k.sameSite){case!0:case"strict":A+="; SameSite=Strict";break;case"lax":A+="; SameSite=Lax";break;case"none":A+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${k.sameSite}`)}return A}function d(y,m){const v=m?.decode||_,k=y.length,x=f(y,0,k),b=p(y,0,x),S=b===-1?{name:"",value:v(h(y,0,x))}:{name:h(y,0,b),value:v(h(y,b+1,x))};let A=x+1;for(;A<k;){const C=f(y,A,k),P=p(y,A,C),R=P===-1?h(y,A,C):h(y,A,P),E=P===-1?void 0:h(y,P+1,C);switch(R.toLowerCase()){case"httponly":S.httpOnly=!0;break;case"secure":S.secure=!0;break;case"partitioned":S.partitioned=!0;break;case"domain":S.domain=E;break;case"path":S.path=E;break;case"max-age":E&&i.test(E)&&(S.maxAge=Number(E));break;case"expires":if(!E)break;const L=new Date(E);Number.isFinite(L.valueOf())&&(S.expires=L);break;case"priority":if(!E)break;const M=E.toLowerCase();(M==="low"||M==="medium"||M==="high")&&(S.priority=M);break;case"samesite":if(!E)break;const H=E.toLowerCase();(H==="lax"||H==="strict"||H==="none")&&(S.sameSite=H);break}A=C+1}return S}function f(y,m,v){const k=y.indexOf(";",m);return k===-1?v:k}function p(y,m,v){const k=y.indexOf("=",m);return k<v?k:-1}function h(y,m,v){let k=m,x=v;do{const b=y.charCodeAt(k);if(b!==32&&b!==9)break}while(++k<x);for(;x>k;){const b=y.charCodeAt(x-1);if(b!==32&&b!==9)break;x--}return y.slice(k,x)}function _(y){if(y.indexOf("%")===-1)return y;try{return decodeURIComponent(y)}catch{return y}}function g(y){return s.call(y)==="[object Date]"}return Yt}var Xs=Az();function fu(e){return`${e}-${vz}`}function Mw(e){if(!e)return;const[t]=e.split(":");if(!t||t==="localhost"||/^(\d{1,3}\.){3}\d{1,3}$/.test(t))return;const n=t.split(".");return n.length>2?`.${n.slice(-2).join(".")}`:`.${t}`}function Ez(e,t){if(!t)return[];const n=fu(e),r=[],i=t.split(";");for(const s of i){const[a,...c]=s.trim().split("=");a===n&&c.length>0&&r.push(c.join("="))}return r}function ui(e,t){return t?Xs.parse(t)[fu(e)]:void 0}function qw(e,t){const n=fu(e),r={path:"/",httpOnly:!0,secure:!0,maxAge:0,sameSite:"none",domain:t?Mw(t):void 0};return[Xs.serialize(n,"",r),Xs.serialize(n,"",{...r,partitioned:!0})]}function sl(e,t,n){const r=fu(e),i={path:"/",httpOnly:!0,secure:!0,sameSite:"none",domain:n?Mw(n):void 0};return[Xs.serialize(r,"",{...i,maxAge:0}),Xs.serialize(r,t,{...i,maxAge:pu,partitioned:!0})]}var Cz=Object.defineProperty,Iz=(e,t,n)=>t in e?Cz(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ao=(e,t,n)=>Iz(e,typeof t!="symbol"?t+"":t,n);const dt=o.z.object({"#text":o.z.string()}),jz=o.z.object({"#text":o.z.string(),"@_xmlns:saml":o.z.string().optional()});o.z.object({"samlp:AuthnRequest":o.z.object({"saml:Issuer":jz,"@_xmlns:samlp":o.z.string(),"@_xmlns:saml":o.z.string().optional(),"@_ForceAuthn":o.z.string().transform(e=>e.toLowerCase()==="true").optional(),"@_ID":o.z.string(),"@_IssueInstant":o.z.string().datetime(),"@_Destination":o.z.string().url(),"@_AssertionConsumerServiceURL":o.z.string().url().optional(),"@_ProtocolBinding":o.z.string().optional(),"@_Version":o.z.string()})});o.z.array(o.z.object({":@":o.z.object({"@_xmlns":o.z.string(),"@_entityID":o.z.string()}),EntityDescriptor:o.z.array(o.z.object({":@":o.z.object({"@_protocolSupportEnumeration":o.z.string()}),IDPSSODescriptor:o.z.array(o.z.union([o.z.object({KeyDescriptor:o.z.array(o.z.object({KeyInfo:o.z.array(o.z.object({X509Data:o.z.array(o.z.object({X509Certificate:o.z.array(dt)}))})),":@":o.z.object({"@_xmlns":o.z.string()})})),":@":o.z.object({"@_use":o.z.string()})}),o.z.object({SingleLogoutService:o.z.array(o.z.object({})),":@":o.z.object({"@_Binding":o.z.string(),"@_Location":o.z.string()})}),o.z.object({NameIDFormat:o.z.array(dt)}),o.z.object({SingleSignOnService:o.z.array(o.z.object({})),":@":o.z.object({"@_Binding":o.z.string(),"@_Location":o.z.string()})}),o.z.object({Attribute:o.z.array(o.z.object({})),":@":o.z.object({"@_Name":o.z.string(),"@_NameFormat":o.z.string(),"@_FriendlyName":o.z.string(),"@_xmlns":o.z.string()})})]))}))}));const Nz=o.z.object({"saml:Attribute":o.z.array(o.z.object({"saml:AttributeValue":o.z.array(o.z.object({"#text":o.z.string()})),":@":o.z.object({"@_xmlns:xs":o.z.string().optional(),"@_xmlns:xsi":o.z.string(),"@_xsi:type":o.z.string()}).optional()})),":@":o.z.object({"@_Name":o.z.string(),"@_NameFormat":o.z.string(),"@_FriendlyName":o.z.string().optional()})}),Tz=o.z.object({"ds:Transform":o.z.array(o.z.any()),":@":o.z.object({"@_Algorithm":o.z.string()})}),Em=o.z.object({"ds:Signature":o.z.array(o.z.union([o.z.object({"ds:SignedInfo":o.z.array(o.z.union([o.z.object({"ds:CanonicalizationMethod":o.z.array(o.z.object({":@":o.z.object({"@_Algorithm":o.z.string()})}))}),o.z.object({"ds:SignatureMethod":o.z.array(o.z.object({":@":o.z.object({"@_Algorithm":o.z.string()})}))}),o.z.object({"ds:Reference":o.z.array(o.z.union([o.z.object({"ds:Transforms":o.z.array(Tz)}),o.z.object({"ds:DigestMethod":o.z.array(o.z.object({":@":o.z.object({"@_Algorithm":o.z.string()})}))}),o.z.object({"ds:DigestValue":o.z.array(dt)})])),":@":o.z.object({"@_URI":o.z.string().optional()}).optional()})]))}),o.z.object({"ds:SignatureValue":o.z.array(dt)}),o.z.object({"ds:KeyInfo":o.z.array(o.z.union([o.z.object({"ds:KeyValue":o.z.array(o.z.object({"ds:RSAKeyValue":o.z.array(o.z.union([o.z.object({"ds:Modulus":o.z.array(dt)}),o.z.object({"ds:Exponent":o.z.array(dt)})]))}))}),o.z.object({"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(dt)}))}),o.z.object({"ds:KeyValue":o.z.array(o.z.object({"ds:RSAKeyValue":o.z.array(o.z.union([o.z.object({"ds:Modulus":o.z.array(dt)}),o.z.object({"ds:Exponent":o.z.array(dt)})]))})),"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(dt)}))})]))})])),":@":o.z.object({"@_xmlns:ds":o.z.string().optional()}).optional()});o.z.array(o.z.object({"samlp:Response":o.z.array(o.z.union([o.z.object({"saml:Issuer":o.z.array(dt)}),Em,o.z.object({"samlp:Status":o.z.array(o.z.object({"samlp:StatusCode":o.z.array(dt),":@":o.z.object({"@_Value":o.z.string()})}))}),o.z.object({"saml:Assertion":o.z.array(o.z.union([o.z.object({"saml:Issuer":o.z.array(dt)}),Em,o.z.object({"saml:Subject":o.z.array(o.z.union([o.z.object({"saml:NameID":o.z.array(dt),":@":o.z.object({"@_Format":o.z.string()})}),o.z.object({"saml:SubjectConfirmation":o.z.array(o.z.object({"saml:SubjectConfirmationData":o.z.array(o.z.any()),":@":o.z.object({"@_InResponseTo":o.z.string(),"@_NotOnOrAfter":o.z.string(),"@_Recipient":o.z.string()})})),":@":o.z.object({"@_Method":o.z.string()})})]))}),o.z.object({"saml:Conditions":o.z.array(o.z.object({"saml:AudienceRestriction":o.z.array(o.z.object({"saml:Audience":o.z.array(dt)}))})),":@":o.z.object({"@_NotBefore":o.z.string(),"@_NotOnOrAfter":o.z.string()})}),o.z.object({"saml:AuthnStatement":o.z.array(o.z.object({"saml:AuthnContext":o.z.array(o.z.object({"saml:AuthnContextClassRef":o.z.array(dt)}))})),":@":o.z.object({"@_AuthnInstant":o.z.string(),"@_SessionIndex":o.z.string(),"@_SessionNotOnOrAfter":o.z.string()})}),o.z.object({"saml:AttributeStatement":o.z.array(Nz)})])),":@":o.z.object({"@_xmlns":o.z.string(),"@_ID":o.z.string(),"@_IssueInstant":o.z.string(),"@_Version":o.z.string()})})])),":@":o.z.object({"@_xmlns:samlp":o.z.string(),"@_xmlns:saml":o.z.string(),"@_Destination":o.z.string(),"@_ID":o.z.string(),"@_InResponseTo":o.z.string(),"@_IssueInstant":o.z.string(),"@_Version":o.z.string()})}));var Pz={};(function(e){const t=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",n=t+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+t+"]["+n+"]*",i=new RegExp("^"+r+"$"),s=function(c,l){const u=[];let d=l.exec(c);for(;d;){const f=[];f.startIndex=l.lastIndex-d[0].length;const p=d.length;for(let h=0;h<p;h++)f.push(d[h]);u.push(f),d=l.exec(c)}return u},a=function(c){const l=i.exec(c);return!(l===null||typeof l>"u")};e.isExist=function(c){return typeof c<"u"},e.isEmptyObject=function(c){return Object.keys(c).length===0},e.merge=function(c,l,u){if(l){const d=Object.keys(l),f=d.length;for(let p=0;p<f;p++)u==="strict"?c[d[p]]=[l[d[p]]]:c[d[p]]=l[d[p]]}},e.getValue=function(c){return e.isExist(c)?c:""},e.isName=a,e.getAllMatches=s,e.nameRegexp=r})(Pz);function Oz(e){return typeof e=="function"?e:Array.isArray(e)?t=>{for(const n of e)if(typeof n=="string"&&t===n||n instanceof RegExp&&n.test(t))return!0}:()=>!1}var Rz=Oz;const Lz=`
|
|
1
|
+
"use strict";var ix=Object.create;var am=Object.defineProperty;var ox=Object.getOwnPropertyDescriptor;var sx=Object.getOwnPropertyNames;var ax=Object.getPrototypeOf,cx=Object.prototype.hasOwnProperty;var lx=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of sx(t))!cx.call(e,i)&&i!==n&&am(e,i,{get:()=>t[i],enumerable:!(r=ox(t,i))||r.enumerable});return e};var ux=(e,t,n)=>(n=e!=null?ix(ax(e)):{},lx(t||!e||!e.__esModule?am(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@hono/zod-openapi");var I=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=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})}};const _e=e=>typeof e=="string",os=()=>{let e,t;const n=new Promise((r,i)=>{e=r,t=i});return n.resolve=e,n.reject=t,n},cm=e=>e==null?"":""+e,dx=(e,t,n)=>{e.forEach(r=>{t[r]&&(n[r]=t[r])})},px=/###/g,lm=e=>e&&e.indexOf("###")>-1?e.replace(px,"."):e,um=e=>!e||_e(e),Ts=(e,t,n)=>{const r=_e(t)?t.split("."):t;let i=0;for(;i<r.length-1;){if(um(e))return{};const s=lm(r[i]);!e[s]&&n&&(e[s]=new n),Object.prototype.hasOwnProperty.call(e,s)?e=e[s]:e={},++i}return um(e)?{}:{obj:e,k:lm(r[i])}},dm=(e,t,n)=>{const{obj:r,k:i}=Ts(e,t,Object);if(r!==void 0||t.length===1){r[i]=n;return}let s=t[t.length-1],a=t.slice(0,t.length-1),c=Ts(e,a,Object);for(;c.obj===void 0&&a.length;)s=`${a[a.length-1]}.${s}`,a=a.slice(0,a.length-1),c=Ts(e,a,Object),c?.obj&&typeof c.obj[`${c.k}.${s}`]<"u"&&(c.obj=void 0);c.obj[`${c.k}.${s}`]=n},fx=(e,t,n,r)=>{const{obj:i,k:s}=Ts(e,t,Object);i[s]=i[s]||[],i[s].push(n)},Fc=(e,t)=>{const{obj:n,k:r}=Ts(e,t);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},hx=(e,t,n)=>{const r=Fc(e,n);return r!==void 0?r:Fc(t,n)},fv=(e,t,n)=>{for(const r in t)r!=="__proto__"&&r!=="constructor"&&(r in e?_e(e[r])||e[r]instanceof String||_e(t[r])||t[r]instanceof String?n&&(e[r]=t[r]):fv(e[r],t[r],n):e[r]=t[r]);return e},Vr=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var _x={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const mx=e=>_e(e)?e.replace(/[&<>"'\/]/g,t=>_x[t]):e;class gx{constructor(t){this.capacity=t,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(t){const n=this.regExpMap.get(t);if(n!==void 0)return n;const r=new RegExp(t);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(t,r),this.regExpQueue.push(t),r}}const yx=[" ",",","?","!",";"],bx=new gx(20),vx=(e,t,n)=>{t=t||"",n=n||"";const r=yx.filter(a=>t.indexOf(a)<0&&n.indexOf(a)<0);if(r.length===0)return!0;const i=bx.getRegExp(`(${r.map(a=>a==="?"?"\\?":a).join("|")})`);let s=!i.test(e);if(!s){const a=e.indexOf(n);a>0&&!i.test(e.substring(0,a))&&(s=!0)}return s},of=(e,t,n=".")=>{if(!e)return;if(e[t])return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;const r=t.split(n);let i=e;for(let s=0;s<r.length;){if(!i||typeof i!="object")return;let a,c="";for(let l=s;l<r.length;++l)if(l!==s&&(c+=n),c+=r[l],a=i[c],a!==void 0){if(["string","number","boolean"].indexOf(typeof a)>-1&&l<r.length-1)continue;s+=l-s+1;break}i=a}return i},Ws=e=>e?.replace("_","-"),wx={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console?.[e]?.apply?.(console,t)}};class Hc{constructor(t,n={}){this.init(t,n)}init(t,n={}){this.prefix=n.prefix||"i18next:",this.logger=t||wx,this.options=n,this.debug=n.debug}log(...t){return this.forward(t,"log","",!0)}warn(...t){return this.forward(t,"warn","",!0)}error(...t){return this.forward(t,"error","")}deprecate(...t){return this.forward(t,"warn","WARNING DEPRECATED: ",!0)}forward(t,n,r,i){return i&&!this.debug?null:(_e(t[0])&&(t[0]=`${r}${this.prefix} ${t[0]}`),this.logger[n](t))}create(t){return new Hc(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return t=t||this.options,t.prefix=t.prefix||this.prefix,new Hc(this.logger,t)}}var zn=new Hc;class au{constructor(){this.observers={}}on(t,n){return t.split(" ").forEach(r=>{this.observers[r]||(this.observers[r]=new Map);const i=this.observers[r].get(n)||0;this.observers[r].set(n,i+1)}),this}off(t,n){if(this.observers[t]){if(!n){delete this.observers[t];return}this.observers[t].delete(n)}}emit(t,...n){this.observers[t]&&Array.from(this.observers[t].entries()).forEach(([i,s])=>{for(let a=0;a<s;a++)i(...n)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([i,s])=>{for(let a=0;a<s;a++)i.apply(i,[t,...n])})}}class pm extends au{constructor(t,n={ns:["translation"],defaultNS:"translation"}){super(),this.data=t||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){const n=this.options.ns.indexOf(t);n>-1&&this.options.ns.splice(n,1)}getResource(t,n,r,i={}){const s=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,a=i.ignoreJSONStructure!==void 0?i.ignoreJSONStructure:this.options.ignoreJSONStructure;let c;t.indexOf(".")>-1?c=t.split("."):(c=[t,n],r&&(Array.isArray(r)?c.push(...r):_e(r)&&s?c.push(...r.split(s)):c.push(r)));const l=Fc(this.data,c);return!l&&!n&&!r&&t.indexOf(".")>-1&&(t=c[0],n=c[1],r=c.slice(2).join(".")),l||!a||!_e(r)?l:of(this.data?.[t]?.[n],r,s)}addResource(t,n,r,i,s={silent:!1}){const a=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let c=[t,n];r&&(c=c.concat(a?r.split(a):r)),t.indexOf(".")>-1&&(c=t.split("."),i=n,n=c[1]),this.addNamespaces(n),dm(this.data,c,i),s.silent||this.emit("added",t,n,r,i)}addResources(t,n,r,i={silent:!1}){for(const s in r)(_e(r[s])||Array.isArray(r[s]))&&this.addResource(t,n,s,r[s],{silent:!0});i.silent||this.emit("added",t,n,r)}addResourceBundle(t,n,r,i,s,a={silent:!1,skipCopy:!1}){let c=[t,n];t.indexOf(".")>-1&&(c=t.split("."),i=r,r=n,n=c[1]),this.addNamespaces(n);let l=Fc(this.data,c)||{};a.skipCopy||(r=JSON.parse(JSON.stringify(r))),i?fv(l,r,s):l={...l,...r},dm(this.data,c,l),a.silent||this.emit("added",t,n,r)}removeResourceBundle(t,n){this.hasResourceBundle(t,n)&&delete this.data[t][n],this.removeNamespaces(n),this.emit("removed",t,n)}hasResourceBundle(t,n){return this.getResource(t,n)!==void 0}getResourceBundle(t,n){return n||(n=this.options.defaultNS),this.getResource(t,n)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const n=this.getDataByLanguage(t);return!!(n&&Object.keys(n)||[]).find(i=>n[i]&&Object.keys(n[i]).length>0)}toJSON(){return this.data}}var hv={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,r,i){return e.forEach(s=>{t=this.processors[s]?.process(t,n,r,i)??t}),t}};const _v=Symbol("i18next/PATH_KEY");function kx(){const e=[],t=Object.create(null);let n;return t.get=(r,i)=>(n?.revoke?.(),i===_v?e:(e.push(i),n=Proxy.revocable(r,t),n.proxy)),Proxy.revocable(Object.create(null),t).proxy}function sf(e,t){const{[_v]:n}=e(kx());return n.join(t?.keySeparator??".")}const fm={},Ud=e=>!_e(e)&&typeof e!="boolean"&&typeof e!="number";class Vc extends au{constructor(t,n={}){super(),dx(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=zn.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t,n={interpolation:{}}){const r={...n};if(t==null)return!1;const i=this.resolve(t,r);if(i?.res===void 0)return!1;const s=Ud(i.res);return!(r.returnObjects===!1&&s)}extractFromKey(t,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const i=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let s=n.ns||this.options.defaultNS||[];const a=r&&t.indexOf(r)>-1,c=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!vx(t,r,i);if(a&&!c){const l=t.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:t,namespaces:_e(s)?[s]:s};const u=t.split(r);(r!==i||r===i&&this.options.ns.indexOf(u[0])>-1)&&(s=u.shift()),t=u.join(i)}return{key:t,namespaces:_e(s)?[s]:s}}translate(t,n,r){let i=typeof n=="object"?{...n}:n;if(typeof i!="object"&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof i=="object"&&(i={...i}),i||(i={}),t==null)return"";typeof t=="function"&&(t=sf(t,{...this.options,...i})),Array.isArray(t)||(t=[String(t)]);const s=i.returnDetails!==void 0?i.returnDetails:this.options.returnDetails,a=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,{key:c,namespaces:l}=this.extractFromKey(t[t.length-1],i),u=l[l.length-1];let d=i.nsSeparator!==void 0?i.nsSeparator:this.options.nsSeparator;d===void 0&&(d=":");const f=i.lng||this.language,p=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(f?.toLowerCase()==="cimode")return p?s?{res:`${u}${d}${c}`,usedKey:c,exactUsedKey:c,usedLng:f,usedNS:u,usedParams:this.getUsedParamsDetails(i)}:`${u}${d}${c}`:s?{res:c,usedKey:c,exactUsedKey:c,usedLng:f,usedNS:u,usedParams:this.getUsedParamsDetails(i)}:c;const h=this.resolve(t,i);let _=h?.res;const g=h?.usedKey||c,y=h?.exactUsedKey||c,m=["[object Number]","[object Function]","[object RegExp]"],v=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,k=!this.i18nFormat||this.i18nFormat.handleAsObject,x=i.count!==void 0&&!_e(i.count),b=Vc.hasDefaultValue(i),S=x?this.pluralResolver.getSuffix(f,i.count,i):"",A=i.ordinal&&x?this.pluralResolver.getSuffix(f,i.count,{ordinal:!1}):"",C=x&&!i.ordinal&&i.count===0,P=C&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${S}`]||i[`defaultValue${A}`]||i.defaultValue;let R=_;k&&!_&&b&&(R=P);const E=Ud(R),L=Object.prototype.toString.apply(R);if(k&&R&&E&&m.indexOf(L)<0&&!(_e(v)&&Array.isArray(R))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const M=this.options.returnedObjectHandler?this.options.returnedObjectHandler(g,R,{...i,ns:l}):`key '${c} (${this.language})' returned an object instead of string.`;return s?(h.res=M,h.usedParams=this.getUsedParamsDetails(i),h):M}if(a){const M=Array.isArray(R),H=M?[]:{},D=M?y:g;for(const Q in R)if(Object.prototype.hasOwnProperty.call(R,Q)){const pe=`${D}${a}${Q}`;b&&!_?H[Q]=this.translate(pe,{...i,defaultValue:Ud(P)?P[Q]:void 0,joinArrays:!1,ns:l}):H[Q]=this.translate(pe,{...i,joinArrays:!1,ns:l}),H[Q]===pe&&(H[Q]=R[Q])}_=H}}else if(k&&_e(v)&&Array.isArray(_))_=_.join(v),_&&(_=this.extendTranslation(_,t,i,r));else{let M=!1,H=!1;!this.isValidLookup(_)&&b&&(M=!0,_=P),this.isValidLookup(_)||(H=!0,_=c);const Q=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&H?void 0:_,pe=b&&P!==_&&this.options.updateMissing;if(H||M||pe){if(this.logger.log(pe?"updateKey":"missingKey",f,u,c,pe?P:_),a){const be=this.resolve(c,{...i,keySeparator:!1});be&&be.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let se=[];const we=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&we&&we[0])for(let be=0;be<we.length;be++)se.push(we[be]);else this.options.saveMissingTo==="all"?se=this.languageUtils.toResolveHierarchy(i.lng||this.language):se.push(i.lng||this.language);const le=(be,Ee,V)=>{const Te=b&&V!==_?V:Q;this.options.missingKeyHandler?this.options.missingKeyHandler(be,u,Ee,Te,pe,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(be,u,Ee,Te,pe,i),this.emit("missingKey",be,u,Ee,_)};this.options.saveMissing&&(this.options.saveMissingPlurals&&x?se.forEach(be=>{const Ee=this.pluralResolver.getSuffixes(be,i);C&&i[`defaultValue${this.options.pluralSeparator}zero`]&&Ee.indexOf(`${this.options.pluralSeparator}zero`)<0&&Ee.push(`${this.options.pluralSeparator}zero`),Ee.forEach(V=>{le([be],c+V,i[`defaultValue${V}`]||P)})}):le(se,c,P))}_=this.extendTranslation(_,t,i,h,r),H&&_===c&&this.options.appendNamespaceToMissingKey&&(_=`${u}${d}${c}`),(H||M)&&this.options.parseMissingKeyHandler&&(_=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${u}${d}${c}`:c,M?_:void 0,i))}return s?(h.res=_,h.usedParams=this.getUsedParamsDetails(i),h):_}extendTranslation(t,n,r,i,s){if(this.i18nFormat?.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const l=_e(t)&&(r?.interpolation?.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let u;if(l){const f=t.match(this.interpolator.nestingRegexp);u=f&&f.length}let d=r.replace&&!_e(r.replace)?r.replace:r;if(this.options.interpolation.defaultVariables&&(d={...this.options.interpolation.defaultVariables,...d}),t=this.interpolator.interpolate(t,d,r.lng||this.language||i.usedLng,r),l){const f=t.match(this.interpolator.nestingRegexp),p=f&&f.length;u<p&&(r.nest=!1)}!r.lng&&i&&i.res&&(r.lng=this.language||i.usedLng),r.nest!==!1&&(t=this.interpolator.nest(t,(...f)=>s?.[0]===f[0]&&!r.context?(this.logger.warn(`It seems you are nesting recursively key: ${f[0]} in key: ${n[0]}`),null):this.translate(...f,n),r)),r.interpolation&&this.interpolator.reset()}const a=r.postProcess||this.options.postProcess,c=_e(a)?[a]:a;return t!=null&&c?.length&&r.applyPostProcessor!==!1&&(t=hv.handle(c,t,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(r)},...r}:r,this)),t}resolve(t,n={}){let r,i,s,a,c;return _e(t)&&(t=[t]),t.forEach(l=>{if(this.isValidLookup(r))return;const u=this.extractFromKey(l,n),d=u.key;i=d;let f=u.namespaces;this.options.fallbackNS&&(f=f.concat(this.options.fallbackNS));const p=n.count!==void 0&&!_e(n.count),h=p&&!n.ordinal&&n.count===0,_=n.context!==void 0&&(_e(n.context)||typeof n.context=="number")&&n.context!=="",g=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);f.forEach(y=>{this.isValidLookup(r)||(c=y,!fm[`${g[0]}-${y}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(c)&&(fm[`${g[0]}-${y}`]=!0,this.logger.warn(`key "${i}" for languages "${g.join(", ")}" won't get resolved as namespace "${c}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),g.forEach(m=>{if(this.isValidLookup(r))return;a=m;const v=[d];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(v,d,m,y,n);else{let x;p&&(x=this.pluralResolver.getSuffix(m,n.count,n));const b=`${this.options.pluralSeparator}zero`,S=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(n.ordinal&&x.indexOf(S)===0&&v.push(d+x.replace(S,this.options.pluralSeparator)),v.push(d+x),h&&v.push(d+b)),_){const A=`${d}${this.options.contextSeparator||"_"}${n.context}`;v.push(A),p&&(n.ordinal&&x.indexOf(S)===0&&v.push(A+x.replace(S,this.options.pluralSeparator)),v.push(A+x),h&&v.push(A+b))}}let k;for(;k=v.pop();)this.isValidLookup(r)||(s=k,r=this.getResource(m,y,k,n))}))})}),{res:r,usedKey:i,exactUsedKey:s,usedLng:a,usedNS:c}}isValidLookup(t){return t!==void 0&&!(!this.options.returnNull&&t===null)&&!(!this.options.returnEmptyString&&t==="")}getResource(t,n,r,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(t,n,r,i):this.resourceStore.getResource(t,n,r,i)}getUsedParamsDetails(t={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=t.replace&&!_e(t.replace);let i=r?t.replace:t;if(r&&typeof t.count<"u"&&(i.count=t.count),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!r){i={...i};for(const s of n)delete i[s]}return i}static hasDefaultValue(t){const n="defaultValue";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&n===r.substring(0,n.length)&&t[r]!==void 0)return!0;return!1}}class hm{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=zn.create("languageUtils")}getScriptPartFromCode(t){if(t=Ws(t),!t||t.indexOf("-")<0)return null;const n=t.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(t){if(t=Ws(t),!t||t.indexOf("-")<0)return t;const n=t.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(t){if(_e(t)&&t.indexOf("-")>-1){let n;try{n=Intl.getCanonicalLocales(t)[0]}catch{}return n&&this.options.lowerCaseLng&&(n=n.toLowerCase()),n||(this.options.lowerCaseLng?t.toLowerCase():t)}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let n;return t.forEach(r=>{if(n)return;const i=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(i))&&(n=i)}),!n&&this.options.supportedLngs&&t.forEach(r=>{if(n)return;const i=this.getScriptPartFromCode(r);if(this.isSupportedCode(i))return n=i;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(a=>{if(a===s)return a;if(!(a.indexOf("-")<0&&s.indexOf("-")<0)&&(a.indexOf("-")>0&&s.indexOf("-")<0&&a.substring(0,a.indexOf("-"))===s||a.indexOf(s)===0&&s.length>1))return a})}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(t,n){if(!t)return[];if(typeof t=="function"&&(t=t(n)),_e(t)&&(t=[t]),Array.isArray(t))return t;if(!n)return t.default||[];let r=t[n];return r||(r=t[this.getScriptPartFromCode(n)]),r||(r=t[this.formatLanguageCode(n)]),r||(r=t[this.getLanguagePartFromCode(n)]),r||(r=t.default),r||[]}toResolveHierarchy(t,n){const r=this.getFallbackCodes((n===!1?[]:n)||this.options.fallbackLng||[],t),i=[],s=a=>{a&&(this.isSupportedCode(a)?i.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return _e(t)&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&s(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&s(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&s(this.getLanguagePartFromCode(t))):_e(t)&&s(this.formatLanguageCode(t)),r.forEach(a=>{i.indexOf(a)<0&&s(this.formatLanguageCode(a))}),i}}const _m={zero:0,one:1,two:2,few:3,many:4,other:5},mm={select:e=>e===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class $x{constructor(t,n={}){this.languageUtils=t,this.options=n,this.logger=zn.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(t,n={}){const r=Ws(t==="dev"?"en":t),i=n.ordinal?"ordinal":"cardinal",s=JSON.stringify({cleanedCode:r,type:i});if(s in this.pluralRulesCache)return this.pluralRulesCache[s];let a;try{a=new Intl.PluralRules(r,{type:i})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),mm;if(!t.match(/-|_/))return mm;const l=this.languageUtils.getLanguagePartFromCode(t);a=this.getRule(l,n)}return this.pluralRulesCache[s]=a,a}needsPlural(t,n={}){let r=this.getRule(t,n);return r||(r=this.getRule("dev",n)),r?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(t,n,r={}){return this.getSuffixes(t,r).map(i=>`${n}${i}`)}getSuffixes(t,n={}){let r=this.getRule(t,n);return r||(r=this.getRule("dev",n)),r?r.resolvedOptions().pluralCategories.sort((i,s)=>_m[i]-_m[s]).map(i=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i}`):[]}getSuffix(t,n,r={}){const i=this.getRule(t,r);return i?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${i.select(n)}`:(this.logger.warn(`no plural rule found for: ${t}`),this.getSuffix("dev",n,r))}}const gm=(e,t,n,r=".",i=!0)=>{let s=hx(e,t,n);return!s&&i&&_e(n)&&(s=of(e,n,r),s===void 0&&(s=of(t,n,r))),s},Bd=e=>e.replace(/\$/g,"$$$$");class ym{constructor(t={}){this.logger=zn.create("interpolator"),this.options=t,this.format=t?.interpolation?.format||(n=>n),this.init(t)}init(t={}){t.interpolation||(t.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:i,prefix:s,prefixEscaped:a,suffix:c,suffixEscaped:l,formatSeparator:u,unescapeSuffix:d,unescapePrefix:f,nestingPrefix:p,nestingPrefixEscaped:h,nestingSuffix:_,nestingSuffixEscaped:g,nestingOptionsSeparator:y,maxReplaces:m,alwaysFormat:v}=t.interpolation;this.escape=n!==void 0?n:mx,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=s?Vr(s):a||"{{",this.suffix=c?Vr(c):l||"}}",this.formatSeparator=u||",",this.unescapePrefix=d?"":f||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=p?Vr(p):h||Vr("$t("),this.nestingSuffix=_?Vr(_):g||Vr(")"),this.nestingOptionsSeparator=y||",",this.maxReplaces=m||1e3,this.alwaysFormat=v!==void 0?v:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=(n,r)=>n?.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=t(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=t(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=t(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(t,n,r,i){let s,a,c;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},u=h=>{if(h.indexOf(this.formatSeparator)<0){const m=gm(n,l,h,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(m,void 0,r,{...i,...n,interpolationkey:h}):m}const _=h.split(this.formatSeparator),g=_.shift().trim(),y=_.join(this.formatSeparator).trim();return this.format(gm(n,l,g,this.options.keySeparator,this.options.ignoreJSONStructure),y,r,{...i,...n,interpolationkey:g})};this.resetRegExp();const d=i?.missingInterpolationHandler||this.options.missingInterpolationHandler,f=i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:h=>Bd(h)},{regex:this.regexp,safeValue:h=>this.escapeValue?Bd(this.escape(h)):Bd(h)}].forEach(h=>{for(c=0;s=h.regex.exec(t);){const _=s[1].trim();if(a=u(_),a===void 0)if(typeof d=="function"){const y=d(t,s,i);a=_e(y)?y:""}else if(i&&Object.prototype.hasOwnProperty.call(i,_))a="";else if(f){a=s[0];continue}else this.logger.warn(`missed to pass in variable ${_} for interpolating ${t}`),a="";else!_e(a)&&!this.useRawValueToEscape&&(a=cm(a));const g=h.safeValue(a);if(t=t.replace(s[0],g),f?(h.regex.lastIndex+=a.length,h.regex.lastIndex-=s[0].length):h.regex.lastIndex=0,c++,c>=this.maxReplaces)break}}),t}nest(t,n,r={}){let i,s,a;const c=(l,u)=>{const d=this.nestingOptionsSeparator;if(l.indexOf(d)<0)return l;const f=l.split(new RegExp(`${Vr(d)}[ ]*{`));let p=`{${f[1]}`;l=f[0],p=this.interpolate(p,a);const h=p.match(/'/g),_=p.match(/"/g);((h?.length??0)%2===0&&!_||(_?.length??0)%2!==0)&&(p=p.replace(/'/g,'"'));try{a=JSON.parse(p),u&&(a={...u,...a})}catch(g){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,g),`${l}${d}${p}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,l};for(;i=this.nestingRegexp.exec(t);){let l=[];a={...r},a=a.replace&&!_e(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;const u=/{.*}/.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(u!==-1&&(l=i[1].slice(u).split(this.formatSeparator).map(d=>d.trim()).filter(Boolean),i[1]=i[1].slice(0,u)),s=n(c.call(this,i[1].trim(),a),a),s&&i[0]===t&&!_e(s))return s;_e(s)||(s=cm(s)),s||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${t}`),s=""),l.length&&(s=l.reduce((d,f)=>this.format(d,f,r.lng,{...r,interpolationkey:i[1].trim()}),s.trim())),t=t.replace(i[0],s),this.regexp.lastIndex=0}return t}}const xx=e=>{let t=e.toLowerCase().trim();const n={};if(e.indexOf("(")>-1){const r=e.split("(");t=r[0].toLowerCase().trim();const i=r[1].substring(0,r[1].length-1);t==="currency"&&i.indexOf(":")<0?n.currency||(n.currency=i.trim()):t==="relativetime"&&i.indexOf(":")<0?n.range||(n.range=i.trim()):i.split(";").forEach(a=>{if(a){const[c,...l]=a.split(":"),u=l.join(":").trim().replace(/^'+|'+$/g,""),d=c.trim();n[d]||(n[d]=u),u==="false"&&(n[d]=!1),u==="true"&&(n[d]=!0),isNaN(u)||(n[d]=parseInt(u,10))}})}return{formatName:t,formatOptions:n}},bm=e=>{const t={};return(n,r,i)=>{let s=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(s={...s,[i.interpolationkey]:void 0});const a=r+JSON.stringify(s);let c=t[a];return c||(c=e(Ws(r),i),t[a]=c),c(n)}},Sx=e=>(t,n,r)=>e(Ws(n),r)(t);class zx{constructor(t={}){this.logger=zn.create("formatter"),this.options=t,this.init(t)}init(t,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const r=n.cacheInBuiltFormats?bm:Sx;this.formats={number:r((i,s)=>{const a=new Intl.NumberFormat(i,{...s});return c=>a.format(c)}),currency:r((i,s)=>{const a=new Intl.NumberFormat(i,{...s,style:"currency"});return c=>a.format(c)}),datetime:r((i,s)=>{const a=new Intl.DateTimeFormat(i,{...s});return c=>a.format(c)}),relativetime:r((i,s)=>{const a=new Intl.RelativeTimeFormat(i,{...s});return c=>a.format(c,s.range||"day")}),list:r((i,s)=>{const a=new Intl.ListFormat(i,{...s});return c=>a.format(c)})}}add(t,n){this.formats[t.toLowerCase().trim()]=n}addCached(t,n){this.formats[t.toLowerCase().trim()]=bm(n)}format(t,n,r,i={}){const s=n.split(this.formatSeparator);if(s.length>1&&s[0].indexOf("(")>1&&s[0].indexOf(")")<0&&s.find(c=>c.indexOf(")")>-1)){const c=s.findIndex(l=>l.indexOf(")")>-1);s[0]=[s[0],...s.splice(1,c)].join(this.formatSeparator)}return s.reduce((c,l)=>{const{formatName:u,formatOptions:d}=xx(l);if(this.formats[u]){let f=c;try{const p=i?.formatParams?.[i.interpolationkey]||{},h=p.locale||p.lng||i.locale||i.lng||r;f=this.formats[u](c,h,{...d,...i,...p})}catch(p){this.logger.warn(p)}return f}else this.logger.warn(`there was no format function for ${u}`);return c},t)}}const Ax=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)};class Ex extends au{constructor(t,n,r,i={}){super(),this.backend=t,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=i,this.logger=zn.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=i.maxParallelReads||10,this.readingCalls=0,this.maxRetries=i.maxRetries>=0?i.maxRetries:5,this.retryTimeout=i.retryTimeout>=1?i.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(r,i.backend,i)}queueLoad(t,n,r,i){const s={},a={},c={},l={};return t.forEach(u=>{let d=!0;n.forEach(f=>{const p=`${u}|${f}`;!r.reload&&this.store.hasResourceBundle(u,f)?this.state[p]=2:this.state[p]<0||(this.state[p]===1?a[p]===void 0&&(a[p]=!0):(this.state[p]=1,d=!1,a[p]===void 0&&(a[p]=!0),s[p]===void 0&&(s[p]=!0),l[f]===void 0&&(l[f]=!0)))}),d||(c[u]=!0)}),(Object.keys(s).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(s),pending:Object.keys(a),toLoadLanguages:Object.keys(c),toLoadNamespaces:Object.keys(l)}}loaded(t,n,r){const i=t.split("|"),s=i[0],a=i[1];n&&this.emit("failedLoading",s,a,n),!n&&r&&this.store.addResourceBundle(s,a,r,void 0,void 0,{skipCopy:!0}),this.state[t]=n?-1:2,n&&r&&(this.state[t]=0);const c={};this.queue.forEach(l=>{fx(l.loaded,[s],a),Ax(l,t),n&&l.errors.push(n),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(u=>{c[u]||(c[u]={});const d=l.loaded[u];d.length&&d.forEach(f=>{c[u][f]===void 0&&(c[u][f]=!0)})}),l.done=!0,l.errors.length?l.callback(l.errors):l.callback())}),this.emit("loaded",c),this.queue=this.queue.filter(l=>!l.done)}read(t,n,r,i=0,s=this.retryTimeout,a){if(!t.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:t,ns:n,fcName:r,tried:i,wait:s,callback:a});return}this.readingCalls++;const c=(u,d)=>{if(this.readingCalls--,this.waitingReads.length>0){const f=this.waitingReads.shift();this.read(f.lng,f.ns,f.fcName,f.tried,f.wait,f.callback)}if(u&&d&&i<this.maxRetries){setTimeout(()=>{this.read.call(this,t,n,r,i+1,s*2,a)},s);return}a(u,d)},l=this.backend[r].bind(this.backend);if(l.length===2){try{const u=l(t,n);u&&typeof u.then=="function"?u.then(d=>c(null,d)).catch(c):c(null,u)}catch(u){c(u)}return}return l(t,n,c)}prepareLoading(t,n,r={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();_e(t)&&(t=this.languageUtils.toResolveHierarchy(t)),_e(n)&&(n=[n]);const s=this.queueLoad(t,n,r,i);if(!s.toLoad.length)return s.pending.length||i(),null;s.toLoad.forEach(a=>{this.loadOne(a)})}load(t,n,r){this.prepareLoading(t,n,{},r)}reload(t,n,r){this.prepareLoading(t,n,{reload:!0},r)}loadOne(t,n=""){const r=t.split("|"),i=r[0],s=r[1];this.read(i,s,"read",void 0,void 0,(a,c)=>{a&&this.logger.warn(`${n}loading namespace ${s} for language ${i} failed`,a),!a&&c&&this.logger.log(`${n}loaded namespace ${s} for language ${i}`,c),this.loaded(t,a,c)})}saveMissing(t,n,r,i,s,a={},c=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if(this.backend?.create){const l={...a,isUpdate:s},u=this.backend.create.bind(this.backend);if(u.length<6)try{let d;u.length===5?d=u(t,n,r,i,l):d=u(t,n,r,i),d&&typeof d.then=="function"?d.then(f=>c(null,f)).catch(c):c(null,d)}catch(d){c(d)}else u(t,n,r,i,c,l)}!t||!t[0]||this.store.addResource(t[0],n,r,i)}}}const Md=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]=="object"&&(t=e[1]),_e(e[1])&&(t.defaultValue=e[1]),_e(e[2])&&(t.tDescription=e[2]),typeof e[2]=="object"||typeof e[3]=="object"){const n=e[3]||e[2];Object.keys(n).forEach(r=>{t[r]=n[r]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),vm=e=>(_e(e.ns)&&(e.ns=[e.ns]),_e(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),_e(e.fallbackNS)&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs?.indexOf?.("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),typeof e.initImmediate=="boolean"&&(e.initAsync=e.initImmediate),e),oc=()=>{},Cx=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(n=>{typeof e[n]=="function"&&(e[n]=e[n].bind(e))})},mv="__i18next_supportNoticeShown",Ix=()=>typeof globalThis<"u"&&!!globalThis[mv],jx=()=>{typeof globalThis<"u"&&(globalThis[mv]=!0)},Nx=e=>!!(e?.modules?.backend?.name?.indexOf("Locize")>0||e?.modules?.backend?.constructor?.name?.indexOf("Locize")>0||e?.options?.backend?.backends&&e.options.backend.backends.some(t=>t?.name?.indexOf("Locize")>0||t?.constructor?.name?.indexOf("Locize")>0)||e?.options?.backend?.projectId||e?.options?.backend?.backendOptions&&e.options.backend.backendOptions.some(t=>t?.projectId));class Ps extends au{constructor(t={},n){if(super(),this.options=vm(t),this.services={},this.logger=zn,this.modules={external:[]},Cx(this),n&&!this.isInitialized&&!t.isClone){if(!this.options.initAsync)return this.init(t,n),this;setTimeout(()=>{this.init(t,n)},0)}}init(t={},n){this.isInitializing=!0,typeof t=="function"&&(n=t,t={}),t.defaultNS==null&&t.ns&&(_e(t.ns)?t.defaultNS=t.ns:t.ns.indexOf("translation")<0&&(t.defaultNS=t.ns[0]));const r=Md();this.options={...r,...this.options,...vm(t)},this.options.interpolation={...r.interpolation,...this.options.interpolation},t.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=t.keySeparator),t.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=t.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=r.overloadTranslationOptionHandler),this.options.showSupportNotice!==!1&&!Nx(this)&&!Ix()&&(typeof console<"u"&&typeof console.info<"u"&&console.info("🌐 i18next is maintained with support from Locize — consider powering your project with managed localization (AI, CDN, integrations): https://locize.com 💙"),jx());const i=u=>u?typeof u=="function"?new u:u:null;if(!this.options.isClone){this.modules.logger?zn.init(i(this.modules.logger),this.options):zn.init(null,this.options);let u;this.modules.formatter?u=this.modules.formatter:u=zx;const d=new hm(this.options);this.store=new pm(this.options.resources,this.options);const f=this.services;f.logger=zn,f.resourceStore=this.store,f.languageUtils=d,f.pluralResolver=new $x(d,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==r.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),u&&(!this.options.interpolation.format||this.options.interpolation.format===r.interpolation.format)&&(f.formatter=i(u),f.formatter.init&&f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new ym(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new Ex(i(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",(h,..._)=>{this.emit(h,..._)}),this.modules.languageDetector&&(f.languageDetector=i(this.modules.languageDetector),f.languageDetector.init&&f.languageDetector.init(f,this.options.detection,this.options)),this.modules.i18nFormat&&(f.i18nFormat=i(this.modules.i18nFormat),f.i18nFormat.init&&f.i18nFormat.init(this)),this.translator=new Vc(this.services,this.options),this.translator.on("*",(h,..._)=>{this.emit(h,..._)}),this.modules.external.forEach(h=>{h.init&&h.init(this)})}if(this.format=this.options.interpolation.format,n||(n=oc),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const u=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);u.length>0&&u[0]!=="dev"&&(this.options.lng=u[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(u=>{this[u]=(...d)=>this.store[u](...d)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(u=>{this[u]=(...d)=>(this.store[u](...d),this)});const c=os(),l=()=>{const u=(d,f)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),c.resolve(f),n(d,f)};if(this.languages&&!this.isInitialized)return u(null,this.t.bind(this));this.changeLanguage(this.options.lng,u)};return this.options.resources||!this.options.initAsync?l():setTimeout(l,0),c}loadResources(t,n=oc){let r=n;const i=_e(t)?t:this.language;if(typeof t=="function"&&(r=t),!this.options.resources||this.options.partialBundledLanguages){if(i?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const s=[],a=c=>{if(!c||c==="cimode")return;this.services.languageUtils.toResolveHierarchy(c).forEach(u=>{u!=="cimode"&&s.indexOf(u)<0&&s.push(u)})};i?a(i):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(l=>a(l)),this.options.preload?.forEach?.(c=>a(c)),this.services.backendConnector.load(s,this.options.ns,c=>{!c&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(c)})}else r(null)}reloadResources(t,n,r){const i=os();return typeof t=="function"&&(r=t,t=void 0),typeof n=="function"&&(r=n,n=void 0),t||(t=this.languages),n||(n=this.options.ns),r||(r=oc),this.services.backendConnector.reload(t,n,s=>{i.resolve(),r(s)}),i}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return t.type==="backend"&&(this.modules.backend=t),(t.type==="logger"||t.log&&t.warn&&t.error)&&(this.modules.logger=t),t.type==="languageDetector"&&(this.modules.languageDetector=t),t.type==="i18nFormat"&&(this.modules.i18nFormat=t),t.type==="postProcessor"&&hv.addPostProcessor(t),t.type==="formatter"&&(this.modules.formatter=t),t.type==="3rdParty"&&this.modules.external.push(t),this}setResolvedLanguage(t){if(!(!t||!this.languages)&&!(["cimode","dev"].indexOf(t)>-1)){for(let n=0;n<this.languages.length;n++){const r=this.languages[n];if(!(["cimode","dev"].indexOf(r)>-1)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}!this.resolvedLanguage&&this.languages.indexOf(t)<0&&this.store.hasLanguageSomeTranslations(t)&&(this.resolvedLanguage=t,this.languages.unshift(t))}}changeLanguage(t,n){this.isLanguageChangingTo=t;const r=os();this.emit("languageChanging",t);const i=c=>{this.language=c,this.languages=this.services.languageUtils.toResolveHierarchy(c),this.resolvedLanguage=void 0,this.setResolvedLanguage(c)},s=(c,l)=>{l?this.isLanguageChangingTo===t&&(i(l),this.translator.changeLanguage(l),this.isLanguageChangingTo=void 0,this.emit("languageChanged",l),this.logger.log("languageChanged",l)):this.isLanguageChangingTo=void 0,r.resolve((...u)=>this.t(...u)),n&&n(c,(...u)=>this.t(...u))},a=c=>{!t&&!c&&this.services.languageDetector&&(c=[]);const l=_e(c)?c:c&&c[0],u=this.store.hasLanguageSomeTranslations(l)?l:this.services.languageUtils.getBestMatchFromCodes(_e(c)?[c]:c);u&&(this.language||i(u),this.translator.language||this.translator.changeLanguage(u),this.services.languageDetector?.cacheUserLanguage?.(u)),this.loadResources(u,d=>{s(d,u)})};return!t&&this.services.languageDetector&&!this.services.languageDetector.async?a(this.services.languageDetector.detect()):!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(t),r}getFixedT(t,n,r){const i=(s,a,...c)=>{let l;typeof a!="object"?l=this.options.overloadTranslationOptionHandler([s,a].concat(c)):l={...a},l.lng=l.lng||i.lng,l.lngs=l.lngs||i.lngs,l.ns=l.ns||i.ns,l.keyPrefix!==""&&(l.keyPrefix=l.keyPrefix||r||i.keyPrefix);const u=this.options.keySeparator||".";let d;return l.keyPrefix&&Array.isArray(s)?d=s.map(f=>(typeof f=="function"&&(f=sf(f,{...this.options,...a})),`${l.keyPrefix}${u}${f}`)):(typeof s=="function"&&(s=sf(s,{...this.options,...a})),d=l.keyPrefix?`${l.keyPrefix}${u}${s}`:s),this.t(d,l)};return _e(t)?i.lng=t:i.lngs=t,i.ns=n,i.keyPrefix=r,i}t(...t){return this.translator?.translate(...t)}exists(...t){return this.translator?.exists(...t)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t,n={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],i=this.options?this.options.fallbackLng:!1,s=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const a=(c,l)=>{const u=this.services.backendConnector.state[`${c}|${l}`];return u===-1||u===0||u===2};if(n.precheck){const c=n.precheck(this,a);if(c!==void 0)return c}return!!(this.hasResourceBundle(r,t)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(r,t)&&(!i||a(s,t)))}loadNamespaces(t,n){const r=os();return this.options.ns?(_e(t)&&(t=[t]),t.forEach(i=>{this.options.ns.indexOf(i)<0&&this.options.ns.push(i)}),this.loadResources(i=>{r.resolve(),n&&n(i)}),r):(n&&n(),Promise.resolve())}loadLanguages(t,n){const r=os();_e(t)&&(t=[t]);const i=this.options.preload||[],s=t.filter(a=>i.indexOf(a)<0&&this.services.languageUtils.isSupportedCode(a));return s.length?(this.options.preload=i.concat(s),this.loadResources(a=>{r.resolve(),n&&n(a)}),r):(n&&n(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!t)return"rtl";try{const i=new Intl.Locale(t);if(i&&i.getTextInfo){const s=i.getTextInfo();if(s&&s.direction)return s.direction}}catch{}const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=this.services?.languageUtils||new hm(Md());return t.toLowerCase().indexOf("-latn")>1?"ltr":n.indexOf(r.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(t={},n){const r=new Ps(t,n);return r.createInstance=Ps.createInstance,r}cloneInstance(t={},n=oc){const r=t.forkResourceStore;r&&delete t.forkResourceStore;const i={...this.options,...t,isClone:!0},s=new Ps(i);if((t.debug!==void 0||t.prefix!==void 0)&&(s.logger=s.logger.clone(t)),["store","services","language"].forEach(c=>{s[c]=this[c]}),s.services={...this.services},s.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},r){const c=Object.keys(this.store.data).reduce((l,u)=>(l[u]={...this.store.data[u]},l[u]=Object.keys(l[u]).reduce((d,f)=>(d[f]={...l[u][f]},d),l[u]),l),{});s.store=new pm(c,i),s.services.resourceStore=s.store}if(t.interpolation){const l={...Md().interpolation,...this.options.interpolation,...t.interpolation},u={...i,interpolation:l};s.services.interpolator=new ym(u)}return s.translator=new Vc(s.services,i),s.translator.on("*",(c,...l)=>{s.emit(c,...l)}),s.init(i,n),s.translator.options=i,s.translator.backendConnector.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},s}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const T=Ps.createInstance();T.createInstance;T.dir;T.init;T.loadResources;T.reloadResources;T.use;T.changeLanguage;T.getFixedT;const he=T.t;T.exists;T.setDefaultNamespace;T.hasLoadedNamespace;T.loadNamespaces;T.loadLanguages;const jr=o.z.object({created_at:o.z.string(),updated_at:o.z.string()}),Tx=o.z.enum(["AUTH0","EMAIL","REDIRECT"]),Px=o.z.enum(["CREATE_USER","GET_USER","UPDATE_USER","SEND_REQUEST","SEND_EMAIL"]),Ox=o.z.enum(["VERIFY_EMAIL"]),gv=o.z.object({require_mx_record:o.z.boolean().optional(),block_aliases:o.z.boolean().optional(),block_free_emails:o.z.boolean().optional(),block_disposable_emails:o.z.boolean().optional(),blocklist:o.z.array(o.z.string()).optional(),allowlist:o.z.array(o.z.string()).optional()}),yv=o.z.object({id:o.z.string(),alias:o.z.string().max(100).optional(),type:o.z.literal("AUTH0"),action:o.z.literal("UPDATE_USER"),allow_failure:o.z.boolean().optional(),mask_output:o.z.boolean().optional(),params:o.z.object({connection_id:o.z.string().optional(),user_id:o.z.string(),changes:o.z.record(o.z.string(),o.z.any())})}),bv=o.z.object({id:o.z.string(),alias:o.z.string().max(100).optional(),type:o.z.literal("EMAIL"),action:o.z.literal("VERIFY_EMAIL"),allow_failure:o.z.boolean().optional(),mask_output:o.z.boolean().optional(),params:o.z.object({email:o.z.string(),rules:gv.optional()})}),vv=o.z.enum(["change-email","account","custom"]),wv=o.z.object({id:o.z.string(),alias:o.z.string().max(100).optional(),type:o.z.literal("REDIRECT"),action:o.z.literal("REDIRECT_USER"),allow_failure:o.z.boolean().optional(),mask_output:o.z.boolean().optional(),params:o.z.object({target:vv.openapi({description:"The predefined target to redirect to, or 'custom' for a custom URL"}),custom_url:o.z.string().optional().openapi({description:"Custom URL to redirect to when target is 'custom'"})})}),kv=o.z.union([yv,bv,wv]),Kc=o.z.object({name:o.z.string().min(1).max(150).openapi({description:"The name of the flow"}),actions:o.z.array(kv).optional().default([]).openapi({description:"The list of actions to execute in sequence"})}),Qi=Kc.extend({...jr.shape,id:o.z.string().openapi({description:"Unique identifier for the flow",example:"af_12tMpdJ3iek7svMyZkSh5M"})}),Rx=o.z.object({page:o.z.string().min(0).optional().default("0").transform(e=>parseInt(e,10)).openapi({description:"The page number where 0 is the first page"}),per_page:o.z.string().min(1).optional().default("10").transform(e=>parseInt(e,10)).openapi({description:"The number of items per page"}),include_totals:o.z.string().optional().default("false").transform(e=>e==="true").openapi({description:"If the total number of items should be included in the response"}),sort:o.z.string().regex(/^.+:(-1|1)$/).optional().openapi({description:"A property that should have the format 'string:-1' or 'string:1'"}),q:o.z.string().optional().openapi({description:"A lucene query string used to filter the results"})}),It=o.z.object({start:o.z.number(),limit:o.z.number(),length:o.z.number(),total:o.z.number().optional()}),$v=o.z.object({email:o.z.string().optional(),email_verified:o.z.boolean().optional(),name:o.z.string().optional(),username:o.z.string().optional(),given_name:o.z.string().optional(),phone_number:o.z.string().optional(),phone_verified:o.z.boolean().optional(),family_name:o.z.string().optional()}).catchall(o.z.any()),Gc=o.z.object({connection:o.z.string(),user_id:o.z.string(),provider:o.z.string(),isSocial:o.z.boolean(),email:o.z.string().optional(),email_verified:o.z.boolean().optional(),phone_number:o.z.string().optional(),phone_verified:o.z.boolean().optional(),username:o.z.string().optional(),access_token:o.z.string().optional(),access_token_secret:o.z.string().optional(),refresh_token:o.z.string().optional(),profileData:$v.optional()}),xv=o.z.object({formatted:o.z.string().optional(),street_address:o.z.string().optional(),locality:o.z.string().optional(),region:o.z.string().optional(),postal_code:o.z.string().optional(),country:o.z.string().optional()}).optional(),cu=o.z.object({email:o.z.string().optional().transform(e=>e&&e.toLowerCase()),username:o.z.string().refine(e=>!e.includes("@"),{message:'Usernames must not contain "@". Use the email field for email addresses.'}).optional(),phone_number:o.z.string().optional(),phone_verified:o.z.boolean().optional(),given_name:o.z.string().optional(),family_name:o.z.string().optional(),nickname:o.z.string().optional(),name:o.z.string().optional(),picture:o.z.string().optional(),locale:o.z.string().optional(),linked_to:o.z.string().optional(),profileData:o.z.string().optional(),user_id:o.z.string().optional(),app_metadata:o.z.any().default({}).optional(),user_metadata:o.z.any().default({}).optional(),middle_name:o.z.string().optional(),preferred_username:o.z.string().optional(),profile:o.z.string().optional(),website:o.z.string().optional(),gender:o.z.string().optional(),birthdate:o.z.string().optional(),zoneinfo:o.z.string().optional(),address:xv}),Wc=cu.extend({email_verified:o.z.boolean().default(!1),verify_email:o.z.boolean().optional(),last_ip:o.z.string().optional(),last_login:o.z.string().optional(),user_id:o.z.string().optional(),provider:o.z.string().optional(),connection:o.z.string(),is_social:o.z.boolean().optional(),password:o.z.object({hash:o.z.string(),algorithm:o.z.string()}).optional()}),ch=o.z.object({...Wc.omit({password:!0}).shape,...jr.shape,user_id:o.z.string(),provider:o.z.string(),is_social:o.z.boolean(),email:o.z.string().optional(),login_count:o.z.number().default(0),identities:o.z.array(Gc).optional()}),xn=ch,Lx=cu.extend({login_count:o.z.number(),multifactor:o.z.array(o.z.string()).optional(),last_ip:o.z.string().optional(),last_login:o.z.string().optional(),user_id:o.z.string()}).catchall(o.z.any()),Dx="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let Ux=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=Dx[n[e]&63];return t};const Jc=o.z.object({client_id:o.z.string().openapi({description:"ID of this client."}),name:o.z.string().min(1).openapi({description:"Name of this client (min length: 1 character, does not allow < or >)."}),description:o.z.string().max(140).optional().openapi({description:"Free text description of this client (max length: 140 characters)."}),global:o.z.boolean().default(!1).openapi({description:"Whether this is your global 'All Applications' client representing legacy tenant settings (true) or a regular client (false)."}),client_secret:o.z.string().default(()=>Ux()).optional().openapi({description:"Client secret (which you must not make public)."}),app_type:o.z.enum(["native","spa","regular_web","non_interactive","resource_server","express_configuration","rms","box","cloudbees","concur","dropbox","mscrm","echosign","egnyte","newrelic","office365","salesforce","sentry","sharepoint","slack","springcm","zendesk","zoom","sso_integration","oag"]).default("regular_web").optional().openapi({description:"The type of application this client represents"}),logo_uri:o.z.string().url().optional().openapi({description:"URL of the logo to display for this client. Recommended size is 150x150 pixels."}),is_first_party:o.z.boolean().default(!1).openapi({description:"Whether this client a first party client (true) or not (false)."}),oidc_conformant:o.z.boolean().default(!0).openapi({description:"Whether this client conforms to strict OIDC specifications (true) or uses legacy features (false)."}),auth0_conformant:o.z.boolean().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:o.z.array(o.z.string()).default([]).optional().openapi({description:"Comma-separated list of URLs whitelisted for Auth0 to use as a callback to the client after authentication."}),allowed_origins:o.z.array(o.z.string()).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:o.z.array(o.z.string()).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:o.z.array(o.z.string()).default([]).optional().openapi({description:"List of audiences/realms for SAML protocol. Used by the wsfed addon."}),allowed_clients:o.z.array(o.z.string()).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:o.z.array(o.z.string()).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:o.z.array(o.z.string()).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:o.z.record(o.z.any()).default({}).optional().openapi({description:"Native to Web SSO Configuration"}),oidc_logout:o.z.record(o.z.any()).default({}).optional().openapi({description:"Configuration for OIDC backchannel logout"}),grant_types:o.z.array(o.z.string()).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:o.z.record(o.z.any()).default({}).optional().openapi({description:"Configuration related to JWTs for the client."}),signing_keys:o.z.array(o.z.record(o.z.any())).default([]).optional().openapi({description:"Signing certificates associated with this client."}),encryption_key:o.z.record(o.z.any()).default({}).optional().openapi({description:"Encryption used for WsFed responses with this client."}),sso:o.z.boolean().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:o.z.boolean().default(!0).openapi({description:"Whether Single Sign On is disabled (true) or enabled (true). Defaults to true."}),cross_origin_authentication:o.z.boolean().default(!1).openapi({description:"Whether this client can be used to make cross-origin authentication requests (true) or it is not allowed to make such requests (false)."}),cross_origin_loc:o.z.string().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:o.z.boolean().default(!1).openapi({description:"Whether a custom login page is to be used (true) or the default provided login page (false)."}),custom_login_page:o.z.string().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page."}),custom_login_page_preview:o.z.string().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page. (Used on Previews)"}),form_template:o.z.string().optional().openapi({description:"HTML form template to be used for WS-Federation."}),addons:o.z.record(o.z.any()).default({}).optional().openapi({description:"Addons enabled for this client and their associated configurations."}),token_endpoint_auth_method:o.z.enum(["none","client_secret_post","client_secret_basic"]).default("client_secret_basic").optional().openapi({description:"Defines the requested authentication method for the token endpoint. Can be none (public client without a client secret), client_secret_post (client uses HTTP POST parameters), or client_secret_basic (client uses HTTP Basic)."}),client_metadata:o.z.record(o.z.string().max(255)).default({}).optional().openapi({description:'Metadata associated with the client, in the form of an object with string values (max 255 chars). Maximum of 10 metadata properties allowed. Field names (max 255 chars) are alphanumeric and may only include the following special characters: :,-+=_*?"/()<>@ [Tab][Space]'}),mobile:o.z.record(o.z.any()).default({}).optional().openapi({description:"Additional configuration for native mobile apps."}),initiate_login_uri:o.z.string().url().optional().openapi({description:"Initiate login uri, must be https"}),native_social_login:o.z.record(o.z.any()).default({}).optional(),refresh_token:o.z.record(o.z.any()).default({}).optional().openapi({description:"Refresh token configuration"}),default_organization:o.z.record(o.z.any()).default({}).optional().openapi({description:"Defines the default Organization ID and flows"}),organization_usage:o.z.enum(["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:o.z.enum(["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:o.z.record(o.z.any()).default({}).optional().openapi({description:"Defines client authentication methods."}),require_pushed_authorization_requests:o.z.boolean().default(!1).openapi({description:"Makes the use of Pushed Authorization Requests mandatory for this client"}),require_proof_of_possession:o.z.boolean().default(!1).openapi({description:"Makes the use of Proof-of-Possession mandatory for this client"}),signed_request_object:o.z.record(o.z.any()).default({}).optional().openapi({description:"JWT-secured Authorization Requests (JAR) settings."}),compliance_level:o.z.enum(["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:o.z.number().optional().openapi({description:"Specifies how long, in seconds, a Pushed Authorization Request URI remains valid"}),token_quota:o.z.record(o.z.any()).default({}).optional()}),Qr=o.z.object({created_at:o.z.string(),updated_at:o.z.string(),...Jc.shape}),Zc=o.z.object({client_id:o.z.string().min(1).openapi({description:"ID of the client."}),audience:o.z.string().min(1).openapi({description:"The audience (API identifier) of this client grant."}),scope:o.z.array(o.z.string()).optional().openapi({description:"Scopes allowed for this client grant."}),organization_usage:o.z.enum(["deny","allow","require"]).optional().openapi({description:"Defines whether organizations can be used with client credentials exchanges for this grant."}),allow_any_organization:o.z.boolean().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:o.z.boolean().optional().openapi({description:"If enabled, this grant is a special grant created by Auth0. It cannot be modified or deleted directly."}),subject_type:o.z.enum(["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:o.z.array(o.z.string()).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."})}),ei=o.z.object({id:o.z.string().openapi({description:"ID of the client grant."}),...Zc.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),Bx=o.z.array(ei),Ei=o.z.object({x:o.z.number(),y:o.z.number()});var lh=(e=>(e.RICH_TEXT="RICH_TEXT",e.NEXT_BUTTON="NEXT_BUTTON",e.BACK_BUTTON="BACK_BUTTON",e.SUBMIT_BUTTON="SUBMIT_BUTTON",e.DIVIDER="DIVIDER",e.TEXT="TEXT",e.EMAIL="EMAIL",e.PASSWORD="PASSWORD",e.NUMBER="NUMBER",e.PHONE="PHONE",e.DATE="DATE",e.CHECKBOX="CHECKBOX",e.RADIO="RADIO",e.SELECT="SELECT",e.HIDDEN="HIDDEN",e.LEGAL="LEGAL",e))(lh||{}),uh=(e=>(e.BLOCK="BLOCK",e.FIELD="FIELD",e))(uh||{});const lu=o.z.object({id:o.z.string(),category:o.z.nativeEnum(uh),type:o.z.nativeEnum(lh)}),Sv=lu.extend({category:o.z.literal("BLOCK"),type:o.z.literal("RICH_TEXT"),config:o.z.object({content:o.z.string()}).passthrough()}),zv=lu.extend({category:o.z.literal("BLOCK"),type:o.z.union([o.z.literal("NEXT_BUTTON"),o.z.literal("BACK_BUTTON"),o.z.literal("SUBMIT_BUTTON")]),config:o.z.object({text:o.z.string()}).passthrough()}),Av=lu.extend({category:o.z.literal("FIELD"),type:o.z.literal("LEGAL"),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional(),config:o.z.object({text:o.z.string()}).passthrough()}),Ev=lu.extend({category:o.z.literal("FIELD"),type:o.z.union([o.z.literal("TEXT"),o.z.literal("EMAIL"),o.z.literal("PASSWORD"),o.z.literal("NUMBER"),o.z.literal("PHONE"),o.z.literal("DATE"),o.z.literal("CHECKBOX"),o.z.literal("RADIO"),o.z.literal("SELECT"),o.z.literal("HIDDEN")]),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional(),config:o.z.object({label:o.z.string().optional(),placeholder:o.z.string().optional()}).passthrough()}),Cv=o.z.object({id:o.z.string(),category:o.z.string(),type:o.z.string()}).passthrough(),Iv=o.z.union([Sv,zv,Av,Ev,Cv]);var jv=(e=>(e.STEP="STEP",e.FLOW="FLOW",e.CONDITION="CONDITION",e.ACTION="ACTION",e))(jv||{});const Nv=o.z.object({id:o.z.string(),type:o.z.literal("STEP"),coordinates:Ei,alias:o.z.string().optional(),config:o.z.object({components:o.z.array(Iv),next_node:o.z.string()}).passthrough()}),Tv=o.z.object({id:o.z.string(),type:o.z.literal("FLOW"),coordinates:Ei,alias:o.z.string().optional(),config:o.z.object({flow_id:o.z.string(),next_node:o.z.string()})}),Pv=o.z.object({id:o.z.string(),type:o.z.literal("ACTION"),coordinates:Ei,alias:o.z.string().optional(),config:o.z.object({action_type:o.z.enum(["REDIRECT"]).openapi({description:"The type of action to perform"}),target:o.z.enum(["change-email","account","custom"]).openapi({description:"The predefined target to redirect to"}),custom_url:o.z.string().optional().openapi({description:"Custom URL when target is 'custom'"}),next_node:o.z.string().openapi({description:"The next node to navigate to after action (for non-redirect actions)"})}).passthrough()}),Ov=o.z.object({id:o.z.string(),type:o.z.string(),coordinates:Ei}).passthrough(),Rv=o.z.union([Nv,Tv,Pv,Ov]),Lv=o.z.object({next_node:o.z.string(),coordinates:Ei}).passthrough(),Dv=o.z.object({resume_flow:o.z.boolean().optional(),coordinates:Ei}).passthrough(),Uv=o.z.object({id:o.z.string(),name:o.z.string(),languages:o.z.object({primary:o.z.string()}).passthrough(),nodes:o.z.array(Rv),start:Lv,ending:Dv,created_at:o.z.string(),updated_at:o.z.string(),links:o.z.object({sdkSrc:o.z.string().optional(),sdk_src:o.z.string().optional()}).passthrough()}).passthrough(),Mx=Uv.omit({id:!0,created_at:!0,updated_at:!0});var ot=(e=>(e.TOKEN="token",e.ID_TOKEN="id_token",e.TOKEN_ID_TOKEN="token id_token",e.CODE="code",e))(ot||{}),pn=(e=>(e.QUERY="query",e.FRAGMENT="fragment",e.FORM_POST="form_post",e.WEB_MESSAGE="web_message",e.SAML_POST="saml_post",e))(pn||{}),uu=(e=>(e.S256="S256",e.Plain="plain",e))(uu||{});const Js=o.z.object({client_id:o.z.string(),act_as:o.z.string().optional(),response_type:o.z.nativeEnum(ot).optional(),response_mode:o.z.nativeEnum(pn).optional(),redirect_uri:o.z.string().optional(),audience:o.z.string().optional(),organization:o.z.string().optional(),state:o.z.string().optional(),nonce:o.z.string().optional(),scope:o.z.string().optional(),prompt:o.z.string().optional(),code_challenge_method:o.z.nativeEnum(uu).optional(),code_challenge:o.z.string().optional(),username:o.z.string().optional(),ui_locales:o.z.string().optional(),max_age:o.z.number().optional(),acr_values:o.z.string().optional(),vendor_id:o.z.string().optional()}),xc=o.z.object({colors:o.z.object({primary:o.z.string(),page_background:o.z.object({type:o.z.string().optional(),start:o.z.string().optional(),end:o.z.string().optional(),angle_deg:o.z.number().optional()}).optional()}).optional(),logo_url:o.z.string().optional(),favicon_url:o.z.string().optional(),powered_by_logo_url:o.z.string().optional(),font:o.z.object({url:o.z.string()}).optional()}),Bv=o.z.enum(["password_reset","email_verification","otp","authorization_code","oauth2_state","ticket"]),Mv=o.z.object({code_id:o.z.string().openapi({description:"The code that will be used in for instance an email verification flow"}),login_id:o.z.string().openapi({description:"The id of the login session that the code is connected to"}),connection_id:o.z.string().optional().openapi({description:"The connection that the code is connected to"}),code_type:Bv,code_verifier:o.z.string().optional().openapi({description:"The code verifier used in PKCE in outbound flows"}),code_challenge:o.z.string().optional().openapi({description:"The code challenge used in PKCE in outbound flows"}),code_challenge_method:o.z.enum(["plain","S256"]).optional().openapi({description:"The code challenge method used in PKCE in outbound flows"}),redirect_uri:o.z.string().optional().openapi({description:"The redirect URI associated with the code"}),nonce:o.z.string().optional().openapi({description:"The nonce value used for security in OIDC flows"}),state:o.z.string().optional().openapi({description:"The state parameter used for CSRF protection in OAuth flows"}),expires_at:o.z.string(),used_at:o.z.string().optional(),user_id:o.z.string().optional()}),qx=o.z.object({...Mv.shape,created_at:o.z.string()}),qv=o.z.object({kid:o.z.string().optional(),team_id:o.z.string().optional(),realms:o.z.string().optional(),authentication_method:o.z.string().optional(),client_id:o.z.string().optional(),client_secret:o.z.string().optional(),app_secret:o.z.string().optional(),scope:o.z.string().optional(),authorization_endpoint:o.z.string().optional(),token_endpoint:o.z.string().optional(),userinfo_endpoint:o.z.string().optional(),jwks_uri:o.z.string().optional(),discovery_url:o.z.string().optional(),issuer:o.z.string().optional(),provider:o.z.string().optional(),from:o.z.string().optional(),twilio_sid:o.z.string().optional(),twilio_token:o.z.string().optional(),icon_url:o.z.string().optional(),passwordPolicy:o.z.enum(["none","low","fair","good","excellent"]).optional(),password_complexity_options:o.z.object({min_length:o.z.number().optional()}).optional(),password_history:o.z.object({enable:o.z.boolean().optional(),size:o.z.number().optional()}).optional(),password_no_personal_info:o.z.object({enable:o.z.boolean().optional()}).optional(),password_dictionary:o.z.object({enable:o.z.boolean().optional(),dictionary:o.z.array(o.z.string()).optional()}).optional(),disable_signup:o.z.boolean().optional(),brute_force_protection:o.z.boolean().optional(),import_mode:o.z.boolean().optional(),attributes:o.z.object({email:o.z.object({identifier:o.z.object({active:o.z.boolean().optional()}).optional(),signup:o.z.object({status:o.z.enum(["required","optional","disabled"]).optional(),verification:o.z.object({active:o.z.boolean().optional()}).optional()}).optional(),validation:o.z.object({allowed:o.z.boolean().optional()}).optional(),unique:o.z.boolean().optional(),profile_required:o.z.boolean().optional(),verification_method:o.z.enum(["link","code"]).optional()}).optional(),username:o.z.object({identifier:o.z.object({active:o.z.boolean().optional()}).optional(),signup:o.z.object({status:o.z.enum(["required","optional","disabled"]).optional()}).optional(),validation:o.z.object({max_length:o.z.number().optional(),min_length:o.z.number().optional(),allowed_types:o.z.object({email:o.z.boolean().optional(),phone_number:o.z.boolean().optional()}).optional()}).optional(),profile_required:o.z.boolean().optional()}).optional(),phone_number:o.z.object({identifier:o.z.object({active:o.z.boolean().optional()}).optional(),signup:o.z.object({status:o.z.enum(["required","optional","disabled"]).optional()}).optional()}).optional()}).optional(),authentication_methods:o.z.object({password:o.z.object({enabled:o.z.boolean().optional()}).optional(),passkey:o.z.object({enabled:o.z.boolean().optional()}).optional()}).optional(),passkey_options:o.z.object({challenge_ui:o.z.enum(["both","autofill","button"]).optional(),local_enrollment_enabled:o.z.boolean().optional(),progressive_enrollment_enabled:o.z.boolean().optional()}).optional(),requires_username:o.z.boolean().optional(),validation:o.z.object({username:o.z.object({min:o.z.number().optional(),max:o.z.number().optional()}).optional()}).optional()}),Xc=o.z.object({id:o.z.string().optional(),name:o.z.string(),display_name:o.z.string().optional(),strategy:o.z.string(),options:qv.default({}),enabled_clients:o.z.array(o.z.string()).default([]).optional(),response_type:o.z.custom().optional(),response_mode:o.z.custom().optional(),is_domain_connection:o.z.boolean().optional(),show_as_button:o.z.boolean().optional(),metadata:o.z.record(o.z.any()).optional(),is_system:o.z.boolean().optional()}),_r=o.z.object({id:o.z.string(),created_at:o.z.string().transform(e=>e===null?"":e),updated_at:o.z.string().transform(e=>e===null?"":e)}).extend(Xc.shape),dh=o.z.object({domain:o.z.string(),custom_domain_id:o.z.string().optional(),type:o.z.enum(["auth0_managed_certs","self_managed_certs"]),verification_method:o.z.enum(["txt"]).optional(),tls_policy:o.z.enum(["recommended"]).optional(),custom_client_ip_header:o.z.enum(["true-client-ip","cf-connecting-ip","x-forwarded-for","x-azure-clientip","null"]).optional(),domain_metadata:o.z.record(o.z.string().max(255)).optional()}),Fv=o.z.object({name:o.z.literal("txt"),record:o.z.string(),domain:o.z.string()}),fr=o.z.object({...dh.shape,custom_domain_id:o.z.string(),primary:o.z.boolean(),status:o.z.enum(["disabled","pending","pending_verification","ready"]),origin_domain_name:o.z.string().optional(),verification:o.z.object({methods:o.z.array(Fv)}).optional(),tls_policy:o.z.string().optional()}),Fx=fr.extend({tenant_id:o.z.string()}),ph=o.z.object({id:o.z.string(),order:o.z.number().optional(),visible:o.z.boolean().optional().default(!0)}),Nr=ph.extend({category:o.z.literal("BLOCK").optional()}),Hx=Nr.extend({type:o.z.literal("DIVIDER"),config:o.z.object({}).optional()}),Vx=Nr.extend({type:o.z.literal("HTML"),config:o.z.object({content:o.z.string().optional()}).optional()}),Kx=Nr.extend({type:o.z.literal("IMAGE"),config:o.z.object({src:o.z.string().optional(),alt:o.z.string().optional(),width:o.z.number().optional(),height:o.z.number().optional()}).optional()}),Gx=Nr.extend({type:o.z.literal("JUMP_BUTTON"),config:o.z.object({text:o.z.string().optional(),target_step:o.z.string().optional()})}),Wx=Nr.extend({type:o.z.literal("RESEND_BUTTON"),config:o.z.object({text:o.z.string().optional(),resend_action:o.z.string().optional()})}),Jx=Nr.extend({type:o.z.literal("NEXT_BUTTON"),config:o.z.object({text:o.z.string().optional()})}),Zx=Nr.extend({type:o.z.literal("PREVIOUS_BUTTON"),config:o.z.object({text:o.z.string().optional()})}),Xx=Nr.extend({type:o.z.literal("RICH_TEXT"),config:o.z.object({content:o.z.string().optional()}).optional()}),fh=ph.extend({category:o.z.literal("WIDGET").optional(),label:o.z.string().min(1).optional(),hint:o.z.string().min(1).max(500).optional(),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional()}),Yx=fh.extend({type:o.z.literal("AUTH0_VERIFIABLE_CREDENTIALS"),config:o.z.object({credential_type:o.z.string().optional()})}),Qx=fh.extend({type:o.z.literal("GMAPS_ADDRESS"),config:o.z.object({api_key:o.z.string().optional()})}),eS=fh.extend({type:o.z.literal("RECAPTCHA"),config:o.z.object({site_key:o.z.string().optional()})}),yt=ph.extend({category:o.z.literal("FIELD").optional(),label:o.z.string().min(1).optional(),hint:o.z.string().min(1).max(500).optional(),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional()}),tS=yt.extend({type:o.z.literal("BOOLEAN"),config:o.z.object({default_value:o.z.boolean().optional()}).optional()}),nS=yt.extend({type:o.z.literal("CARDS"),config:o.z.object({options:o.z.array(o.z.object({value:o.z.string(),label:o.z.string(),description:o.z.string().optional(),image:o.z.string().optional()})).optional(),multi_select:o.z.boolean().optional()}).optional()}),rS=yt.extend({type:o.z.literal("CHOICE"),config:o.z.object({options:o.z.array(o.z.object({value:o.z.string(),label:o.z.string()})).optional(),display:o.z.enum(["radio","checkbox"]).optional(),multiple:o.z.boolean().optional(),default_value:o.z.union([o.z.string(),o.z.array(o.z.string())]).optional()}).optional()}),iS=yt.extend({type:o.z.literal("CUSTOM"),config:o.z.object({component:o.z.string().optional(),props:o.z.record(o.z.any()).optional(),schema:o.z.record(o.z.any()).optional(),code:o.z.string().optional()})}),oS=yt.extend({type:o.z.literal("DATE"),config:o.z.object({format:o.z.string().optional(),min:o.z.string().optional(),max:o.z.string().optional(),default_value:o.z.string().optional()}).optional()}),sS=yt.extend({type:o.z.literal("DROPDOWN"),config:o.z.object({options:o.z.array(o.z.object({value:o.z.string(),label:o.z.string()})).optional(),placeholder:o.z.string().optional(),searchable:o.z.boolean().optional(),multiple:o.z.boolean().optional(),default_value:o.z.union([o.z.string(),o.z.array(o.z.string())]).optional()}).optional()}),aS=yt.extend({type:o.z.literal("EMAIL"),config:o.z.object({placeholder:o.z.string().optional(),default_value:o.z.string().optional()}).optional()}),cS=yt.extend({type:o.z.literal("FILE"),config:o.z.object({accept:o.z.string().optional(),max_size:o.z.number().optional(),multiple:o.z.boolean().optional()}).optional()}),lS=yt.extend({type:o.z.literal("LEGAL"),config:o.z.object({text:o.z.string(),html:o.z.boolean().optional()}).optional()}),uS=yt.extend({type:o.z.literal("NUMBER"),config:o.z.object({placeholder:o.z.string().optional(),min:o.z.number().optional(),max:o.z.number().optional(),step:o.z.number().optional(),default_value:o.z.string().optional()}).optional()}),dS=yt.extend({type:o.z.literal("PASSWORD"),config:o.z.object({placeholder:o.z.string().optional(),min_length:o.z.number().optional(),show_toggle:o.z.boolean().optional(),forgot_password_link:o.z.string().optional(),default_value:o.z.string().optional()}).optional()}),pS=yt.extend({type:o.z.literal("PAYMENT"),config:o.z.object({provider:o.z.string().optional(),currency:o.z.string().optional()}).optional()}),fS=yt.extend({type:o.z.literal("SOCIAL"),config:o.z.object({providers:o.z.array(o.z.string()).optional(),provider_details:o.z.array(o.z.object({name:o.z.string(),strategy:o.z.string().optional(),display_name:o.z.string().optional(),icon_url:o.z.string().optional()})).optional()}).optional()}),hS=yt.extend({type:o.z.literal("TEL"),config:o.z.object({placeholder:o.z.string().optional(),default_country:o.z.string().optional(),default_value:o.z.string().optional()}).optional()}),_S=yt.extend({type:o.z.literal("TEXT"),config:o.z.object({placeholder:o.z.string().optional(),multiline:o.z.boolean().optional(),max_length:o.z.number().optional(),default_value:o.z.string().optional()}).optional()}),mS=yt.extend({type:o.z.literal("URL"),config:o.z.object({placeholder:o.z.string().optional(),default_value:o.z.string().optional()}).optional()}),Hv=o.z.discriminatedUnion("type",[Hx,Vx,Kx,Gx,Wx,Jx,Zx,Xx]),Vv=o.z.discriminatedUnion("type",[Yx,Qx,eS]),Kv=o.z.discriminatedUnion("type",[tS,nS,rS,iS,oS,sS,aS,cS,lS,uS,dS,pS,fS,hS,_S,mS]),hh=o.z.union([Hv,Vv,Kv]),_h=new Set(["BOOLEAN","CARDS","CHOICE","DATE","DROPDOWN","EMAIL","LEGAL","NUMBER","PASSWORD","TEL","TEXT","URL"]),gS=o.z.object({id:o.z.string(),type:o.z.literal("submit"),label:o.z.string(),className:o.z.string().optional(),disabled:o.z.boolean().optional().default(!1),order:o.z.number().optional(),visible:o.z.boolean().optional().default(!0),customizations:o.z.record(o.z.string(),o.z.any()).optional()}),Zs=o.z.object({x:o.z.number(),y:o.z.number()}),yS=o.z.object({id:o.z.string(),type:o.z.literal("FLOW"),coordinates:Zs,alias:o.z.string().min(1).max(150).optional(),config:o.z.object({flow_id:o.z.string().max(30),next_node:o.z.string().optional()})}),bS=o.z.object({id:o.z.string(),type:o.z.literal("ROUTER"),coordinates:Zs,alias:o.z.string().min(1).max(150),config:o.z.object({rules:o.z.array(o.z.object({id:o.z.string(),alias:o.z.string().min(1).max(150).optional(),condition:o.z.any(),next_node:o.z.string()})),fallback:o.z.string()})}),vS=o.z.object({id:o.z.string(),type:o.z.literal("STEP"),coordinates:Zs,alias:o.z.string().min(1).max(150).optional(),config:o.z.object({components:o.z.array(hh),next_node:o.z.string().optional()})}),Gv=o.z.discriminatedUnion("type",[yS,bS,vS]),Yc=o.z.object({name:o.z.string().openapi({description:"The name of the form"}),messages:o.z.object({errors:o.z.record(o.z.string(),o.z.any()).optional(),custom:o.z.record(o.z.string(),o.z.any()).optional()}).optional(),languages:o.z.object({primary:o.z.string().optional(),default:o.z.string().optional()}).optional(),translations:o.z.record(o.z.string(),o.z.any()).optional(),nodes:o.z.array(Gv).optional(),start:o.z.object({hidden_fields:o.z.array(o.z.object({key:o.z.string(),value:o.z.string()})).optional(),next_node:o.z.string().optional(),coordinates:Zs.optional()}).optional(),ending:o.z.object({redirection:o.z.object({delay:o.z.number().optional(),target:o.z.string().optional()}).optional(),after_submit:o.z.object({flow_id:o.z.string().optional()}).optional(),coordinates:Zs.optional(),resume_flow:o.z.boolean().optional()}).optional(),style:o.z.object({css:o.z.string().optional()}).optional(),links:o.z.object({sdkSrc:o.z.string().optional(),sdk_src:o.z.string().optional()}).optional()}).openapi({description:"Schema for flow-based forms (matches Auth0 Forms structure)"}),eo=o.z.object({...jr.shape,...Yc.shape,id:o.z.string()}),Wv=o.z.object({id:o.z.number().optional(),text:o.z.string(),type:o.z.enum(["info","error","success","warning"])}),Jv=o.z.object({id:o.z.string().optional(),text:o.z.string(),href:o.z.string(),linkText:o.z.string().optional()}),wS=o.z.object({name:o.z.string().optional(),action:o.z.string(),method:o.z.enum(["POST","GET"]),title:o.z.string().optional(),description:o.z.string().optional(),components:o.z.array(hh),messages:o.z.array(Wv).optional(),links:o.z.array(Jv).optional(),footer:o.z.string().optional()});function kS(e){return e.category==="BLOCK"}function $S(e){return e.category==="WIDGET"}function xS(e){return e.category==="FIELD"}const Zv=o.z.enum(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Xv=o.z.enum(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Yv=o.z.enum(["post-user-login","credentials-exchange"]),mh=o.z.enum(["ensure-username","set-preferred-username"]),SS={"ensure-username":{name:"Ensure Username",description:"Automatically assigns a username to users who sign in without one. Creates a linked username account for social/email users.",trigger_id:"post-user-login"},"set-preferred-username":{name:"Set Preferred Username",description:"Sets the preferred_username claim on tokens based on the username from the primary or linked user.",trigger_id:"credentials-exchange"}},Lo={enabled:o.z.boolean().default(!1),synchronous:o.z.boolean().default(!1),priority:o.z.number().optional(),hook_id:o.z.string().optional()},zS=o.z.object({...Lo,trigger_id:Zv,url:o.z.string()}),AS=o.z.object({...Lo,trigger_id:Xv,form_id:o.z.string()}),ES=o.z.object({...Lo,trigger_id:Yv,template_id:mh}),af=o.z.union([zS,AS,ES]),CS=o.z.object({...Lo,trigger_id:Zv,...jr.shape,hook_id:o.z.string(),url:o.z.string()}),IS=o.z.object({...Lo,trigger_id:Xv,...jr.shape,hook_id:o.z.string(),form_id:o.z.string()}),jS=o.z.object({...Lo,trigger_id:Yv,...jr.shape,hook_id:o.z.string(),template_id:mh}),to=o.z.union([CS,IS,jS]),Qv=o.z.object({name:o.z.string().optional()}),ew=o.z.object({email:o.z.string().optional()}),gh=o.z.object({organization_id:o.z.string().max(50),inviter:Qv,invitee:ew,invitation_url:o.z.string().url(),client_id:o.z.string(),connection_id:o.z.string().optional(),app_metadata:o.z.record(o.z.any()).default({}).optional(),user_metadata:o.z.record(o.z.any()).default({}).optional(),ttl_sec:o.z.number().int().max(2592e3).default(604800).optional(),roles:o.z.array(o.z.string()).default([]).optional(),send_invitation_email:o.z.boolean().default(!0).optional()}),Os=o.z.object({id:o.z.string(),organization_id:o.z.string().max(50),created_at:o.z.string().datetime(),expires_at:o.z.string().datetime(),ticket_id:o.z.string().optional()}).extend(gh.shape),yh=o.z.object({alg:o.z.enum(["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512"]),e:o.z.string(),kid:o.z.string(),kty:o.z.enum(["RSA","EC","oct"]),n:o.z.string(),x5t:o.z.string().optional(),x5c:o.z.array(o.z.string()).optional(),use:o.z.enum(["sig","enc"]).optional()}),tw=o.z.object({keys:o.z.array(yh)}),cf=o.z.object({issuer:o.z.string(),authorization_endpoint:o.z.string(),token_endpoint:o.z.string(),device_authorization_endpoint:o.z.string(),userinfo_endpoint:o.z.string(),mfa_challenge_endpoint:o.z.string(),jwks_uri:o.z.string(),registration_endpoint:o.z.string(),revocation_endpoint:o.z.string(),scopes_supported:o.z.array(o.z.string()),response_types_supported:o.z.array(o.z.string()),code_challenge_methods_supported:o.z.array(o.z.string()),response_modes_supported:o.z.array(o.z.string()),subject_types_supported:o.z.array(o.z.string()),id_token_signing_alg_values_supported:o.z.array(o.z.string()),token_endpoint_auth_methods_supported:o.z.array(o.z.string()),claims_supported:o.z.array(o.z.string()),request_uri_parameter_supported:o.z.boolean(),request_parameter_supported:o.z.boolean(),token_endpoint_auth_signing_alg_values_supported:o.z.array(o.z.string())});var We=(e=>(e.PENDING="pending",e.AUTHENTICATED="authenticated",e.AWAITING_EMAIL_VERIFICATION="awaiting_email_verification",e.AWAITING_HOOK="awaiting_hook",e.AWAITING_CONTINUATION="awaiting_continuation",e.COMPLETED="completed",e.FAILED="failed",e.EXPIRED="expired",e))(We||{});const nw=o.z.nativeEnum(We),rw=o.z.object({csrf_token:o.z.string(),auth0Client:o.z.string().optional(),authParams:Js,expires_at:o.z.string(),deleted_at:o.z.string().optional(),ip:o.z.string().optional(),useragent:o.z.string().optional(),session_id:o.z.string().optional(),authorization_url:o.z.string().optional(),state:nw.optional().default("pending"),state_data:o.z.string().optional(),failure_reason:o.z.string().optional(),user_id:o.z.string().optional()}).openapi({description:"This represents a login sesion"}),NS=o.z.object({...rw.shape,id:o.z.string().openapi({description:"This is is used as the state in the universal login"}),created_at:o.z.string(),updated_at:o.z.string()}),ue={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",SUCCESS_CHANGE_EMAIL:"sce",SUCCESS_CROSS_ORIGIN_AUTHENTICATION:"scoa",SUCCESS_CHANGE_PASSWORD:"scp",SUCCESS_CHANGE_PHONE_NUMBER:"scpn",SUCCESS_CHANGE_PASSWORD_REQUEST:"scpr",SUCCESS_CHANGE_USERNAME:"scu",SUCCESS_CREDENTIAL_VALIDATION:"scv",SUCCESS_DELEGATION:"sd",SUCCESS_USER_DELETION:"sdu",SUCCESS_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN:"seacft",SUCCESS_EXCHANGE_ACCESS_TOKEN_FOR_CLIENT_CREDENTIALS:"seccft",SUCCESS_EXCHANGE_CUSTOM_TOKEN:"secte",SUCCESS_EXCHANGE_DEVICE_CODE_FOR_ACCESS_TOKEN:"sede",SUCCESS_EXCHANGE_NATIVE_SOCIAL_LOGIN:"sens",SUCCESS_EXCHANGE_PASSWORD_OOB_FOR_ACCESS_TOKEN:"seoobft",SUCCESS_EXCHANGE_PASSWORD_OTP_FOR_ACCESS_TOKEN:"seotpft",SUCCESS_EXCHANGE_PASSWORD_FOR_ACCESS_TOKEN:"sepft",SUCCESS_EXCHANGE_PASSKEY_OOB_FOR_ACCESS_TOKEN:"sepkoobft",SUCCESS_EXCHANGE_PASSKEY_OTP_FOR_ACCESS_TOKEN:"sepkotpft",SUCCESS_EXCHANGE_PASSKEY_MFA_RECOVERY_FOR_ACCESS_TOKEN:"sepkrcft",SUCCESS_EXCHANGE_PASSWORD_MFA_RECOVERY_FOR_ACCESS_TOKEN:"sercft",SUCCESS_EXCHANGE_REFRESH_TOKEN_FOR_ACCESS_TOKEN:"sertft",SUCCESS_IMPERSONATION:"simp",SUCCESSFULLY_ACCEPTED_USER_INVITE:"si",BREACHED_PASSWORD_ON_SIGNUP:"signup_pwd_leak",SUCCESS_LOGOUT:"slo",SUCCESS_REVOCATION:"srrt",SUCCESS_SIGNUP:"ss",FAILED_SS_SSO_OPERATION:"ss_sso_failure",INFORMATION_FROM_SS_SSO_OPERATION:"ss_sso_info",SUCCESS_SS_SSO_OPERATION:"ss_sso_success",SUCCESS_SILENT_AUTH:"ssa",SUCCESSFUL_SCIM_OPERATION:"sscim",SUCCESSFULLY_IMPORTED_USERS:"sui",SUCCESS_VERIFICATION_EMAIL:"sv",SUCCESS_VERIFICATION_EMAIL_REQUEST:"svr",MAX_AMOUNT_OF_AUTHENTICATORS:"too_many_records",USER_LOGIN_BLOCK_RELEASED:"ublkdu",FAILED_UNIVERSAL_LOGOUT:"universal_logout_failed",SUCCESSFUL_UNIVERSAL_LOGOUT:"universal_logout_succeeded",WARNING_DURING_LOGIN:"w",WARNING_SENDING_NOTIFICATION:"wn",WARNING_USER_MANAGEMENT:"wum"},TS=o.z.string().refine(e=>Object.values(ue).includes(e),{message:"Invalid log type"}),iw=o.z.object({name:o.z.string(),version:o.z.string(),env:o.z.object({node:o.z.string().optional()}).optional()}),ow=o.z.object({country_code:o.z.string().length(2),city_name:o.z.string(),latitude:o.z.string(),longitude:o.z.string(),time_zone:o.z.string(),continent_code:o.z.string()}),sw=o.z.object({type:TS,date:o.z.string(),description:o.z.string().optional(),ip:o.z.string().optional(),user_agent:o.z.string().optional(),details:o.z.any().optional(),isMobile:o.z.boolean(),user_id:o.z.string().optional(),user_name:o.z.string().optional(),connection:o.z.string().optional(),connection_id:o.z.string().optional(),client_id:o.z.string().optional(),client_name:o.z.string().optional(),audience:o.z.string().optional(),scope:o.z.string().optional(),strategy:o.z.string().optional(),strategy_type:o.z.string().optional(),hostname:o.z.string().optional(),auth0_client:iw.optional(),log_id:o.z.string().optional(),location_info:ow.optional()}),Qc=o.z.object({...sw.shape,log_id:o.z.string()}),aw=o.z.object({id:o.z.string().optional(),user_id:o.z.string(),password:o.z.string(),algorithm:o.z.enum(["bcrypt","argon2id"]).default("argon2id"),is_current:o.z.boolean().default(!0)}),PS=aw.extend({id:o.z.string(),created_at:o.z.string(),updated_at:o.z.string()}),cw=o.z.object({initial_user_agent:o.z.string().describe("First user agent of the device from which this user logged in"),initial_ip:o.z.string().describe("First IP address associated with this session"),initial_asn:o.z.string().describe("First autonomous system number associated with this session"),last_user_agent:o.z.string().describe("Last user agent of the device from which this user logged in"),last_ip:o.z.string().describe("Last IP address from which this user logged in"),last_asn:o.z.string().describe("Last autonomous system number from which this user logged in")}),lw=o.z.object({id:o.z.string(),revoked_at:o.z.string().optional(),used_at:o.z.string().optional(),user_id:o.z.string().describe("The user ID associated with the session"),expires_at:o.z.string().optional(),login_session_id:o.z.string(),idle_expires_at:o.z.string().optional(),device:cw.describe("Metadata related to the device used in the session"),clients:o.z.array(o.z.string()).describe("List of client details for the session")}),du=o.z.object({created_at:o.z.string(),updated_at:o.z.string(),authenticated_at:o.z.string(),last_interaction_at:o.z.string(),...lw.shape}),lf=o.z.object({kid:o.z.string().openapi({description:"The key id of the signing key"}),cert:o.z.string().openapi({description:"The public certificate of the signing key"}),fingerprint:o.z.string().openapi({description:"The cert fingerprint"}),thumbprint:o.z.string().openapi({description:"The cert thumbprint"}),pkcs7:o.z.string().optional().openapi({description:"The private key in pkcs7 format"}),current:o.z.boolean().optional().openapi({description:"True if the key is the current key"}),next:o.z.boolean().optional().openapi({description:"True if the key is the next key"}),previous:o.z.boolean().optional().openapi({description:"True if the key is the previous key"}),current_since:o.z.string().optional().openapi({description:"The date and time when the key became the current key"}),current_until:o.z.string().optional().openapi({description:"The date and time when the current key was rotated"}),revoked:o.z.boolean().optional().openapi({description:"True if the key is revoked"}),revoked_at:o.z.string().optional().openapi({description:"The date and time when the key was revoked"}),connection:o.z.string().optional().openapi({description:"The connection identifier associated with the key"}),type:o.z.enum(["jwt_signing","saml_encryption"]).openapi({description:"The type of the signing key"})}),bh=o.z.object({id:o.z.string().optional(),audience:o.z.string(),friendly_name:o.z.string(),picture_url:o.z.string().optional(),support_email:o.z.string().optional(),support_url:o.z.string().optional(),sender_email:o.z.string().email(),sender_name:o.z.string(),session_lifetime:o.z.number().optional(),idle_session_lifetime:o.z.number().optional(),ephemeral_session_lifetime:o.z.number().optional(),idle_ephemeral_session_lifetime:o.z.number().optional(),session_cookie:o.z.object({mode:o.z.enum(["persistent","non-persistent"]).optional()}).optional(),allowed_logout_urls:o.z.array(o.z.string()).optional(),default_redirection_uri:o.z.string().optional(),enabled_locales:o.z.array(o.z.string()).optional(),default_directory:o.z.string().optional(),error_page:o.z.object({html:o.z.string().optional(),show_log_link:o.z.boolean().optional(),url:o.z.string().optional()}).optional(),flags:o.z.object({allow_changing_enable_sso:o.z.boolean().optional(),allow_legacy_delegation_grant_types:o.z.boolean().optional(),allow_legacy_ro_grant_types:o.z.boolean().optional(),allow_legacy_tokeninfo_endpoint:o.z.boolean().optional(),change_pwd_flow_v1:o.z.boolean().optional(),custom_domains_provisioning:o.z.boolean().optional(),dashboard_insights_view:o.z.boolean().optional(),dashboard_log_streams_next:o.z.boolean().optional(),disable_clickjack_protection_headers:o.z.boolean().optional(),disable_fields_map_fix:o.z.boolean().optional(),disable_impersonation:o.z.boolean().optional(),disable_management_api_sms_obfuscation:o.z.boolean().optional(),enable_adfs_waad_email_verification:o.z.boolean().optional(),enable_apis_section:o.z.boolean().optional(),enable_client_connections:o.z.boolean().optional(),enable_custom_domain_in_emails:o.z.boolean().optional(),enable_dynamic_client_registration:o.z.boolean().optional(),enable_idtoken_api2:o.z.boolean().optional(),enable_legacy_logs_search_v2:o.z.boolean().optional(),enable_legacy_profile:o.z.boolean().optional(),enable_pipeline2:o.z.boolean().optional(),enable_public_signup_user_exists_error:o.z.boolean().optional(),enable_sso:o.z.boolean().optional(),enforce_client_authentication_on_passwordless_start:o.z.boolean().optional(),genai_trial:o.z.boolean().optional(),improved_signup_bot_detection_in_classic:o.z.boolean().optional(),mfa_show_factor_list_on_enrollment:o.z.boolean().optional(),no_disclose_enterprise_connections:o.z.boolean().optional(),remove_alg_from_jwks:o.z.boolean().optional(),revoke_refresh_token_grant:o.z.boolean().optional(),trust_azure_adfs_email_verified_connection_property:o.z.boolean().optional(),use_scope_descriptions_for_consent:o.z.boolean().optional(),inherit_global_permissions_in_organizations:o.z.boolean().optional()}).optional(),sandbox_version:o.z.string().optional(),legacy_sandbox_version:o.z.string().optional(),sandbox_versions_available:o.z.array(o.z.string()).optional(),change_password:o.z.object({enabled:o.z.boolean().optional(),html:o.z.string().optional()}).optional(),guardian_mfa_page:o.z.object({enabled:o.z.boolean().optional(),html:o.z.string().optional()}).optional(),device_flow:o.z.object({charset:o.z.enum(["base20","digits"]).optional(),mask:o.z.string().max(20).optional()}).optional(),default_token_quota:o.z.object({clients:o.z.object({client_credentials:o.z.record(o.z.any()).optional()}).optional(),organizations:o.z.object({client_credentials:o.z.record(o.z.any()).optional()}).optional()}).optional(),default_audience:o.z.string().optional(),default_organization:o.z.string().optional(),sessions:o.z.object({oidc_logout_prompt_enabled:o.z.boolean().optional()}).optional(),oidc_logout:o.z.object({rp_logout_end_session_endpoint_discovery:o.z.boolean().optional()}).optional(),allow_organization_name_in_authentication_api:o.z.boolean().optional(),customize_mfa_in_postlogin_action:o.z.boolean().optional(),acr_values_supported:o.z.array(o.z.string()).optional(),mtls:o.z.object({enable_endpoint_aliases:o.z.boolean().optional()}).optional(),pushed_authorization_requests_supported:o.z.boolean().optional(),authorization_response_iss_parameter_supported:o.z.boolean().optional(),mfa:o.z.object({factors:o.z.object({sms:o.z.boolean().default(!1),otp:o.z.boolean().default(!1),email:o.z.boolean().default(!1),push_notification:o.z.boolean().default(!1),webauthn_roaming:o.z.boolean().default(!1),webauthn_platform:o.z.boolean().default(!1),recovery_code:o.z.boolean().default(!1),duo:o.z.boolean().default(!1)}).optional(),sms_provider:o.z.object({provider:o.z.enum(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:o.z.object({sid:o.z.string().optional(),auth_token:o.z.string().optional(),from:o.z.string().optional(),messaging_service_sid:o.z.string().optional()}).optional(),phone_message:o.z.object({message:o.z.string().optional()}).optional()}).optional()}),el=o.z.object({created_at:o.z.string().nullable().transform(e=>e??""),updated_at:o.z.string().nullable().transform(e=>e??""),...bh.shape,id:o.z.string()});var an=(e=>(e.RefreshToken="refresh_token",e.AuthorizationCode="authorization_code",e.ClientCredential="client_credentials",e.Passwordless="passwordless",e.Password="password",e.OTP="http://auth0.com/oauth/grant-type/passwordless/otp",e))(an||{});const vh=o.z.object({access_token:o.z.string(),id_token:o.z.string().optional(),scope:o.z.string().optional(),state:o.z.string().optional(),refresh_token:o.z.string().optional(),token_type:o.z.string(),expires_in:o.z.number()});o.z.object({code:o.z.string(),state:o.z.string().optional()});const uw=o.z.object({button_border_radius:o.z.number(),button_border_weight:o.z.number(),buttons_style:o.z.enum(["pill","rounded","sharp"]),input_border_radius:o.z.number(),input_border_weight:o.z.number(),inputs_style:o.z.enum(["pill","rounded","sharp"]),show_widget_shadow:o.z.boolean(),widget_border_weight:o.z.number(),widget_corner_radius:o.z.number()}),dw=o.z.object({base_focus_color:o.z.string(),base_hover_color:o.z.string(),body_text:o.z.string(),captcha_widget_theme:o.z.enum(["auto","dark","light"]),error:o.z.string(),header:o.z.string(),icons:o.z.string(),input_background:o.z.string(),input_border:o.z.string(),input_filled_text:o.z.string(),input_labels_placeholders:o.z.string(),links_focused_components:o.z.string(),primary_button:o.z.string(),primary_button_label:o.z.string(),secondary_button_border:o.z.string(),secondary_button_label:o.z.string(),success:o.z.string(),widget_background:o.z.string(),widget_border:o.z.string()}),Zr=o.z.object({bold:o.z.boolean(),size:o.z.number()}),pw=o.z.object({body_text:Zr,buttons_text:Zr,font_url:o.z.string(),input_labels:Zr,links:Zr,links_style:o.z.enum(["normal","underlined"]),reference_text_size:o.z.number(),subtitle:Zr,title:Zr}),fw=o.z.object({background_color:o.z.string(),background_image_url:o.z.string(),page_layout:o.z.enum(["center","left","right"])}),hw=o.z.object({header_text_alignment:o.z.enum(["center","left","right"]),logo_height:o.z.number(),logo_position:o.z.enum(["center","left","none","right"]),logo_url:o.z.string(),social_buttons_layout:o.z.enum(["bottom","top"])}),_w=o.z.object({borders:uw,colors:dw,displayName:o.z.string(),fonts:pw,page_background:fw,widget:hw}),Sc=_w.extend({themeId:o.z.string()}),Rs=o.z.object({universal_login_experience:o.z.enum(["new","classic"]).default("new"),identifier_first:o.z.boolean().default(!0),password_first:o.z.boolean().default(!1),webauthn_platform_first_factor:o.z.boolean()}),zc=o.z.object({name:o.z.string(),enabled:o.z.boolean().optional().default(!0),default_from_address:o.z.string().optional(),credentials:o.z.union([o.z.object({accessKeyId:o.z.string(),secretAccessKey:o.z.string(),region:o.z.string()}),o.z.object({smtp_host:o.z.array(o.z.string()),smtp_port:o.z.number(),smtp_user:o.z.string(),smtp_pass:o.z.string()}),o.z.object({api_key:o.z.string(),domain:o.z.string().optional()}),o.z.object({connectionString:o.z.string()}),o.z.object({tenantId:o.z.string(),clientId:o.z.string(),clientSecret:o.z.string()})]),settings:o.z.object({}).optional()}),wh=o.z.object({id:o.z.string(),session_id:o.z.string(),user_id:o.z.string(),client_id:o.z.string(),expires_at:o.z.string().optional(),idle_expires_at:o.z.string().optional(),last_exchanged_at:o.z.string().optional(),device:cw,resource_servers:o.z.array(o.z.object({audience:o.z.string(),scopes:o.z.string()})),rotating:o.z.boolean()}),OS=o.z.object({created_at:o.z.string(),...wh.shape}),RS=o.z.object({to:o.z.string(),message:o.z.string()}),LS=o.z.object({name:o.z.string(),options:o.z.object({})}),mw=o.z.object({value:o.z.string(),description:o.z.string().optional()}),gw=o.z.object({token_dialect:o.z.enum(["access_token","access_token_authz"]).optional(),enforce_policies:o.z.boolean().optional(),allow_skipping_userinfo:o.z.boolean().optional(),skip_userinfo:o.z.boolean().optional(),persist_client_authorization:o.z.boolean().optional(),enable_introspection_endpoint:o.z.boolean().optional(),mtls:o.z.object({bound_access_tokens:o.z.boolean().optional()}).optional()}),tl=o.z.object({id:o.z.string().optional(),name:o.z.string(),identifier:o.z.string(),scopes:o.z.array(mw).optional(),signing_alg:o.z.string().optional(),signing_secret:o.z.string().optional(),token_lifetime:o.z.number().optional(),token_lifetime_for_web:o.z.number().optional(),skip_consent_for_verifiable_first_party_clients:o.z.boolean().optional(),allow_offline_access:o.z.boolean().optional(),verificationKey:o.z.string().optional(),options:gw.optional(),is_system:o.z.boolean().optional(),metadata:o.z.record(o.z.any()).optional()}),ti=o.z.object({...tl.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),DS=o.z.array(ti),yw=o.z.object({role_id:o.z.string(),resource_server_identifier:o.z.string(),permission_name:o.z.string()}),bw=o.z.object({...yw.shape,created_at:o.z.string()}),vw=o.z.array(bw),ww=o.z.object({user_id:o.z.string(),resource_server_identifier:o.z.string(),permission_name:o.z.string(),organization_id:o.z.string().optional()}),kw=o.z.object({...ww.shape,tenant_id:o.z.string(),created_at:o.z.string().optional()}),US=o.z.array(kw),$w=o.z.object({user_id:o.z.string(),resource_server_identifier:o.z.string(),resource_server_name:o.z.string(),permission_name:o.z.string(),description:o.z.string().nullable().optional(),created_at:o.z.string().optional(),organization_id:o.z.string().optional()}),xw=o.z.array($w),Sw=o.z.object({user_id:o.z.string(),role_id:o.z.string(),organization_id:o.z.string().optional()}),zw=o.z.object({...Sw.shape,tenant_id:o.z.string(),created_at:o.z.string().optional()}),BS=o.z.array(zw),nl=o.z.object({id:o.z.string().optional().openapi({description:"The unique identifier of the role. If not provided, one will be generated."}),name:o.z.string().min(1).max(50).openapi({description:"The name of the role. Cannot include '<' or '>'"}),description:o.z.string().max(255).optional().openapi({description:"The description of the role"}),is_system:o.z.boolean().optional(),metadata:o.z.record(o.z.any()).optional().openapi({description:"Metadata associated with the role. Can be used to control sync behavior in multi-tenancy scenarios."})}),ni=nl.extend({id:o.z.string().openapi({description:"The unique identifier of the role"}),created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),rl=o.z.array(ni),Aw=o.z.object({logo_url:o.z.string().optional().openapi({description:"URL of the organization's logo"}),colors:o.z.object({primary:o.z.string().optional().openapi({description:"Primary color in hex format (e.g., #FF0000)"}),page_background:o.z.string().optional().openapi({description:"Page background color in hex format (e.g., #FFFFFF)"})}).optional()}).optional(),Ew=o.z.object({connection_id:o.z.string().openapi({description:"ID of the connection"}),assign_membership_on_login:o.z.boolean().default(!1).openapi({description:"Whether to assign membership to the organization on login"}),show_as_button:o.z.boolean().default(!0).openapi({description:"Whether to show this connection as a button in the login screen"}),is_signup_enabled:o.z.boolean().default(!0).openapi({description:"Whether signup is enabled for this connection"})}),Cw=o.z.object({client_credentials:o.z.object({enforce:o.z.boolean().default(!1).openapi({description:"Whether to enforce token quota limits"}),per_day:o.z.number().min(0).default(0).openapi({description:"Maximum tokens per day (0 = unlimited)"}),per_hour:o.z.number().min(0).default(0).openapi({description:"Maximum tokens per hour (0 = unlimited)"})}).optional()}).optional(),il=o.z.object({id:o.z.string().optional(),name:o.z.string().min(1).regex(/^[a-z0-9_-]+$/,{message:"Organization name must be lowercase and can only contain letters, numbers, hyphens, and underscores"}).openapi({description:"The name of the organization. Must be lowercase and can only contain letters, numbers, hyphens, and underscores."}),display_name:o.z.string().optional().openapi({description:"The display name of the organization"}),branding:Aw,metadata:o.z.record(o.z.any()).default({}).optional().openapi({description:"Custom metadata for the organization"}),enabled_connections:o.z.array(Ew).default([]).optional().openapi({description:"List of enabled connections for the organization"}),token_quota:Cw}),mr=o.z.object({...il.shape,...jr.shape,id:o.z.string(),name:o.z.string().min(1).openapi({description:"The name of the organization"})}),Iw=o.z.object({user_id:o.z.string().openapi({description:"ID of the user"}),organization_id:o.z.string().openapi({description:"ID of the organization"})}),MS=o.z.object({...Iw.shape,...jr.shape,id:o.z.string()}),qS=o.z.object({idle_session_lifetime:o.z.number().optional(),session_lifetime:o.z.number().optional(),session_cookie:o.z.object({mode:o.z.enum(["persistent","non-persistent"]).optional()}).optional(),enable_client_connections:o.z.boolean().optional(),default_redirection_uri:o.z.string().optional(),enabled_locales:o.z.array(o.z.string()).optional(),default_directory:o.z.string().optional(),error_page:o.z.object({html:o.z.string().optional(),show_log_link:o.z.boolean().optional(),url:o.z.string().optional()}).optional(),flags:o.z.object({allow_legacy_delegation_grant_types:o.z.boolean().optional(),allow_legacy_ro_grant_types:o.z.boolean().optional(),allow_legacy_tokeninfo_endpoint:o.z.boolean().optional(),disable_clickjack_protection_headers:o.z.boolean().optional(),enable_apis_section:o.z.boolean().optional(),enable_client_connections:o.z.boolean().optional(),enable_custom_domain_in_emails:o.z.boolean().optional(),enable_dynamic_client_registration:o.z.boolean().optional(),enable_idtoken_api2:o.z.boolean().optional(),enable_legacy_logs_search_v2:o.z.boolean().optional(),enable_legacy_profile:o.z.boolean().optional(),enable_pipeline2:o.z.boolean().optional(),enable_public_signup_user_exists_error:o.z.boolean().optional(),use_scope_descriptions_for_consent:o.z.boolean().optional(),disable_management_api_sms_obfuscation:o.z.boolean().optional(),enable_adfs_waad_email_verification:o.z.boolean().optional(),revoke_refresh_token_grant:o.z.boolean().optional(),dashboard_log_streams_next:o.z.boolean().optional(),dashboard_insights_view:o.z.boolean().optional(),disable_fields_map_fix:o.z.boolean().optional(),mfa_show_factor_list_on_enrollment:o.z.boolean().optional()}).optional(),friendly_name:o.z.string().optional(),picture_url:o.z.string().optional(),support_email:o.z.string().optional(),support_url:o.z.string().optional(),sandbox_version:o.z.string().optional(),sandbox_versions_available:o.z.array(o.z.string()).optional(),change_password:o.z.object({enabled:o.z.boolean(),html:o.z.string()}).optional(),guardian_mfa_page:o.z.object({enabled:o.z.boolean(),html:o.z.string()}).optional(),default_audience:o.z.string().optional(),default_organization:o.z.string().optional(),sessions:o.z.object({oidc_logout_prompt_enabled:o.z.boolean().optional()}).optional(),mfa:o.z.object({factors:o.z.object({sms:o.z.boolean().default(!1),otp:o.z.boolean().default(!1),email:o.z.boolean().default(!1),push_notification:o.z.boolean().default(!1),webauthn_roaming:o.z.boolean().default(!1),webauthn_platform:o.z.boolean().default(!1),recovery_code:o.z.boolean().default(!1),duo:o.z.boolean().default(!1)}).optional(),sms_provider:o.z.object({provider:o.z.enum(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:o.z.object({sid:o.z.string().optional(),auth_token:o.z.string().optional(),from:o.z.string().optional(),messaging_service_sid:o.z.string().optional()}).optional(),phone_message:o.z.object({message:o.z.string().optional()}).optional()}).optional()}),jw=o.z.object({date:o.z.string().openapi({description:"Date these events occurred in ISO 8601 format",example:"2025-12-19"}),logins:o.z.number().openapi({description:"Number of logins on this date",example:150}),signups:o.z.number().openapi({description:"Number of signups on this date",example:25}),leaked_passwords:o.z.number().openapi({description:"Number of breached-password detections on this date (subscription required)",example:0}),updated_at:o.z.string().openapi({description:"Date and time this stats entry was last updated in ISO 8601 format",example:"2025-12-19T10:30:00.000Z"}),created_at:o.z.string().openapi({description:"Approximate date and time the first event occurred in ISO 8601 format",example:"2025-12-19T00:00:00.000Z"})}),FS=o.z.number().openapi({description:"Number of active users in the last 30 days",example:1234}),no=o.z.enum(["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-sms","mfa-email","mfa-recovery-code","status","device-flow","email-verification","email-otp-challenge","organizations","invitation","common","passkeys","captcha","custom-form"]),ro=o.z.record(o.z.string(),o.z.string()).openapi({type:"object",additionalProperties:{type:"string"}}),HS=o.z.object({prompt:no,language:o.z.string(),custom_text:ro});function VS(e){const[t,n]=e.split("|");if(!t||!n)throw new Error(`Invalid user_id: ${e}`);return{connection:t,id:n}}function KS(e){const{primary:t,secondaries:n,syncMethods:r=["create","update","remove","delete","set"]}=e,i={get(s,a){if(typeof a=="symbol")return s[a];const c=s[a];return typeof c!="function"?c:r.includes(a)?async(...l)=>{const u=await c.apply(s,l),d=[];for(const f of n){const p=f.adapter[a];if(typeof p!="function")continue;const h=(async()=>{try{await p.apply(f.adapter,l)}catch(_){try{f.onError?f.onError(_,a,l):console.error(`Passthrough adapter: secondary write failed for ${a}:`,_)}catch(g){console.error(`Passthrough adapter: onError handler threw for ${a}:`,g)}}})();f.blocking&&d.push(h)}return d.length>0&&await Promise.all(d),u}:c.bind(s)}};return new Proxy(t,i)}function GS(e){return e}function Ci(e){var t,n,r,i,s,a,c,l,u,d,f,p;const h=e?.options;if(!h)return{usernameIdentifierActive:!1,emailIdentifierActive:!0,usernameMinLength:1,usernameMaxLength:15};const _=h.attributes;if(_){const g=((n=(t=_.username)==null?void 0:t.identifier)==null?void 0:n.active)===!0,y=((i=(r=_.email)==null?void 0:r.identifier)==null?void 0:i.active)!==!1,m=((a=(s=_.username)==null?void 0:s.validation)==null?void 0:a.min_length)??1,v=((l=(c=_.username)==null?void 0:c.validation)==null?void 0:l.max_length)??15;return{usernameIdentifierActive:g,emailIdentifierActive:y,usernameMinLength:m,usernameMaxLength:v}}return{usernameIdentifierActive:h.requires_username===!0,emailIdentifierActive:!0,usernameMinLength:((d=(u=h.validation)==null?void 0:u.username)==null?void 0:d.min)??1,usernameMaxLength:((p=(f=h.validation)==null?void 0:f.username)==null?void 0:p.max)??15}}const uf={themeId:"default",borders:{button_border_radius:8,button_border_weight:1,buttons_style:"pill",input_border_radius:8,input_border_weight:1,inputs_style:"pill",show_widget_shadow:!0,widget_border_weight:1,widget_corner_radius:16},colors:{base_focus_color:"#7D68F4",base_hover_color:"#A091F2",body_text:"#000000",captcha_widget_theme:"auto",error:"#FC5A5A",header:"#000000",icons:"#666666",input_background:"#FFFFFF",input_border:"#BFBCD7",input_filled_text:"#000000",input_labels_placeholders:"#88869F",links_focused_components:"#7D68F4",primary_button:"#7D68F4",primary_button_label:"#FFFFFF",secondary_button_border:"#BFBCD7",secondary_button_label:"#000000",success:"#36BF76",widget_background:"#FFFFFF",widget_border:"#BFBCD7"},displayName:"Default Theme",fonts:{body_text:{bold:!1,size:100},buttons_text:{bold:!0,size:100},font_url:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Regular.woff2",input_labels:{bold:!1,size:100},links:{bold:!0,size:100},links_style:"normal",reference_text_size:16,subtitle:{bold:!1,size:100},title:{bold:!0,size:150}},page_background:{background_color:"#F8F9FB",background_image_url:"",page_layout:"center"},widget:{logo_url:"",header_text_alignment:"center",logo_height:36,logo_position:"center",social_buttons_layout:"bottom"}};function Nw(e,t){const n=structuredClone(e);function r(i,s){for(const a in s)s[a]!==void 0&&typeof s[a]=="object"&&!Array.isArray(s[a])&&typeof i[a]=="object"&&i[a]!==null?r(i[a],s[a]):i[a]=s[a];return i}return r(n,t)}const WS=new o.OpenAPIHono().openapi(o.createRoute({tags:["branding"],method:"get",path:"/default",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:branding","auth:read"]}],responses:{200:{content:{"application/json":{schema:Sc}},description:"Default theme settings"}}}),async e=>{const t=await e.env.data.themes.get(e.var.tenant_id,"default");return t?e.json(t):e.json(uf)}).openapi(o.createRoute({tags:["branding"],method:"patch",path:"/default",request:{body:{content:{"application/json":{schema:Sc.deepPartial()}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:branding","auth:write"]}],responses:{200:{content:{"application/json":{schema:Sc}},description:"Updated theme settings"}}}),async e=>{const t=e.req.valid("json"),n=await e.env.data.themes.get(e.var.tenant_id,"default"),i=Nw(n||uf,t);return n?await e.env.data.themes.update(e.var.tenant_id,"default",i):await e.env.data.themes.create(e.var.tenant_id,i,"default"),e.json({...i,themeId:"default"})}),wm={colors:{primary:"#7D68F4",page_background:{type:"solid",start:"#F8F9FB",end:"#F8F9FB",angle_deg:0}},logo_url:"https://assets.sesamy.com/static/images/sesamy/logos/sesamy_logo_black.svg",favicon_url:"https://assets.sesamy.com/images/favicon.ico",font:{url:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Regular.woff2"}},km=o.z.object({body:o.z.string()}),JS=new o.OpenAPIHono().openapi(o.createRoute({tags:["branding"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:branding","auth:read"]}],responses:{200:{content:{"application/json":{schema:xc}},description:"Branding settings"}}}),async e=>{const t=await e.env.data.branding.get(e.var.tenant_id);return t?e.json(t):e.json(wm)}).openapi(o.createRoute({tags:["branding"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object(xc.shape).partial()}}}},security:[{Bearer:["update:branding","auth:write"]}],responses:{200:{content:{"application/json":{schema:xc}},description:"Branding settings"}}}),async e=>{const t=e.req.valid("json");await e.env.data.branding.set(e.var.tenant_id,t);const n=await e.env.data.branding.get(e.var.tenant_id);return e.json(n||wm)}).openapi(o.createRoute({tags:["branding"],method:"get",path:"/templates/universal-login",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:branding","auth:read"]}],responses:{200:{content:{"application/json":{schema:km}},description:"Universal login template"},404:{description:"Template not found"}}}),async e=>{const t=await e.env.data.universalLoginTemplates.get(e.var.tenant_id);if(!t)throw new I(404,{message:"Template not found"});return e.json(t)}).openapi(o.createRoute({tags:["branding"],method:"put",path:"/templates/universal-login",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:km}}}},security:[{Bearer:["update:branding","auth:write"]}],responses:{204:{description:"Template updated successfully"},400:{description:"Invalid template"}}}),async e=>{const t=e.req.valid("json");if(!t.body.includes("{%- auth0:head -%}"))throw new I(400,{message:"Template must contain {%- auth0:head -%} tag"});if(!t.body.includes("{%- auth0:widget -%}"))throw new I(400,{message:"Template must contain {%- auth0:widget -%} tag"});return await e.env.data.universalLoginTemplates.set(e.var.tenant_id,t),e.body(null,204)}).openapi(o.createRoute({tags:["branding"],method:"delete",path:"/templates/universal-login",request:{headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["delete:branding","auth:write"]}],responses:{204:{description:"Template deleted successfully"}}}),async e=>(await e.env.data.universalLoginTemplates.delete(e.var.tenant_id),e.body(null,204))).route("/themes",WS),ZS="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let XS=e=>crypto.getRandomValues(new Uint8Array(e)),YS=(e,t,n)=>{let r=(2<<Math.log2(e.length-1))-1,i=-~(1.6*r*t/e.length);return(s=t)=>{let a="";for(;;){let c=n(i),l=i|0;for(;l--;)if(a+=e[c[l]&r]||"",a.length>=s)return a}}},Tw=(e,t=21)=>YS(e,t|0,XS),Oe=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=ZS[n[e]&63];return t};const QS=24;function Ii(){return Tw("0123456789abcdef",QS)()}function df(e){if(!e.includes("|"))return console.error("Invalid user_id format"),e;const[,t]=e.split("|");return t}class W extends I{constructor(t,n){super(t,{message:JSON.stringify(n),res:new Response(JSON.stringify(n),{status:t,headers:{"Content-Type":"application/json"}})})}}function ez(e){return async(t,n)=>{const r=n.email?.toLowerCase();if(!n.linked_to&&r&&n.email_verified){const s=await Uo({userAdapter:e.users,tenant_id:t,email:r});s&&(n.linked_to=s.user_id)}if(n.linked_to&&!await e.users.get(t,n.linked_to))throw new W(400,{error:"invalid_request",error_description:"Primary user does not exist"});const i=await e.users.create(t,n);if(n.linked_to){const s=await e.users.get(t,n.linked_to);if(!s)throw new W(500,{error:"server_error",error_description:"Failed to fetch primary user after linking"});return s}return i}}var tz={deno:"Deno",bun:"Bun",workerd:"Cloudflare-Workers",node:"Node.js"},Pw=()=>{const e=globalThis;if(typeof navigator<"u"&&typeof navigator.userAgent=="string"){for(const[n,r]of Object.entries(tz))if(nz(r))return n}return typeof e?.EdgeRuntime=="string"?"edge-light":e?.fastly!==void 0?"fastly":e?.process?.release?.name==="node"?"node":"other"},nz=e=>navigator.userAgent.startsWith(e);function Ow(e,t){if(Pw()==="workerd")try{e.executionCtx.waitUntil(t)}catch{t.catch(n=>console.error("waitUntil promise error:",n))}}function rz(e){return[...e].reduce((t,[n,r])=>({...t,[n]:r}),{})}async function fe(e,t,n){const r={};if(e.req.raw?.headers){const s=rz(e.req.raw.headers);for(const[a,c]of Object.entries(s))r[a.toLowerCase()]=c}const i=async()=>{let s;if(e.env.data.geo)try{s=await e.env.data.geo.getGeoInfo(r)||void 0}catch(c){console.warn("Failed to get geo information:",c)}const a={type:n.type,description:n.description||"",ip:e.var.ip,user_agent:e.var.useragent||"",auth0_client:e.var.auth0_client,date:new Date().toISOString(),details:n.details||{request:{method:e.req.method,path:e.req.path,qs:e.req.queries(),body:n.body||e.var.body||""},...n.response&&{response:n.response}},isMobile:!1,client_id:e.var.client_id,client_name:"",user_id:n.userId||e.var.user_id||"",hostname:e.req.header("host")||"",user_name:e.var.username||"",connection_id:"",connection:n.connection||e.var.connection||"",strategy:n.strategy||"",strategy_type:n.strategy_type||"",audience:n.audience||"",scope:n.scope||"",location_info:s};await e.env.data.logs.create(t,a)};n.waitForCompletion?await i():Ow(e,i())}class ol{constructor(t,n){this.value=t,this.unit=n}value;unit;milliseconds(){return this.unit==="ms"?this.value:this.unit==="s"?this.value*1e3:this.unit==="m"?this.value*1e3*60:this.unit==="h"?this.value*1e3*60*60:this.unit==="d"?this.value*1e3*60*60*24:this.value*1e3*60*60*24*7}seconds(){return this.milliseconds()/1e3}transform(t){return new ol(Math.round(this.milliseconds()*t),"ms")}}class iz{hash;constructor(t){this.hash=t}async verify(t,n,r){const i=await crypto.subtle.importKey("spki",t,{name:"RSASSA-PKCS1-v1_5",hash:this.hash},!1,["verify"]);return await crypto.subtle.verify("RSASSA-PKCS1-v1_5",i,n,r)}async sign(t,n){const r=await crypto.subtle.importKey("pkcs8",t,{name:"RSASSA-PKCS1-v1_5",hash:this.hash},!1,["sign"]);return await crypto.subtle.sign("RSASSA-PKCS1-v1_5",r,n)}async generateKeyPair(t){const n=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",hash:this.hash,modulusLength:t??2048,publicExponent:new Uint8Array([1,0,1])},!0,["sign"]),r=await crypto.subtle.exportKey("pkcs8",n.privateKey),i=await crypto.subtle.exportKey("spki",n.publicKey);return{privateKey:r,publicKey:i}}}async function Rw(e){return await crypto.subtle.digest("SHA-256",e)}const $m="0123456789abcdef";function pf(e){const t=new Uint8Array(e);let n="";for(let r=0;r<t.length;r++){const i=t[r]>>4;n+=$m[i];const s=t[r]&15;n+=$m[s]}return n}class Lw{alphabet;padding;decodeMap=new Map;constructor(t,n){if(t.length!==32)throw new Error("Invalid alphabet");if(this.alphabet=t,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<t.length;r++)this.decodeMap.set(t[r],r)}encode(t,n){let r="",i=0,s=0;for(let c=0;c<t.length;c++)for(i=i<<8|t[c],s+=8;s>=5;)s-=5,r+=this.alphabet[i>>s&31];if(s>0&&(r+=this.alphabet[i<<5-s&31]),n?.includePadding??!0){const c=(8-r.length%8)%8;for(let l=0;l<c;l++)r+="="}return r}decode(t,n){const r=n?.strict??!0,i=Math.ceil(t.length/8),s=[];for(let a=0;a<i;a++){let c=0;const l=[];for(let d=0;d<8;d++){const f=t[a*8+d];if(f==="="){if(a+1!==i)throw new Error(`Invalid character: ${f}`);c+=1;continue}if(f===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const p=this.decodeMap.get(f)??null;if(p===null)throw new Error(`Invalid character: ${f}`);l.push(p)}if(c===8||c===7||c===5||c===2)throw new Error("Invalid padding");const u=(l[0]<<3)+(l[1]>>2);if(s.push(u),c<6){const d=((l[1]&3)<<6)+(l[2]<<1)+(l[3]>>4);s.push(d)}if(c<4){const d=((l[3]&255)<<4)+(l[4]>>1);s.push(d)}if(c<3){const d=((l[4]&1)<<7)+(l[5]<<2)+(l[6]>>3);s.push(d)}if(c<1){const d=((l[6]&7)<<5)+l[7];s.push(d)}}return Uint8Array.from(s)}}new Lw("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");new Lw("0123456789ABCDEFGHIJKLMNOPQRSTUV");class Dw{alphabet;padding;decodeMap=new Map;constructor(t,n){if(t.length!==64)throw new Error("Invalid alphabet");if(this.alphabet=t,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<t.length;r++)this.decodeMap.set(t[r],r)}encode(t,n){let r="",i=0,s=0;for(let c=0;c<t.length;c++)for(i=i<<8|t[c],s+=8;s>=6;)s+=-6,r+=this.alphabet[i>>s&63];if(s>0&&(r+=this.alphabet[i<<6-s&63]),n?.includePadding??!0){const c=(4-r.length%4)%4;for(let l=0;l<c;l++)r+="="}return r}decode(t,n){const r=n?.strict??!0,i=Math.ceil(t.length/4),s=[];for(let a=0;a<i;a++){let c=0,l=0;for(let u=0;u<4;u++){const d=t[a*4+u];if(d==="="){if(a+1!==i)throw new Error(`Invalid character: ${d}`);c+=1;continue}if(d===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const f=this.decodeMap.get(d)??null;if(f===null)throw new Error(`Invalid character: ${d}`);l+=f<<6*(3-u)}s.push(l>>16&255),c<2&&s.push(l>>8&255),c<1&&s.push(l&255)}return Uint8Array.from(s)}}const oz=new Dw("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),wr=new Dw("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");async function xm(e,t,n,r){const i={alg:e,typ:"JWT",...r?.headers},s={...n};r?.audiences!==void 0&&(s.aud=r.audiences),r?.subject!==void 0&&(s.sub=r.subject),r?.issuer!==void 0&&(s.iss=r.issuer),r?.jwtId!==void 0&&(s.jti=r.jwtId),r?.expiresIn!==void 0&&(s.exp=Math.floor(Date.now()/1e3)+r.expiresIn.seconds()),r?.notBefore!==void 0&&(s.nbf=Math.floor(r.notBefore.getTime()/1e3)),s.iat=Math.floor(Date.now()/1e3);const a=new TextEncoder,c=wr.encode(a.encode(JSON.stringify(i)),{includePadding:!1}),l=wr.encode(a.encode(JSON.stringify(s)),{includePadding:!1}),u=a.encode([c,l].join(".")),d=await az(e).sign(t,u),f=wr.encode(new Uint8Array(d),{includePadding:!1});return[c,l,f].join(".")}function sz(e){const t=e.split(".");return t.length!==3?null:t}function za(e){const t=sz(e);if(!t)return null;const n=new TextDecoder,r=wr.decode(t[0],{strict:!1}),i=wr.decode(t[1],{strict:!1}),s=JSON.parse(n.decode(r));if(typeof s!="object"||s===null||!("alg"in s)||!cz(s.alg)||"typ"in s&&s.typ!=="JWT")return null;const a=JSON.parse(n.decode(i));if(typeof a!="object"||a===null)return null;const c={algorithm:s.alg,expiresAt:null,subject:null,issuedAt:null,issuer:null,jwtId:null,audiences:null,notBefore:null};if("exp"in a){if(typeof a.exp!="number")return null;c.expiresAt=new Date(a.exp*1e3)}if("iss"in a){if(typeof a.iss!="string")return null;c.issuer=a.iss}if("sub"in a){if(typeof a.sub!="string")return null;c.subject=a.sub}if("aud"in a)if(Array.isArray(a.aud)){for(const l of a.aud)if(typeof l!="string")return null;c.audiences=a.aud}else{if(typeof a.aud!="string")return null;c.audiences=[a.aud]}if("nbf"in a){if(typeof a.nbf!="number")return null;c.notBefore=new Date(a.nbf*1e3)}if("iat"in a){if(typeof a.iat!="number")return null;c.issuedAt=new Date(a.iat*1e3)}if("jti"in a){if(typeof a.jti!="string")return null;c.jwtId=a.jti}return{value:e,header:{...s,typ:"JWT",alg:s.alg},payload:{...a},parts:t,...c}}function az(e){return new iz(lz[e])}function cz(e){return typeof e!="string"?!1:["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512","PS256","PS384","PS512"].includes(e)}const lz={RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512"};function Ac(e){const t=new Error(e);return t.source="ulid",t}const kh="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ls=kh.length,Sm=Math.pow(2,48)-1,uz=10,dz=16;function pz(e){let t=Math.floor(e()*Ls);return t===Ls&&(t=Ls-1),kh.charAt(t)}function fz(e,t){if(isNaN(e))throw new Error(e+" must be a number");if(e>Sm)throw Ac("cannot encode time greater than "+Sm);if(e<0)throw Ac("time must be positive");if(Number.isInteger(Number(e))===!1)throw Ac("time must be an integer");let n,r="";for(;t>0;t--)n=e%Ls,r=kh.charAt(n)+r,e=(e-n)/Ls;return r}function hz(e,t){let n="";for(;e>0;e--)n=pz(t)+n;return n}function _z(e=!1,t){t||(t=typeof window<"u"?window:null);const n=t&&(t.crypto||t.msCrypto);if(n)return()=>{const r=new Uint8Array(1);return n.getRandomValues(r),r[0]/255};try{const r=require("crypto");return()=>r.randomBytes(1).readUInt8()/255}catch{}if(e){try{console.error("secure crypto unusable, falling back to insecure Math.random()!")}catch{}return()=>Math.random()}throw Ac("secure crypto unusable, insecure Math.random not allowed")}function mz(e){return e||(e=_z()),function(n){return isNaN(n)&&(n=Date.now()),fz(n,uz)+hz(dz,e)}}const Uw=mz();function gz(){const e=new Uint8Array(32);return crypto.getRandomValues(e),wr.encode(e,{includePadding:!1})}function yz(e){try{const n=/-----BEGIN (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----([^-]*)-----END (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----/.exec(e);if(!n||!n[1])throw new Error("Invalid PEM format");return Uint8Array.from(atob(n[1].replace(/\s/g,"")),r=>r.charCodeAt(0)).buffer}finally{e=e.replace(/./g,"\0")}}async function bz(e,t){if(t==="plain")return e;const n=new TextEncoder().encode(e),r=await Rw(n);return wr.encode(new Uint8Array(r),{includePadding:!1})}const Pe="auth2",sc=300,pu=720*60*60,li=1440*60,vz="auth-token",Ds=1800*1e3,ff=10080*60*1e3,wz=300,kz=300,$z=1800*1e3,xz=1800*1e3,Sz=1440*60*1e3;var zm=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Bw(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function zz(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function r(){var i=!1;try{i=this instanceof r}catch{}return i?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}),n}var Yt={},Am;function Az(){if(Am)return Yt;Am=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.parseCookie=c,Yt.parse=c,Yt.stringifyCookie=l,Yt.stringifySetCookie=u,Yt.serialize=u,Yt.parseSetCookie=d,Yt.stringifySetCookie=u,Yt.serialize=u;const e=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,t=/^[\u0021-\u003A\u003C-\u007E]*$/,n=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,r=/^[\u0020-\u003A\u003D-\u007E]*$/,i=/^-?\d+$/,s=Object.prototype.toString,a=(()=>{const y=function(){};return y.prototype=Object.create(null),y})();function c(y,m){const v=new a,k=y.length;if(k<2)return v;const x=m?.decode||_;let b=0;do{const S=p(y,b,k);if(S===-1)break;const A=f(y,b,k);if(S>A){b=y.lastIndexOf(";",S-1)+1;continue}const C=h(y,b,S);v[C]===void 0&&(v[C]=x(h(y,S+1,A))),b=A+1}while(b<k);return v}function l(y,m){const v=m?.encode||encodeURIComponent,k=[];for(const x of Object.keys(y)){const b=y[x];if(b===void 0)continue;if(!e.test(x))throw new TypeError(`cookie name is invalid: ${x}`);const S=v(b);if(!t.test(S))throw new TypeError(`cookie val is invalid: ${b}`);k.push(`${x}=${S}`)}return k.join("; ")}function u(y,m,v){const k=typeof y=="object"?y:{...v,name:y,value:String(m)},b=(typeof m=="object"?m:v)?.encode||encodeURIComponent;if(!e.test(k.name))throw new TypeError(`argument name is invalid: ${k.name}`);const S=k.value?b(k.value):"";if(!t.test(S))throw new TypeError(`argument val is invalid: ${k.value}`);let A=k.name+"="+S;if(k.maxAge!==void 0){if(!Number.isInteger(k.maxAge))throw new TypeError(`option maxAge is invalid: ${k.maxAge}`);A+="; Max-Age="+k.maxAge}if(k.domain){if(!n.test(k.domain))throw new TypeError(`option domain is invalid: ${k.domain}`);A+="; Domain="+k.domain}if(k.path){if(!r.test(k.path))throw new TypeError(`option path is invalid: ${k.path}`);A+="; Path="+k.path}if(k.expires){if(!g(k.expires)||!Number.isFinite(k.expires.valueOf()))throw new TypeError(`option expires is invalid: ${k.expires}`);A+="; Expires="+k.expires.toUTCString()}if(k.httpOnly&&(A+="; HttpOnly"),k.secure&&(A+="; Secure"),k.partitioned&&(A+="; Partitioned"),k.priority)switch(typeof k.priority=="string"?k.priority.toLowerCase():void 0){case"low":A+="; Priority=Low";break;case"medium":A+="; Priority=Medium";break;case"high":A+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${k.priority}`)}if(k.sameSite)switch(typeof k.sameSite=="string"?k.sameSite.toLowerCase():k.sameSite){case!0:case"strict":A+="; SameSite=Strict";break;case"lax":A+="; SameSite=Lax";break;case"none":A+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${k.sameSite}`)}return A}function d(y,m){const v=m?.decode||_,k=y.length,x=f(y,0,k),b=p(y,0,x),S=b===-1?{name:"",value:v(h(y,0,x))}:{name:h(y,0,b),value:v(h(y,b+1,x))};let A=x+1;for(;A<k;){const C=f(y,A,k),P=p(y,A,C),R=P===-1?h(y,A,C):h(y,A,P),E=P===-1?void 0:h(y,P+1,C);switch(R.toLowerCase()){case"httponly":S.httpOnly=!0;break;case"secure":S.secure=!0;break;case"partitioned":S.partitioned=!0;break;case"domain":S.domain=E;break;case"path":S.path=E;break;case"max-age":E&&i.test(E)&&(S.maxAge=Number(E));break;case"expires":if(!E)break;const L=new Date(E);Number.isFinite(L.valueOf())&&(S.expires=L);break;case"priority":if(!E)break;const M=E.toLowerCase();(M==="low"||M==="medium"||M==="high")&&(S.priority=M);break;case"samesite":if(!E)break;const H=E.toLowerCase();(H==="lax"||H==="strict"||H==="none")&&(S.sameSite=H);break}A=C+1}return S}function f(y,m,v){const k=y.indexOf(";",m);return k===-1?v:k}function p(y,m,v){const k=y.indexOf("=",m);return k<v?k:-1}function h(y,m,v){let k=m,x=v;do{const b=y.charCodeAt(k);if(b!==32&&b!==9)break}while(++k<x);for(;x>k;){const b=y.charCodeAt(x-1);if(b!==32&&b!==9)break;x--}return y.slice(k,x)}function _(y){if(y.indexOf("%")===-1)return y;try{return decodeURIComponent(y)}catch{return y}}function g(y){return s.call(y)==="[object Date]"}return Yt}var Xs=Az();function fu(e){return`${e}-${vz}`}function Mw(e){if(!e)return;const[t]=e.split(":");if(!t||t==="localhost"||/^(\d{1,3}\.){3}\d{1,3}$/.test(t))return;const n=t.split(".");return n.length>2?`.${n.slice(-2).join(".")}`:`.${t}`}function Ez(e,t){if(!t)return[];const n=fu(e),r=[],i=t.split(";");for(const s of i){const[a,...c]=s.trim().split("=");a===n&&c.length>0&&r.push(c.join("="))}return r}function ui(e,t){return t?Xs.parse(t)[fu(e)]:void 0}function qw(e,t){const n=fu(e),r={path:"/",httpOnly:!0,secure:!0,maxAge:0,sameSite:"none",domain:t?Mw(t):void 0};return[Xs.serialize(n,"",r),Xs.serialize(n,"",{...r,partitioned:!0})]}function sl(e,t,n){const r=fu(e),i={path:"/",httpOnly:!0,secure:!0,sameSite:"none",domain:n?Mw(n):void 0};return[Xs.serialize(r,"",{...i,maxAge:0}),Xs.serialize(r,t,{...i,maxAge:pu,partitioned:!0})]}var Cz=Object.defineProperty,Iz=(e,t,n)=>t in e?Cz(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ao=(e,t,n)=>Iz(e,typeof t!="symbol"?t+"":t,n);const dt=o.z.object({"#text":o.z.string()}),jz=o.z.object({"#text":o.z.string(),"@_xmlns:saml":o.z.string().optional()});o.z.object({"samlp:AuthnRequest":o.z.object({"saml:Issuer":jz,"@_xmlns:samlp":o.z.string(),"@_xmlns:saml":o.z.string().optional(),"@_ForceAuthn":o.z.string().transform(e=>e.toLowerCase()==="true").optional(),"@_ID":o.z.string(),"@_IssueInstant":o.z.string().datetime(),"@_Destination":o.z.string().url(),"@_AssertionConsumerServiceURL":o.z.string().url().optional(),"@_ProtocolBinding":o.z.string().optional(),"@_Version":o.z.string()})});o.z.array(o.z.object({":@":o.z.object({"@_xmlns":o.z.string(),"@_entityID":o.z.string()}),EntityDescriptor:o.z.array(o.z.object({":@":o.z.object({"@_protocolSupportEnumeration":o.z.string()}),IDPSSODescriptor:o.z.array(o.z.union([o.z.object({KeyDescriptor:o.z.array(o.z.object({KeyInfo:o.z.array(o.z.object({X509Data:o.z.array(o.z.object({X509Certificate:o.z.array(dt)}))})),":@":o.z.object({"@_xmlns":o.z.string()})})),":@":o.z.object({"@_use":o.z.string()})}),o.z.object({SingleLogoutService:o.z.array(o.z.object({})),":@":o.z.object({"@_Binding":o.z.string(),"@_Location":o.z.string()})}),o.z.object({NameIDFormat:o.z.array(dt)}),o.z.object({SingleSignOnService:o.z.array(o.z.object({})),":@":o.z.object({"@_Binding":o.z.string(),"@_Location":o.z.string()})}),o.z.object({Attribute:o.z.array(o.z.object({})),":@":o.z.object({"@_Name":o.z.string(),"@_NameFormat":o.z.string(),"@_FriendlyName":o.z.string(),"@_xmlns":o.z.string()})})]))}))}));const Nz=o.z.object({"saml:Attribute":o.z.array(o.z.object({"saml:AttributeValue":o.z.array(o.z.object({"#text":o.z.string()})),":@":o.z.object({"@_xmlns:xs":o.z.string().optional(),"@_xmlns:xsi":o.z.string(),"@_xsi:type":o.z.string()}).optional()})),":@":o.z.object({"@_Name":o.z.string(),"@_NameFormat":o.z.string(),"@_FriendlyName":o.z.string().optional()})}),Tz=o.z.object({"ds:Transform":o.z.array(o.z.any()),":@":o.z.object({"@_Algorithm":o.z.string()})}),Em=o.z.object({"ds:Signature":o.z.array(o.z.union([o.z.object({"ds:SignedInfo":o.z.array(o.z.union([o.z.object({"ds:CanonicalizationMethod":o.z.array(o.z.object({":@":o.z.object({"@_Algorithm":o.z.string()})}))}),o.z.object({"ds:SignatureMethod":o.z.array(o.z.object({":@":o.z.object({"@_Algorithm":o.z.string()})}))}),o.z.object({"ds:Reference":o.z.array(o.z.union([o.z.object({"ds:Transforms":o.z.array(Tz)}),o.z.object({"ds:DigestMethod":o.z.array(o.z.object({":@":o.z.object({"@_Algorithm":o.z.string()})}))}),o.z.object({"ds:DigestValue":o.z.array(dt)})])),":@":o.z.object({"@_URI":o.z.string().optional()}).optional()})]))}),o.z.object({"ds:SignatureValue":o.z.array(dt)}),o.z.object({"ds:KeyInfo":o.z.array(o.z.union([o.z.object({"ds:KeyValue":o.z.array(o.z.object({"ds:RSAKeyValue":o.z.array(o.z.union([o.z.object({"ds:Modulus":o.z.array(dt)}),o.z.object({"ds:Exponent":o.z.array(dt)})]))}))}),o.z.object({"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(dt)}))}),o.z.object({"ds:KeyValue":o.z.array(o.z.object({"ds:RSAKeyValue":o.z.array(o.z.union([o.z.object({"ds:Modulus":o.z.array(dt)}),o.z.object({"ds:Exponent":o.z.array(dt)})]))})),"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(dt)}))})]))})])),":@":o.z.object({"@_xmlns:ds":o.z.string().optional()}).optional()});o.z.array(o.z.object({"samlp:Response":o.z.array(o.z.union([o.z.object({"saml:Issuer":o.z.array(dt)}),Em,o.z.object({"samlp:Status":o.z.array(o.z.object({"samlp:StatusCode":o.z.array(dt),":@":o.z.object({"@_Value":o.z.string()})}))}),o.z.object({"saml:Assertion":o.z.array(o.z.union([o.z.object({"saml:Issuer":o.z.array(dt)}),Em,o.z.object({"saml:Subject":o.z.array(o.z.union([o.z.object({"saml:NameID":o.z.array(dt),":@":o.z.object({"@_Format":o.z.string()})}),o.z.object({"saml:SubjectConfirmation":o.z.array(o.z.object({"saml:SubjectConfirmationData":o.z.array(o.z.any()),":@":o.z.object({"@_InResponseTo":o.z.string(),"@_NotOnOrAfter":o.z.string(),"@_Recipient":o.z.string()})})),":@":o.z.object({"@_Method":o.z.string()})})]))}),o.z.object({"saml:Conditions":o.z.array(o.z.object({"saml:AudienceRestriction":o.z.array(o.z.object({"saml:Audience":o.z.array(dt)}))})),":@":o.z.object({"@_NotBefore":o.z.string(),"@_NotOnOrAfter":o.z.string()})}),o.z.object({"saml:AuthnStatement":o.z.array(o.z.object({"saml:AuthnContext":o.z.array(o.z.object({"saml:AuthnContextClassRef":o.z.array(dt)}))})),":@":o.z.object({"@_AuthnInstant":o.z.string(),"@_SessionIndex":o.z.string(),"@_SessionNotOnOrAfter":o.z.string()})}),o.z.object({"saml:AttributeStatement":o.z.array(Nz)})])),":@":o.z.object({"@_xmlns":o.z.string(),"@_ID":o.z.string(),"@_IssueInstant":o.z.string(),"@_Version":o.z.string()})})])),":@":o.z.object({"@_xmlns:samlp":o.z.string(),"@_xmlns:saml":o.z.string(),"@_Destination":o.z.string(),"@_ID":o.z.string(),"@_InResponseTo":o.z.string(),"@_IssueInstant":o.z.string(),"@_Version":o.z.string()})}));var Pz={};(function(e){const t=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",n=t+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+t+"]["+n+"]*",i=new RegExp("^"+r+"$"),s=function(c,l){const u=[];let d=l.exec(c);for(;d;){const f=[];f.startIndex=l.lastIndex-d[0].length;const p=d.length;for(let h=0;h<p;h++)f.push(d[h]);u.push(f),d=l.exec(c)}return u},a=function(c){const l=i.exec(c);return!(l===null||typeof l>"u")};e.isExist=function(c){return typeof c<"u"},e.isEmptyObject=function(c){return Object.keys(c).length===0},e.merge=function(c,l,u){if(l){const d=Object.keys(l),f=d.length;for(let p=0;p<f;p++)u==="strict"?c[d[p]]=[l[d[p]]]:c[d[p]]=l[d[p]]}},e.getValue=function(c){return e.isExist(c)?c:""},e.isName=a,e.getAllMatches=s,e.nameRegexp=r})(Pz);function Oz(e){return typeof e=="function"?e:Array.isArray(e)?t=>{for(const n of e)if(typeof n=="string"&&t===n||n instanceof RegExp&&n.test(t))return!0}:()=>!1}var Rz=Oz;const Lz=`
|
|
2
2
|
`;function Dz(e,t){let n="";return t.format&&t.indentBy.length>0&&(n=Lz),Fw(e,t,"",n)}function Fw(e,t,n,r){let i="",s=!1;if(!Array.isArray(e)){if(e!=null){let a=e.toString();return a=hf(a,t),a}return""}for(let a=0;a<e.length;a++){const c=e[a],l=Uz(c);if(l===void 0)continue;let u="";if(n.length===0?u=l:u=`${n}.${l}`,l===t.textNodeName){let _=c[l];Bz(u,t)||(_=t.tagValueProcessor(l,_),_=hf(_,t)),s&&(i+=r),i+=_,s=!1;continue}else if(l===t.cdataPropName){s&&(i+=r),i+=`<![CDATA[${c[l][0][t.textNodeName]}]]>`,s=!1;continue}else if(l===t.commentPropName){i+=r+`<!--${c[l][0][t.textNodeName]}-->`,s=!0;continue}else if(l[0]==="?"){const _=Cm(c[":@"],t),g=l==="?xml"?"":r;let y=c[l][0][t.textNodeName];y=y.length!==0?" "+y:"",i+=g+`<${l}${y}${_}?>`,s=!0;continue}let d=r;d!==""&&(d+=t.indentBy);const f=Cm(c[":@"],t),p=r+`<${l}${f}`,h=Fw(c[l],t,u,d);t.unpairedTags.indexOf(l)!==-1?t.suppressUnpairedNode?i+=p+">":i+=p+"/>":(!h||h.length===0)&&t.suppressEmptyNode?i+=p+"/>":h&&h.endsWith(">")?i+=p+`>${h}${r}</${l}>`:(i+=p+">",h&&r!==""&&(h.includes("/>")||h.includes("</"))?i+=r+t.indentBy+h+r:i+=h,i+=`</${l}>`),s=!0}return i}function Uz(e){const t=Object.keys(e);for(let n=0;n<t.length;n++){const r=t[n];if(Object.prototype.hasOwnProperty.call(e,r)&&r!==":@")return r}}function Cm(e,t){let n="";if(e&&!t.ignoreAttributes)for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let i=t.attributeValueProcessor(r,e[r]);i=hf(i,t),i===!0&&t.suppressBooleanAttributes?n+=` ${r.substr(t.attributeNamePrefix.length)}`:n+=` ${r.substr(t.attributeNamePrefix.length)}="${i}"`}return n}function Bz(e,t){e=e.substr(0,e.length-t.textNodeName.length-1);let n=e.substr(e.lastIndexOf(".")+1);for(let r in t.stopNodes)if(t.stopNodes[r]===e||t.stopNodes[r]==="*."+n)return!0;return!1}function hf(e,t){if(e&&e.length>0&&t.processEntities)for(let n=0;n<t.entities.length;n++){const r=t.entities[n];e=e.replace(r.regex,r.val)}return e}var Mz=Dz;const qz=Mz,Fz=Rz,Hz={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function Tr(e){this.options=Object.assign({},Hz,e),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=Fz(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Gz),this.processTextOrObjNode=Vz,this.options.format?(this.indentate=Kz,this.tagEndChar=`>
|
|
3
3
|
`,this.newLine=`
|
|
4
4
|
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}Tr.prototype.build=function(e){return this.options.preserveOrder?qz(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)};Tr.prototype.j2x=function(e,t,n){let r="",i="";const s=n.join(".");for(let a in e)if(Object.prototype.hasOwnProperty.call(e,a))if(typeof e[a]>"u")this.isAttribute(a)&&(i+="");else if(e[a]===null)this.isAttribute(a)||a===this.options.cdataPropName?i+="":a[0]==="?"?i+=this.indentate(t)+"<"+a+"?"+this.tagEndChar:i+=this.indentate(t)+"<"+a+"/"+this.tagEndChar;else if(e[a]instanceof Date)i+=this.buildTextValNode(e[a],a,"",t);else if(typeof e[a]!="object"){const c=this.isAttribute(a);if(c&&!this.ignoreAttributesFn(c,s))r+=this.buildAttrPairStr(c,""+e[a]);else if(!c)if(a===this.options.textNodeName){let l=this.options.tagValueProcessor(a,""+e[a]);i+=this.replaceEntitiesValue(l)}else i+=this.buildTextValNode(e[a],a,"",t)}else if(Array.isArray(e[a])){const c=e[a].length;let l="",u="";for(let d=0;d<c;d++){const f=e[a][d];if(!(typeof f>"u"))if(f===null)a[0]==="?"?i+=this.indentate(t)+"<"+a+"?"+this.tagEndChar:i+=this.indentate(t)+"<"+a+"/"+this.tagEndChar;else if(typeof f=="object")if(this.options.oneListGroup){const p=this.j2x(f,t+1,n.concat(a));l+=p.val,this.options.attributesGroupName&&f.hasOwnProperty(this.options.attributesGroupName)&&(u+=p.attrStr)}else l+=this.processTextOrObjNode(f,a,t,n);else if(this.options.oneListGroup){let p=this.options.tagValueProcessor(a,f);p=this.replaceEntitiesValue(p),l+=p}else l+=this.buildTextValNode(f,a,"",t)}this.options.oneListGroup&&(l=this.buildObjectNode(l,a,u,t)),i+=l}else if(this.options.attributesGroupName&&a===this.options.attributesGroupName){const c=Object.keys(e[a]),l=c.length;for(let u=0;u<l;u++)r+=this.buildAttrPairStr(c[u],""+e[a][c[u]])}else i+=this.processTextOrObjNode(e[a],a,t,n);return{attrStr:r,val:i}};Tr.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,""+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t==="true"?" "+e:" "+e+'="'+t+'"'};function Vz(e,t,n,r){const i=this.j2x(e,n+1,r.concat(t));return e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,i.attrStr,n):this.buildObjectNode(i.val,t,i.attrStr,n)}Tr.prototype.buildObjectNode=function(e,t,n,r){if(e==="")return t[0]==="?"?this.indentate(r)+"<"+t+n+"?"+this.tagEndChar:this.indentate(r)+"<"+t+n+this.closeTag(t)+this.tagEndChar;{let i="</"+t+this.tagEndChar,s="";return t[0]==="?"&&(s="?",i=""),(n||n==="")&&e.indexOf("<")===-1?this.indentate(r)+"<"+t+n+s+">"+e+i:this.options.commentPropName!==!1&&t===this.options.commentPropName&&s.length===0?this.indentate(r)+`<!--${e}-->`+this.newLine:this.indentate(r)+"<"+t+n+s+this.tagEndChar+e+this.indentate(r)+i}};Tr.prototype.closeTag=function(e){let t="";return this.options.unpairedTags.indexOf(e)!==-1?this.options.suppressUnpairedNode||(t="/"):this.options.suppressEmptyNode?t="/":t=`></${e}`,t};Tr.prototype.buildTextValNode=function(e,t,n,r){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(r)+`<![CDATA[${e}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(r)+`<!--${e}-->`+this.newLine;if(t[0]==="?")return this.indentate(r)+"<"+t+n+"?"+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),i===""?this.indentate(r)+"<"+t+n+this.closeTag(t)+this.tagEndChar:this.indentate(r)+"<"+t+n+">"+i+"</"+t+this.tagEndChar}};Tr.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){const n=this.options.entities[t];e=e.replace(n.regex,n.val)}return e};function Kz(e){return this.options.indentBy.repeat(e)}function Gz(e){return e.startsWith(this.options.attributeNamePrefix)&&e!==this.options.textNodeName?e.substr(this.attrPrefixLen):!1}var Wz=Tr;const Jz=Wz;var Zz={XMLBuilder:Jz};let Hw=class{constructor(t,n){if(ao(this,"alphabet"),ao(this,"padding"),ao(this,"decodeMap",new Map),t.length!==32)throw new Error("Invalid alphabet");if(this.alphabet=t,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<t.length;r++)this.decodeMap.set(t[r],r)}encode(t,n){let r="",i=0,s=0;for(let a=0;a<t.length;a++)for(i=i<<8|t[a],s+=8;s>=5;)s-=5,r+=this.alphabet[i>>s&31];if(s>0&&(r+=this.alphabet[i<<5-s&31]),n?.includePadding??!0){const a=(8-r.length%8)%8;for(let c=0;c<a;c++)r+="="}return r}decode(t,n){const r=n?.strict??!0,i=Math.ceil(t.length/8),s=[];for(let a=0;a<i;a++){let c=0;const l=[];for(let d=0;d<8;d++){const f=t[a*8+d];if(f==="="){if(a+1!==i)throw new Error(`Invalid character: ${f}`);c+=1;continue}if(f===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const p=this.decodeMap.get(f)??null;if(p===null)throw new Error(`Invalid character: ${f}`);l.push(p)}if(c===8||c===7||c===5||c===2)throw new Error("Invalid padding");const u=(l[0]<<3)+(l[1]>>2);if(s.push(u),c<6){const d=((l[1]&3)<<6)+(l[2]<<1)+(l[3]>>4);s.push(d)}if(c<4){const d=((l[3]&255)<<4)+(l[4]>>1);s.push(d)}if(c<3){const d=((l[4]&1)<<7)+(l[5]<<2)+(l[6]>>3);s.push(d)}if(c<1){const d=((l[6]&7)<<5)+l[7];s.push(d)}}return Uint8Array.from(s)}};new Hw("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");new Hw("0123456789ABCDEFGHIJKLMNOPQRSTUV");let Vw=class{constructor(t,n){if(ao(this,"alphabet"),ao(this,"padding"),ao(this,"decodeMap",new Map),t.length!==64)throw new Error("Invalid alphabet");if(this.alphabet=t,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<t.length;r++)this.decodeMap.set(t[r],r)}encode(t,n){let r="",i=0,s=0;for(let a=0;a<t.length;a++)for(i=i<<8|t[a],s+=8;s>=6;)s+=-6,r+=this.alphabet[i>>s&63];if(s>0&&(r+=this.alphabet[i<<6-s&63]),n?.includePadding??!0){const a=(4-r.length%4)%4;for(let c=0;c<a;c++)r+="="}return r}decode(t,n){const r=n?.strict??!0,i=Math.ceil(t.length/4),s=[];for(let a=0;a<i;a++){let c=0,l=0;for(let u=0;u<4;u++){const d=t[a*4+u];if(d==="="){if(a+1!==i)throw new Error(`Invalid character: ${d}`);c+=1;continue}if(d===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const f=this.decodeMap.get(d)??null;if(f===null)throw new Error(`Invalid character: ${d}`);l+=f<<6*(3-u)}s.push(l>>16&255),c<2&&s.push(l>>8&255),c<1&&s.push(l&255)}return Uint8Array.from(s)}};new Vw("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");new Vw("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");const Xz="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let Im=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=Xz[n[e]&63];return t};async function Yz(e,t){const n=e.notBefore||new Date().toISOString(),r=e.notAfter||new Date(new Date(n).getTime()+600*1e3).toISOString(),i=e.issueInstant||n,s=e.sessionNotOnOrAfter||r,a=e.responseId||`_${Im()}`,c=e.assertionId||`_${Im()}`,l=[{"samlp:Response":[{"saml:Issuer":[{"#text":e.issuer}]},{"samlp:Status":[{"samlp:StatusCode":[],":@":{"@_Value":"urn:oasis:names:tc:SAML:2.0:status:Success"}}]},{"saml:Assertion":[{"saml:Issuer":[{"#text":e.issuer}]},{"saml:Subject":[{"saml:NameID":[{"#text":e.email}],":@":{"@_Format":"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"}},{"saml:SubjectConfirmation":[{"saml:SubjectConfirmationData":[],":@":{"@_InResponseTo":e.inResponseTo,"@_NotOnOrAfter":r,"@_Recipient":e.destination}}],":@":{"@_Method":"urn:oasis:names:tc:SAML:2.0:cm:bearer"}}]},{"saml:Conditions":[{"saml:AudienceRestriction":[{"saml:Audience":[{"#text":e.audience}]}]}],":@":{"@_NotBefore":n,"@_NotOnOrAfter":r}},{"saml:AuthnStatement":[{"saml:AuthnContext":[{"saml:AuthnContextClassRef":[{"#text":"urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified"}]}]}],":@":{"@_AuthnInstant":i,"@_SessionIndex":e.sessionIndex,"@_SessionNotOnOrAfter":s}},{"saml:AttributeStatement":[{"saml:Attribute":[{"saml:AttributeValue":[{"#text":e.userId}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_FriendlyName":"persistent","@_Name":"id","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":e.email}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"email","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"manage-account"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"default-roles-master"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"offline_access"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"view-profile"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"uma_authorization"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"manage-account-links"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}}]}],":@":{"@_xmlns":"urn:oasis:names:tc:SAML:2.0:assertion","@_ID":c,"@_IssueInstant":i,"@_Version":"2.0"}}],":@":{"@_xmlns:samlp":"urn:oasis:names:tc:SAML:2.0:protocol","@_xmlns:saml":"urn:oasis:names:tc:SAML:2.0:assertion","@_Destination":e.destination,"@_ID":a,"@_InResponseTo":e.inResponseTo,"@_IssueInstant":i,"@_Version":"2.0"}}];let u=new Zz.XMLBuilder({ignoreAttributes:!1,suppressEmptyNode:!0,preserveOrder:!0}).build(l);return e.signature&&t&&(u=await t.signSAML(u,e.signature.privateKeyPem,e.signature.cert)),e.encode===!1?u:btoa(u)}let Kw=class{constructor(t){this.signUrl=t}async signSAML(t,n,r){const i=await fetch(this.signUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({xmlContent:t,privateKey:n,publicCert:r})});if(!i.ok)throw new Error(`Failed to sign SAML via HTTP: ${i.status} ${i.statusText}`);return await i.text()}};function Qz(e,t,n){const r=n?`<input type="hidden" name="RelayState" value="${n}" />`:"",i=`
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
|
|
65
65
|
</html>`;return e.html(s,{headers:i})}const cl=["openid","profile","email","address","phone"];async function l9(e,t,n,r){const i=[];if(!(await e.env.data.tenants.get(t))?.flags?.inherit_global_permissions_in_organizations)return[];const a=await e.env.data.userRoles.list(t,n,void 0,"");for(const c of a)(await e.env.data.rolePermissions.list(t,c.id,{per_page:1e3})).forEach(u=>{u.resource_server_identifier===r&&i.push(u.permission_name)});return[...new Set(i)]}async function u9(e,t){const{tenantId:n,clientId:r,audience:i,requestedScopes:s}=t,a=s.filter(b=>cl.includes(b)),c=s.filter(b=>!cl.includes(b)),u=(await e.env.data.resourceServers.list(n)).resource_servers.filter(b=>b.identifier===i);if(u.length===0)return{scopes:a,permissions:[]};const d=u[0];if(!d)return{scopes:a,permissions:[]};const f=d.options?.enforce_policies===!0,p=d.options?.token_dialect||"access_token",_=(await e.env.data.clientGrants.list(n,{q:`client_id:"${r}"`})).client_grants.find(b=>b.audience===i);if(!_)return{scopes:a,permissions:[]};const g=_.scope||[],y=(d.scopes||[]).map(b=>b.value);if(c.length>0){const b=c.filter(S=>!g.includes(S));if(b.length>0)throw new W(403,{error:"access_denied",error_description:`Client is not authorized for scope(s): ${b.join(", ")}`})}const m=g.filter(b=>y.includes(b)),v=c.length===0?m:c.filter(b=>m.includes(b));if(!f)return{scopes:[...new Set([...a,...v])],permissions:[]};const k=v;return p==="access_token_authz"?{scopes:[...new Set([...a,...v])],permissions:k}:{scopes:[...new Set([...a,...v])],permissions:[]}}async function Ys(e,t){if(t.grantType===an.ClientCredential)return await u9(e,{tenantId:t.tenantId,clientId:t.clientId,audience:t.audience,requestedScopes:t.requestedScopes});const{tenantId:n,userId:r,audience:i,requestedScopes:s,organizationId:a}=t;let c=!1;if(a){if((await e.env.data.tenants.get(n))?.flags?.inherit_global_permissions_in_organizations){const L=await e.env.data.userRoles.list(n,r,void 0,"");for(const M of L)if((await e.env.data.rolePermissions.list(n,M.id,{per_page:1e3})).some(Q=>Q.permission_name==="admin:organizations"&&Q.resource_server_identifier===i)){c=!0;break}}if(!c&&!(await e.env.data.userOrganizations.list(n,{q:`user_id:${r}`,per_page:1e3})).userOrganizations.some(H=>H.organization_id===a))throw new W(403,{error:"access_denied",error_description:"User is not a member of the specified organization"})}const l=s.filter(E=>cl.includes(E)),d=(await e.env.data.resourceServers.list(n)).resource_servers.filter(E=>E.identifier===i);if(d.length===0)return{scopes:s,permissions:[]};const f=d[0];if(!f)return{scopes:s,permissions:[]};const p=(f.scopes||[]).map(E=>E.value),h=f.options?.enforce_policies===!0,_=f.options?.token_dialect||"access_token";if(!h)return{scopes:s,permissions:[]};const g=await e.env.data.userPermissions.list(n,r,void 0,a),y=await e.env.data.userRoles.list(n,r,void 0,""),m=a?await e.env.data.userRoles.list(n,r,void 0,a):[],v=[...y,...m],k=a?await l9(e,n,r,i):[],x=[];for(const E of v)(await e.env.data.rolePermissions.list(n,E.id,{per_page:1e3})).forEach(M=>{M.resource_server_identifier===i&&x.push(M.permission_name)});const b=new Set;g.forEach(E=>{E.resource_server_identifier===i&&b.add(E.permission_name)}),x.forEach(E=>{b.add(E)}),k.forEach(E=>{b.add(E)});const S=Array.from(b),A=S.filter(E=>p.includes(E)),C=s.filter(E=>!p.includes(E)&&!cl.includes(E));if(_==="access_token_authz")return{scopes:[...new Set([...l,...C])],permissions:A};const P=s.filter(E=>p.includes(E)&&S.includes(E));return{scopes:[...new Set([...l,...P,...C])],permissions:[]}}function d9(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function p9(){const e=d9();if(e.__xstate__)return e.__xstate__}const f9=e=>{if(typeof window>"u")return;const t=p9();t&&t.register(e)};class Nm{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const n={value:t,next:null};if(this._current){this._last.next=n,this._last=n;return}this._current=n,this._last=n,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const Jw=".",h9="",Zw="",_9="#",m9="*",Xw="xstate.init",g9="xstate.error",mf="xstate.stop";function y9(e,t){return{type:`xstate.after.${e}.${t}`}}function gf(e,t){return{type:`xstate.done.state.${e}`,output:t}}function b9(e,t){return{type:`xstate.done.actor.${e}`,output:t,actorId:e}}function Yw(e,t){return{type:`xstate.error.actor.${e}`,error:t,actorId:e}}function Qw(e){return{type:Xw,input:e}}function bn(e){setTimeout(()=>{throw e})}const v9=typeof Symbol=="function"&&Symbol.observable||"@@observable";function e2(e,t){const n=Tm(e),r=Tm(t);return typeof r=="string"?typeof n=="string"?r===n:!1:typeof n=="string"?n in r:Object.keys(n).every(i=>i in r?e2(n[i],r[i]):!1)}function $h(e){if(n2(e))return e;const t=[];let n="";for(let r=0;r<e.length;r++){switch(e.charCodeAt(r)){case 92:n+=e[r+1],r++;continue;case 46:t.push(n),n="";continue}n+=e[r]}return t.push(n),t}function Tm(e){if(tA(e))return e.value;if(typeof e!="string")return e;const t=$h(e);return w9(t)}function w9(e){if(e.length===1)return e[0];const t={};let n=t;for(let r=0;r<e.length-1;r++)if(r===e.length-2)n[e[r]]=e[r+1];else{const i=n;n={},i[e[r]]=n}return t}function Pm(e,t){const n={},r=Object.keys(e);for(let i=0;i<r.length;i++){const s=r[i];n[s]=t(e[s],s,e,i)}return n}function t2(e){return n2(e)?e:[e]}function gr(e){return e===void 0?[]:t2(e)}function yf(e,t,n,r){return typeof e=="function"?e({context:t,event:n,self:r}):e}function n2(e){return Array.isArray(e)}function k9(e){return e.type.startsWith("xstate.error.actor")}function Vi(e){return t2(e).map(t=>typeof t>"u"||typeof t=="string"?{target:t}:t)}function r2(e){if(!(e===void 0||e===h9))return gr(e)}function bf(e,t,n){const r=typeof e=="object",i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}function Om(e,t){return`${t}.${e}`}function xh(e,t){const n=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return e.implementations.actors[t];const[,r,i]=n,a=e.getStateNodeById(i).config.invoke;return(Array.isArray(a)?a[r]:a).src}function $9(e,t){if(t===e||t===m9)return!0;if(!t.endsWith(".*"))return!1;const n=t.split("."),r=e.split(".");for(let i=0;i<n.length;i++){const s=n[i],a=r[i];if(s==="*")return i===n.length-1;if(s!==a)return!1}return!0}function Rm(e,t){return`${e.sessionId}.${t}`}let x9=0;function S9(e,t){const n=new Map,r=new Map,i=new WeakMap,s=new Set,a={},{clock:c,logger:l}=t,u={schedule:(p,h,_,g,y=Math.random().toString(36).slice(2))=>{const m={source:p,target:h,event:_,delay:g,id:y,startedAt:Date.now()},v=Rm(p,y);f._snapshot._scheduledEvents[v]=m;const k=c.setTimeout(()=>{delete a[v],delete f._snapshot._scheduledEvents[v],f._relay(p,h,_)},g);a[v]=k},cancel:(p,h)=>{const _=Rm(p,h),g=a[_];delete a[_],delete f._snapshot._scheduledEvents[_],g!==void 0&&c.clearTimeout(g)},cancelAll:p=>{for(const h in f._snapshot._scheduledEvents){const _=f._snapshot._scheduledEvents[h];_.source===p&&u.cancel(p,_.id)}}},d=p=>{if(!s.size)return;const h={...p,rootId:e.sessionId};s.forEach(_=>_.next?.(h))},f={_snapshot:{_scheduledEvents:(t?.snapshot&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${x9++}`,_register:(p,h)=>(n.set(p,h),p),_unregister:p=>{n.delete(p.sessionId);const h=i.get(p);h!==void 0&&(r.delete(h),i.delete(p))},get:p=>r.get(p),getAll:()=>Object.fromEntries(r.entries()),_set:(p,h)=>{const _=r.get(p);if(_&&_!==h)throw new Error(`Actor with system ID '${p}' already exists.`);r.set(p,h),i.set(h,p)},inspect:p=>{const h=bf(p);return s.add(h),{unsubscribe(){s.delete(h)}}},_sendInspectionEvent:d,_relay:(p,h,_)=>{f._sendInspectionEvent({type:"@xstate.event",sourceRef:p,actorRef:h,event:_}),h._send(_)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...f._snapshot._scheduledEvents}}),start:()=>{const p=f._snapshot._scheduledEvents;f._snapshot._scheduledEvents={};for(const h in p){const{source:_,target:g,event:y,delay:m,id:v}=p[h];u.schedule(_,g,y,m,v)}},_clock:c,_logger:l};return f}let qd=!1;const Sh=1;let At=(function(e){return e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped",e})({});const z9={clock:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},logger:console.log.bind(console),devTools:!1};class A9{constructor(t,n){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new Nm(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=At.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const r={...z9,...n},{clock:i,logger:s,parent:a,syncSnapshot:c,id:l,systemId:u,inspect:d}=r;this.system=a?a.system:S9(this,{clock:i,logger:s}),d&&!a&&this.system.inspect(bf(d)),this.sessionId=this.system._bookId(),this.id=l??this.sessionId,this.logger=n?.logger??this.system._logger,this.clock=n?.clock??this.system._clock,this._parent=a,this._syncSnapshot=c,this.options=r,this.src=r.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:f=>{this._deferred.push(f)},system:this.system,stopChild:f=>{if(f._parent!==this)throw new Error(`Cannot stop child actor ${f.id} of ${this.id} because it is not a child`);f._stop()},emit:f=>{const p=this.eventListeners.get(f.type),h=this.eventListeners.get("*");if(!p&&!h)return;const _=[...p?p.values():[],...h?h.values():[]];for(const g of _)try{g(f)}catch(y){bn(y)}},actionExecutor:f=>{const p=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:f.type,params:f.params}}),!f.exec)return;const h=qd;try{qd=!0,f.exec(f.info,f.params)}finally{qd=h}};this._processingStatus===At.Running?p():this._deferred.push(p)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),u&&(this.systemId=u,this.system._set(u,this)),this._initState(n?.snapshot??n?.state),u&&this._snapshot.status!=="active"&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(n){this._snapshot={status:"error",output:void 0,error:n}}}update(t,n){this._snapshot=t;let r;for(;r=this._deferred.shift();)try{r()}catch(i){this._deferred.length=0,this._snapshot={...t,status:"error",error:i}}switch(this._snapshot.status){case"active":for(const i of this.observers)try{i.next?.(t)}catch(s){bn(s)}break;case"done":for(const i of this.observers)try{i.next?.(t)}catch(s){bn(s)}this._stopProcedure(),this._complete(),this._doneEvent=b9(this.id,this._snapshot.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:n,snapshot:t})}subscribe(t,n,r){const i=bf(t,n,r);if(this._processingStatus!==At.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{i.complete?.()}catch(s){bn(s)}break;case"error":{const s=this._snapshot.error;if(!i.error)bn(s);else try{i.error(s)}catch(a){bn(a)}break}}return{unsubscribe:()=>{this.observers.delete(i)}}}on(t,n){let r=this.eventListeners.get(t);r||(r=new Set,this.eventListeners.set(t,r));const i=n.bind(void 0);return r.add(i),{unsubscribe:()=>{r.delete(i)}}}start(){if(this._processingStatus===At.Running)return this;this._syncSnapshot&&this.subscribe({next:r=>{r.status==="active"&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:r})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=At.Running;const t=Qw(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t}),this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(r){return this._snapshot={...this._snapshot,status:"error",error:r},this._error(r),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let n,r;try{n=this.logic.transition(this._snapshot,t,this._actorScope)}catch(i){r={err:i}}if(r){const{err:i}=r;this._snapshot={...this._snapshot,status:"error",error:i},this._error(i);return}this.update(n,t),t.type===mf&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===At.Stopped?this:(this.mailbox.clear(),this._processingStatus===At.NotStarted?(this._processingStatus=At.Stopped,this):(this.mailbox.enqueue({type:mf}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(n){bn(n)}this.observers.clear(),this.eventListeners.clear()}_reportError(t){if(!this.observers.size){this._parent||bn(t),this.eventListeners.clear();return}let n=!1;for(const r of this.observers){const i=r.error;n||=!i;try{i?.(t)}catch(s){bn(s)}}this.observers.clear(),this.eventListeners.clear(),n&&bn(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,Yw(this.id,t))}_stopProcedure(){return this._processingStatus!==At.Running?this:(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new Nm(this._process.bind(this)),this._processingStatus=At.Stopped,this.system._unregister(this),this)}_send(t){this._processingStatus!==At.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;t&&(typeof t=="function"?t:f9)(this)}toJSON(){return{xstate$$type:Sh,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[v9](){return this}getSnapshot(){return this._snapshot}}function Qs(e,...[t]){return new A9(e,t)}function E9(e,t,n,r,{sendId:i}){const s=typeof i=="function"?i(n,r):i;return[t,{sendId:s},void 0]}function C9(e,t){e.defer(()=>{e.system.scheduler.cancel(e.self,t.sendId)})}function zh(e){function t(n,r){}return t.type="xstate.cancel",t.sendId=e,t.resolve=E9,t.execute=C9,t}function I9(e,t,n,r,{id:i,systemId:s,src:a,input:c,syncSnapshot:l}){const u=typeof a=="string"?xh(t.machine,a):a,d=typeof i=="function"?i(n):i;let f,p;return u&&(p=typeof c=="function"?c({context:t.context,event:n.event,self:e.self}):c,f=Qs(u,{id:d,src:a,parent:e.self,syncSnapshot:l,systemId:s,input:p})),[di(t,{children:{...t.children,[d]:f}}),{id:i,systemId:s,actorRef:f,src:a,input:p},void 0]}function j9(e,{actorRef:t}){t&&e.defer(()=>{t._processingStatus!==At.Stopped&&t.start()})}function Ah(...[e,{id:t,systemId:n,input:r,syncSnapshot:i=!1}={}]){function s(a,c){}return s.type="xstate.spawnChild",s.id=t,s.systemId=n,s.src=e,s.input=r,s.syncSnapshot=i,s.resolve=I9,s.execute=j9,s}function N9(e,t,n,r,{actorRef:i}){const s=typeof i=="function"?i(n,r):i,a=typeof s=="string"?t.children[s]:s;let c=t.children;return a&&(c={...c},delete c[a.id]),[di(t,{children:c}),a,void 0]}function i2(e,t){const n=t.getSnapshot();if(n&&"children"in n)for(const r of Object.values(n.children))i2(e,r);e.system._unregister(t)}function T9(e,t){if(t){if(i2(e,t),t._processingStatus!==At.Running){e.stopChild(t);return}e.defer(()=>{e.stopChild(t)})}}function hu(e){function t(n,r){}return t.type="xstate.stopChild",t.actorRef=e,t.resolve=N9,t.execute=T9,t}function _u(e,t,n,r){const{machine:i}=r,s=typeof e=="function",a=s?e:i.implementations.guards[typeof e=="string"?e:e.type];if(!s&&!a)throw new Error(`Guard '${typeof e=="string"?e:e.type}' is not implemented.'.`);if(typeof a!="function")return _u(a,t,n,r);const c={context:t,event:n},l=s||typeof e=="string"?void 0:"params"in e?typeof e.params=="function"?e.params({context:t,event:n}):e.params:void 0;return"check"in a?a.check(r,c,a):a(c,l)}function Eh(e){return e.type==="atomic"||e.type==="final"}function _o(e){return Object.values(e.states).filter(t=>t.type!=="history")}function Aa(e,t){const n=[];if(t===e)return n;let r=e.parent;for(;r&&r!==t;)n.push(r),r=r.parent;return n}function ll(e){const t=new Set(e),n=s2(t);for(const r of t)if(r.type==="compound"&&(!n.get(r)||!n.get(r).length))Lm(r).forEach(i=>t.add(i));else if(r.type==="parallel"){for(const i of _o(r))if(i.type!=="history"&&!t.has(i)){const s=Lm(i);for(const a of s)t.add(a)}}for(const r of t){let i=r.parent;for(;i;)t.add(i),i=i.parent}return t}function o2(e,t){const n=t.get(e);if(!n)return{};if(e.type==="compound"){const i=n[0];if(i){if(Eh(i))return i.key}else return{}}const r={};for(const i of n)r[i.key]=o2(i,t);return r}function s2(e){const t=new Map;for(const n of e)t.has(n)||t.set(n,[]),n.parent&&(t.has(n.parent)||t.set(n.parent,[]),t.get(n.parent).push(n));return t}function a2(e,t){const n=ll(t);return o2(e,s2(n))}function Ch(e,t){return t.type==="compound"?_o(t).some(n=>n.type==="final"&&e.has(n)):t.type==="parallel"?_o(t).every(n=>Ch(e,n)):t.type==="final"}const mu=e=>e[0]===_9;function P9(e,t){return e.transitions.get(t)||[...e.transitions.keys()].filter(r=>$9(t,r)).sort((r,i)=>i.length-r.length).flatMap(r=>e.transitions.get(r))}function O9(e){const t=e.config.after;if(!t)return[];const n=i=>{const s=y9(i,e.id),a=s.type;return e.entry.push(Nh(s,{id:a,delay:i})),e.exit.push(zh(a)),a};return Object.keys(t).flatMap(i=>{const s=t[i],a=typeof s=="string"?{target:s}:s,c=Number.isNaN(+i)?i:+i,l=n(c);return gr(a).map(u=>({...u,event:l,delay:c}))}).map(i=>{const{delay:s}=i;return{...hr(e,i.event,i),delay:s}})}function hr(e,t,n){const r=r2(n.target),i=n.reenter??!1,s=U9(e,r),a={...n,actions:gr(n.actions),guard:n.guard,target:s,source:e,reenter:i,eventType:t,toJSON:()=>({...a,source:`#${e.id}`,target:s?s.map(c=>`#${c.id}`):void 0})};return a}function R9(e){const t=new Map;if(e.config.on)for(const n of Object.keys(e.config.on)){if(n===Zw)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const r=e.config.on[n];t.set(n,Vi(r).map(i=>hr(e,n,i)))}if(e.config.onDone){const n=`xstate.done.state.${e.id}`;t.set(n,Vi(e.config.onDone).map(r=>hr(e,n,r)))}for(const n of e.invoke){if(n.onDone){const r=`xstate.done.actor.${n.id}`;t.set(r,Vi(n.onDone).map(i=>hr(e,r,i)))}if(n.onError){const r=`xstate.error.actor.${n.id}`;t.set(r,Vi(n.onError).map(i=>hr(e,r,i)))}if(n.onSnapshot){const r=`xstate.snapshot.${n.id}`;t.set(r,Vi(n.onSnapshot).map(i=>hr(e,r,i)))}}for(const n of e.after){let r=t.get(n.eventType);r||(r=[],t.set(n.eventType,r)),r.push(n)}return t}function L9(e){const t=[],n=r=>{Object.values(r).forEach(i=>{if(i.config.route&&i.config.id){const s=i.config.id,a=i.config.route.guard,c=(u,d)=>u.event.to!==`#${s}`?!1:a&&typeof a=="function"?a(u,d):!0,l={...i.config.route,guard:c,target:`#${s}`};t.push(hr(e,"xstate.route",l))}i.states&&n(i.states)})};n(e.states),t.length>0&&e.transitions.set("xstate.route",t)}function D9(e,t){const n=typeof t=="string"?e.states[t]:t?e.states[t.target]:void 0;if(!n&&t)throw new Error(`Initial state node "${t}" not found on parent state node #${e.id}`);const r={source:e,actions:!t||typeof t=="string"?[]:gr(t.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...r,source:`#${e.id}`,target:n?[`#${n.id}`]:[]})};return r}function U9(e,t){if(t!==void 0)return t.map(n=>{if(typeof n!="string")return n;if(mu(n))return e.machine.getStateNodeById(n);const r=n[0]===Jw;if(r&&!e.parent)return ul(e,n.slice(1));const i=r?e.key+n:n;if(e.parent)try{return ul(e.parent,i)}catch(s){throw new Error(`Invalid transition definition for state node '${e.id}':
|
|
66
66
|
${s.message}`)}else throw new Error(`Invalid target: "${n}" is not a valid target from the root node. Did you mean ".${n}"?`)})}function c2(e){const t=r2(e.config.target);return t?{target:t.map(n=>typeof n=="string"?ul(e.parent,n):n)}:e.parent.initial}function ri(e){return e.type==="history"}function Lm(e){const t=l2(e);for(const n of t)for(const r of Aa(n,e))t.add(r);return t}function l2(e){const t=new Set;function n(r){if(!t.has(r)){if(t.add(r),r.type==="compound")n(r.initial.target[0]);else if(r.type==="parallel")for(const i of _o(r))n(i)}}return n(e),t}function mo(e,t){if(mu(t))return e.machine.getStateNodeById(t);if(!e.states)throw new Error(`Unable to retrieve child state '${t}' from '${e.id}'; no child states exist.`);const n=e.states[t];if(!n)throw new Error(`Child state '${t}' does not exist on '${e.id}'`);return n}function ul(e,t){if(typeof t=="string"&&mu(t))try{return e.machine.getStateNodeById(t)}catch{}const n=$h(t).slice();let r=e;for(;n.length;){const i=n.shift();if(!i.length)break;r=mo(r,i)}return r}function dl(e,t){if(typeof t=="string"){const i=e.states[t];if(!i)throw new Error(`State '${t}' does not exist on '${e.id}'`);return[e,i]}const n=Object.keys(t),r=n.map(i=>mo(e,i)).filter(Boolean);return[e.machine.root,e].concat(r,n.reduce((i,s)=>{const a=mo(e,s);if(!a)return i;const c=dl(a,t[s]);return i.concat(c)},[]))}function B9(e,t,n,r){const s=mo(e,t).next(n,r);return!s||!s.length?e.next(n,r):s}function M9(e,t,n,r){const i=Object.keys(t),s=mo(e,i[0]),a=Ih(s,t[i[0]],n,r);return!a||!a.length?e.next(n,r):a}function q9(e,t,n,r){const i=[];for(const s of Object.keys(t)){const a=t[s];if(!a)continue;const c=mo(e,s),l=Ih(c,a,n,r);l&&i.push(...l)}return i.length?i:e.next(n,r)}function Ih(e,t,n,r){return typeof t=="string"?B9(e,t,n,r):Object.keys(t).length===1?M9(e,t,n,r):q9(e,t,n,r)}function F9(e){return Object.keys(e.states).map(t=>e.states[t]).filter(t=>t.type==="history")}function Sr(e,t){let n=e;for(;n.parent&&n.parent!==t;)n=n.parent;return n.parent===t}function H9(e,t){const n=new Set(e),r=new Set(t);for(const i of n)if(r.has(i))return!0;for(const i of r)if(n.has(i))return!0;return!1}function u2(e,t,n){const r=new Set;for(const i of e){let s=!1;const a=new Set;for(const c of r)if(H9(vf([i],t,n),vf([c],t,n)))if(Sr(i.source,c.source))a.add(c);else{s=!0;break}if(!s){for(const c of a)r.delete(c);r.add(i)}}return Array.from(r)}function V9(e){const[t,...n]=e;for(const r of Aa(t,void 0))if(n.every(i=>Sr(i,r)))return r}function jh(e,t){if(!e.target)return[];const n=new Set;for(const r of e.target)if(ri(r))if(t[r.id])for(const i of t[r.id])n.add(i);else for(const i of jh(c2(r),t))n.add(i);else n.add(r);return[...n]}function d2(e,t){const n=jh(e,t);if(!n)return;if(!e.reenter&&n.every(i=>i===e.source||Sr(i,e.source)))return e.source;const r=V9(n.concat(e.source));if(r)return r;if(!e.reenter)return e.source.machine.root}function vf(e,t,n){const r=new Set;for(const i of e)if(i.target?.length){const s=d2(i,n);i.reenter&&i.source===s&&r.add(s);for(const a of t)Sr(a,s)&&r.add(a)}return[...r]}function K9(e,t){if(e.length!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function G9(e,t,n,r,i){return wf([{target:[...l2(e)],source:e,reenter:!0,actions:[],eventType:null,toJSON:null}],t,n,r,!0,i)}function wf(e,t,n,r,i,s){const a=[];if(!e.length)return[t,a];const c=n.actionExecutor;n.actionExecutor=l=>{a.push(l),c(l)};try{const l=new Set(t._nodes);let u=t.historyValue;const d=u2(e,l,u);let f=t;i||([f,u]=X9(f,r,n,d,l,u,s,n.actionExecutor)),f=go(f,r,n,d.flatMap(h=>h.actions),s,void 0),f=J9(f,r,n,d,l,s,u,i);const p=[...l];f.status==="done"&&(f=go(f,r,n,p.sort((h,_)=>_.order-h.order).flatMap(h=>h.exit),s,void 0));try{return u===t.historyValue&&K9(t._nodes,l)?[f,a]:[di(f,{_nodes:p,historyValue:u}),a]}catch(h){throw h}}finally{n.actionExecutor=c}}function W9(e,t,n,r,i){if(r.output===void 0)return;const s=gf(i.id,i.output!==void 0&&i.parent?yf(i.output,e.context,t,n.self):void 0);return yf(r.output,e.context,s,n.self)}function J9(e,t,n,r,i,s,a,c){let l=e;const u=new Set,d=new Set;Z9(r,a,d,u),c&&d.add(e.machine.root);const f=new Set;for(const p of[...u].sort((h,_)=>h.order-_.order)){i.add(p);const h=[];h.push(...p.entry);for(const _ of p.invoke)h.push(Ah(_.src,{..._,syncSnapshot:!!_.onSnapshot}));if(d.has(p)){const _=p.initial.actions;h.push(..._)}if(l=go(l,t,n,h,s,p.invoke.map(_=>_.id)),p.type==="final"){const _=p.parent;let g=_?.type==="parallel"?_:_?.parent,y=g||p;for(_?.type==="compound"&&s.push(gf(_.id,p.output!==void 0?yf(p.output,l.context,t,n.self):void 0));g?.type==="parallel"&&!f.has(g)&&Ch(i,g);)f.add(g),s.push(gf(g.id)),y=g,g=g.parent;if(g)continue;l=di(l,{status:"done",output:W9(l,t,n,l.machine.root,y)})}}return l}function Z9(e,t,n,r){for(const i of e){const s=d2(i,t);for(const c of i.target||[])!ri(c)&&(i.source!==c||i.source!==s||i.reenter)&&(r.add(c),n.add(c)),io(c,t,n,r);const a=jh(i,t);for(const c of a){const l=Aa(c,s);s?.type==="parallel"&&l.push(s),p2(r,t,n,l,!i.source.parent&&i.reenter?void 0:s)}}}function io(e,t,n,r){if(ri(e))if(t[e.id]){const i=t[e.id];for(const s of i)r.add(s),io(s,t,n,r);for(const s of i)Fd(s,e.parent,r,t,n)}else{const i=c2(e);for(const s of i.target)r.add(s),i===e.parent?.initial&&n.add(e.parent),io(s,t,n,r);for(const s of i.target)Fd(s,e.parent,r,t,n)}else if(e.type==="compound"){const[i]=e.initial.target;ri(i)||(r.add(i),n.add(i)),io(i,t,n,r),Fd(i,e,r,t,n)}else if(e.type==="parallel")for(const i of _o(e).filter(s=>!ri(s)))[...r].some(s=>Sr(s,i))||(ri(i)||(r.add(i),n.add(i)),io(i,t,n,r))}function p2(e,t,n,r,i){for(const s of r)if((!i||Sr(s,i))&&e.add(s),s.type==="parallel")for(const a of _o(s).filter(c=>!ri(c)))[...e].some(c=>Sr(c,a))||(e.add(a),io(a,t,n,e))}function Fd(e,t,n,r,i){p2(n,r,i,Aa(e,t))}function X9(e,t,n,r,i,s,a,c){let l=e;const u=vf(r,i,s);u.sort((f,p)=>p.order-f.order);let d;for(const f of u)for(const p of F9(f)){let h;p.history==="deep"?h=_=>Eh(_)&&Sr(_,f):h=_=>_.parent===f,d??={...s},d[p.id]=Array.from(i).filter(h)}for(const f of u)l=go(l,t,n,[...f.exit,...f.invoke.map(p=>hu(p.id))],a,void 0),i.delete(f);return[l,d||s]}function Y9(e,t){return e.implementations.actions[t]}function f2(e,t,n,r,i,s){const{machine:a}=e;let c=e;for(const l of r){const u=typeof l=="function",d=u?l:Y9(a,typeof l=="string"?l:l.type),f={context:c.context,event:t,self:n.self,system:n.system},p=u||typeof l=="string"?void 0:"params"in l?typeof l.params=="function"?l.params({context:c.context,event:t}):l.params:void 0;if(!d||!("resolve"in d)){n.actionExecutor({type:typeof l=="string"?l:typeof l=="object"?l.type:l.name||"(anonymous)",info:f,params:p,exec:d});continue}const h=d,[_,g,y]=h.resolve(n,c,f,p,d,i);c=_,"retryResolve"in h&&s?.push([h,g]),"execute"in h&&n.actionExecutor({type:h.type,info:f,params:g,exec:h.execute.bind(null,n,g)}),y&&(c=f2(c,t,n,y,i,s))}return c}function go(e,t,n,r,i,s){const a=s?[]:void 0,c=f2(e,t,n,r,{internalQueue:i,deferredActorIds:s},a);return a?.forEach(([l,u])=>{l.retryResolve(n,c,u)}),c}function Hd(e,t,n,r){let i=e;const s=[];function a(u,d,f){n.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:n.self,event:d,snapshot:u[0],_transitions:f}),s.push(u)}if(t.type===mf)return i=di(Dm(i,t,n),{status:"stopped"}),a([i,[]],t,[]),{snapshot:i,microsteps:s};let c=t;if(c.type!==Xw){const u=c,d=k9(u),f=Um(u,i);if(d&&!f.length)return i=di(e,{status:"error",error:u.error}),a([i,[]],u,[]),{snapshot:i,microsteps:s};const p=wf(f,e,n,c,!1,r);i=p[0],a(p,u,f)}let l=!0;for(;i.status==="active";){let u=l?Q9(i,c):[];const d=u.length?i:void 0;if(!u.length){if(!r.length)break;c=r.shift(),u=Um(c,i)}const f=wf(u,i,n,c,!1,r);i=f[0],l=i!==d,a(f,c,u)}return i.status!=="active"&&Dm(i,c,n),{snapshot:i,microsteps:s}}function Dm(e,t,n){return go(e,t,n,Object.values(e.children).map(r=>hu(r)),[],void 0)}function Um(e,t){return t.machine.getTransitionData(t,e)}function Q9(e,t){const n=new Set,r=e._nodes.filter(Eh);for(const i of r)e:for(const s of[i].concat(Aa(i,void 0)))if(s.always){for(const a of s.always)if(a.guard===void 0||_u(a.guard,e.context,t,e)){n.add(a);break e}}return u2(Array.from(n),new Set(e._nodes),e.historyValue)}function eA(e,t){const n=ll(dl(e,t));return a2(e,[...n])}function tA(e){return!!e&&typeof e=="object"&&"machine"in e&&"value"in e}const nA=function(t){return e2(t,this.value)},rA=function(t){return this.tags.has(t)},iA=function(t){const n=this.machine.getTransitionData(this,t);return!!n?.length&&n.some(r=>r.target!==void 0||r.actions.length)},oA=function(){const{_nodes:t,tags:n,machine:r,getMeta:i,toJSON:s,can:a,hasTag:c,matches:l,...u}=this;return{...u,tags:Array.from(n)}},sA=function(){return this._nodes.reduce((t,n)=>(n.meta!==void 0&&(t[n.id]=n.meta),t),{})};function Ec(e,t){return{status:e.status,output:e.output,error:e.error,machine:t,context:e.context,_nodes:e._nodes,value:a2(t.root,e._nodes),tags:new Set(e._nodes.flatMap(n=>n.tags)),children:e.children,historyValue:e.historyValue||{},matches:nA,hasTag:rA,can:iA,getMeta:sA,toJSON:oA}}function di(e,t={}){return Ec({...e,...t},e.machine)}function aA(e){if(typeof e!="object"||e===null)return{};const t={};for(const n in e){const r=e[n];Array.isArray(r)&&(t[n]=r.map(i=>({id:i.id})))}return t}function cA(e,t){const{_nodes:n,tags:r,machine:i,children:s,context:a,can:c,hasTag:l,matches:u,getMeta:d,toJSON:f,...p}=e,h={};for(const g in s){const y=s[g];h[g]={snapshot:y.getPersistedSnapshot(t),src:y.src,systemId:y.systemId,syncSnapshot:y._syncSnapshot}}return{...p,context:h2(a),children:h,historyValue:aA(p.historyValue)}}function h2(e){let t;for(const n in e){const r=e[n];if(r&&typeof r=="object")if("sessionId"in r&&"send"in r&&"ref"in r)t??=Array.isArray(e)?e.slice():{...e},t[n]={xstate$$type:Sh,id:r.id};else{const i=h2(r);i!==r&&(t??=Array.isArray(e)?e.slice():{...e},t[n]=i)}}return t??e}function lA(e,t,n,r,{event:i,id:s,delay:a},{internalQueue:c}){const l=t.machine.implementations.delays;if(typeof i=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${i}" }) instead`);const u=typeof i=="function"?i(n,r):i;let d;if(typeof a=="string"){const f=l&&l[a];d=typeof f=="function"?f(n,r):f}else d=typeof a=="function"?a(n,r):a;return typeof d!="number"&&c.push(u),[t,{event:u,id:s,delay:d},void 0]}function uA(e,t){const{event:n,delay:r,id:i}=t;if(typeof r=="number"){e.defer(()=>{const s=e.self;e.system.scheduler.schedule(s,s,n,r,i)});return}}function Nh(e,t){function n(r,i){}return n.type="xstate.raise",n.event=e,n.id=t?.id,n.delay=t?.delay,n.resolve=lA,n.execute=uA,n}function dA(e,{machine:t,context:n},r,i){const s=(a,c)=>{if(typeof a=="string"){const l=xh(t,a);if(!l)throw new Error(`Actor logic '${a}' not implemented in machine '${t.id}'`);const u=Qs(l,{id:c?.id,parent:e.self,syncSnapshot:c?.syncSnapshot,input:typeof c?.input=="function"?c.input({context:n,event:r,self:e.self}):c?.input,src:a,systemId:c?.systemId});return i[u.id]=u,u}else return Qs(a,{id:c?.id,parent:e.self,syncSnapshot:c?.syncSnapshot,input:c?.input,src:a,systemId:c?.systemId})};return(a,c)=>{const l=s(a,c);return i[l.id]=l,e.defer(()=>{l._processingStatus!==At.Stopped&&l.start()}),l}}function pA(e,t,n,r,{assignment:i}){if(!t.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const s={},a={context:t.context,event:n.event,spawn:dA(e,t,n.event,s),self:e.self,system:e.system};let c={};if(typeof i=="function")c=i(a,r);else for(const u of Object.keys(i)){const d=i[u];c[u]=typeof d=="function"?d(a,r):d}const l=Object.assign({},t.context,c);return[di(t,{context:l,children:Object.keys(s).length?{...t.children,...s}:t.children}),void 0,void 0]}function Kn(e){function t(n,r){}return t.type="xstate.assign",t.assignment=e,t.resolve=pA,t}const Bm=new WeakMap;function Bi(e,t,n){let r=Bm.get(e);return r?t in r||(r[t]=n()):(r={[t]:n()},Bm.set(e,r)),r[t]}const fA={},ss=e=>typeof e=="string"?{type:e}:typeof e=="function"?"resolve"in e?{type:e.type}:{type:e.name}:e;class pl{constructor(t,n){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=n._parent,this.key=n._key,this.machine=n._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(Jw),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?Pm(this.config.states,(r,i)=>new pl(r,{_parent:this,_key:i,_machine:this.machine})):fA,this.type==="compound"&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?"shallow":this.config.history||!1,this.entry=gr(this.config.entry).slice(),this.exit=gr(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=gr(t.tags).slice()}_initialize(){this.transitions=R9(this),this.config.always&&(this.always=Vi(this.config.always).map(t=>hr(this,Zw,t))),Object.keys(this.states).forEach(t=>{this.states[t]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(ss),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(ss),eventType:null})}:void 0,history:this.history,states:Pm(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(ss)})),entry:this.entry.map(ss),exit:this.exit.map(ss),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return Bi(this,"invoke",()=>gr(this.config.invoke).map((t,n)=>{const{src:r,systemId:i}=t,s=t.id??Om(this.id,n),a=typeof r=="string"?r:`xstate.invoke.${Om(this.id,n)}`;return{...t,src:a,id:s,systemId:i,toJSON(){const{onDone:c,onError:l,...u}=t;return{...u,type:"xstate.invoke",src:a,id:s}}}}))}get on(){return Bi(this,"on",()=>[...this.transitions].flatMap(([n,r])=>r.map(i=>[n,i])).reduce((n,[r,i])=>(n[r]=n[r]||[],n[r].push(i),n),{}))}get after(){return Bi(this,"delayedTransitions",()=>O9(this))}get initial(){return Bi(this,"initial",()=>D9(this,this.config.initial))}next(t,n){const r=n.type,i=[];let s;const a=Bi(this,`candidates-${r}`,()=>P9(this,r));for(const c of a){const{guard:l}=c,u=t.context;let d=!1;try{d=!l||_u(l,u,n,t)}catch(f){const p=typeof l=="string"?l:typeof l=="object"?l.type:void 0;throw new Error(`Unable to evaluate guard ${p?`'${p}' `:""}in transition for event '${r}' in state node '${this.id}':
|
|
67
|
-
${f.message}`)}if(d){i.push(...c.actions),s=c;break}}return s?[s]:void 0}get events(){return Bi(this,"events",()=>{const{states:t}=this,n=new Set(this.ownEvents);if(t)for(const r of Object.keys(t)){const i=t[r];if(i.states)for(const s of i.events)n.add(`${s}`)}return Array.from(n)})}get ownEvents(){const t=Object.keys(Object.fromEntries(this.transitions)),n=new Set(t.filter(r=>this.transitions.get(r).some(i=>!(!i.target&&!i.actions.length&&!i.reenter))));return Array.from(n)}}const hA="#";class Th{constructor(t,n){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:n?.actors??{},actions:n?.actions??{},delays:n?.delays??{},guards:n?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new pl(t,{_key:this.id,_machine:this}),this.root._initialize(),L9(this.root),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:n,guards:r,actors:i,delays:s}=this.implementations;return new Th(this.config,{actions:{...n,...t.actions},guards:{...r,...t.guards},actors:{...i,...t.actors},delays:{...s,...t.delays}})}resolveState(t){const n=eA(this.root,t.value),r=ll(dl(this.root,n));return Ec({_nodes:[...r],context:t.context||{},children:{},status:Ch(r,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,n,r){return Hd(t,n,r,[]).snapshot}microstep(t,n,r){return Hd(t,n,r,[]).microsteps.map(([i])=>i)}getTransitionData(t,n){return Ih(this.root,t.value,t,n)||[]}_getPreInitialState(t,n,r){const{context:i}=this.config,s=Ec({context:typeof i!="function"&&i?i:{},_nodes:[this.root],children:{},status:"active"},this);return typeof i=="function"?go(s,n,t,[Kn(({spawn:c,event:l,self:u})=>i({spawn:c,input:l.input,self:u}))],r,void 0):s}getInitialSnapshot(t,n){const r=Qw(n),i=[],s=this._getPreInitialState(t,r,i),[a]=G9(this.root,s,t,r,i),{snapshot:c}=Hd(a,r,t,i);return c}start(t){Object.values(t.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(t){const n=$h(t),r=n.slice(1),i=mu(n[0])?n[0].slice(hA.length):n[0],s=this.idMap.get(i);if(!s)throw new Error(`Child state node '#${i}' does not exist on machine '${this.id}'`);return ul(s,r)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,n){return cA(t,n)}restoreSnapshot(t,n){const r={},i=t.children;Object.keys(i).forEach(f=>{const p=i[f],h=p.snapshot,_=p.src,g=typeof _=="string"?xh(this,_):_;if(!g)return;const y=Qs(g,{id:f,parent:n.self,syncSnapshot:p.syncSnapshot,snapshot:h,src:_,systemId:p.systemId});r[f]=y});function s(f,p){if(p instanceof pl)return p;try{return f.machine.getStateNodeById(p.id)}catch{}}function a(f,p){if(!p||typeof p!="object")return{};const h={};for(const _ in p){const g=p[_];for(const y of g){const m=s(f,y);m&&(h[_]??=[],h[_].push(m))}}return h}const c=a(this.root,t.historyValue),l=Ec({...t,children:r,_nodes:Array.from(ll(dl(this.root,t.value))),historyValue:c},this),u=new Set;function d(f,p){if(!u.has(f)){u.add(f);for(const h in f){const _=f[h];if(_&&typeof _=="object"){if("xstate$$type"in _&&_.xstate$$type===Sh){f[h]=p[_.id];continue}d(_,p)}}}}return d(l.context,r),l}}function _A(e,t,n,r,{event:i}){const s=typeof i=="function"?i(n,r):i;return[t,{event:s},void 0]}function mA(e,{event:t}){e.defer(()=>e.emit(t))}function _2(e){function t(n,r){}return t.type="xstate.emit",t.event=e,t.resolve=_A,t.execute=mA,t}let kf=(function(e){return e.Parent="#_parent",e.Internal="#_internal",e})({});function gA(e,t,n,r,{to:i,event:s,id:a,delay:c},l){const u=t.machine.implementations.delays;if(typeof s=="string")throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${s}" }) instead`);const d=typeof s=="function"?s(n,r):s;let f;if(typeof c=="string"){const _=u&&u[c];f=typeof _=="function"?_(n,r):_}else f=typeof c=="function"?c(n,r):c;const p=typeof i=="function"?i(n,r):i;let h;if(typeof p=="string"){if(p===kf.Parent?h=e.self._parent:p===kf.Internal?h=e.self:p.startsWith("#_")?h=t.children[p.slice(2)]:h=l.deferredActorIds?.includes(p)?p:t.children[p],!h)throw new Error(`Unable to send event to actor '${p}' from machine '${t.machine.id}'.`)}else h=p||e.self;return[t,{to:h,targetId:typeof p=="string"?p:void 0,event:d,id:a,delay:f},void 0]}function yA(e,t,n){typeof n.to=="string"&&(n.to=t.children[n.to])}function bA(e,t){e.defer(()=>{const{to:n,event:r,delay:i,id:s}=t;if(typeof i=="number"){e.system.scheduler.schedule(e.self,n,r,i,s);return}e.system._relay(e.self,n,r.type===g9?Yw(e.self.id,r.data):r)})}function Ph(e,t,n){function r(i,s){}return r.type="xstate.sendTo",r.to=e,r.event=t,r.id=n?.id,r.delay=n?.delay,r.resolve=gA,r.retryResolve=yA,r.execute=bA,r}function vA(e,t){return Ph(kf.Parent,e,t)}function wA(e,t,n,r,{collect:i}){const s=[],a=function(l){s.push(l)};return a.assign=(...c)=>{s.push(Kn(...c))},a.cancel=(...c)=>{s.push(zh(...c))},a.raise=(...c)=>{s.push(Nh(...c))},a.sendTo=(...c)=>{s.push(Ph(...c))},a.sendParent=(...c)=>{s.push(vA(...c))},a.spawnChild=(...c)=>{s.push(Ah(...c))},a.stopChild=(...c)=>{s.push(hu(...c))},a.emit=(...c)=>{s.push(_2(...c))},i({context:n.context,event:n.event,enqueue:a,check:c=>_u(c,t.context,n.event,t),self:e.self,system:e.system},r),[t,void 0,s]}function kA(e){function t(n,r){}return t.type="xstate.enqueueActions",t.collect=e,t.resolve=wA,t}function $A(e,t,n,r,{value:i,label:s}){return[t,{value:typeof i=="function"?i(n,r):i,label:s},void 0]}function xA({logger:e},{value:t,label:n}){n?e(n,t):e(t)}function SA(e=({context:n,event:r})=>({context:n,event:r}),t){function n(r,i){}return n.type="xstate.log",n.value=e,n.label=t,n.resolve=$A,n.execute=xA,n}function zA(e,t){return new Th(e,t)}function AA(e){const t=Qs(e);return{self:t,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:t.system,emit:()=>{},actionExecutor:()=>{}}}function m2({schemas:e,actors:t,actions:n,guards:r,delays:i}){return{assign:Kn,sendTo:Ph,raise:Nh,log:SA,cancel:zh,stopChild:hu,enqueueActions:kA,emit:_2,spawnChild:Ah,createStateConfig:s=>s,createAction:s=>s,createMachine:s=>zA({...s,schemas:e},{actors:t,actions:n,guards:r,delays:i}),extend:s=>m2({schemas:e,actors:t,actions:{...n,...s.actions},guards:{...r,...s.guards},delays:{...i,...s.delays}})}}function EA(e,t,n){const r=[],i=AA(e);return i.actionExecutor=a=>{r.push(a)},[e.transition(t,n,i),r]}var Pr=(e=>(e.AUTHENTICATE="AUTHENTICATE",e.REQUIRE_EMAIL_VERIFICATION="REQUIRE_EMAIL_VERIFICATION",e.START_HOOK="START_HOOK",e.COMPLETE_HOOK="COMPLETE_HOOK",e.START_CONTINUATION="START_CONTINUATION",e.COMPLETE_CONTINUATION="COMPLETE_CONTINUATION",e.COMPLETE="COMPLETE",e.FAIL="FAIL",e.EXPIRE="EXPIRE",e))(Pr||{});const g2=m2({actions:{setUserId:Kn(({event:e})=>e.type==="AUTHENTICATE"?{userId:e.userId}:{}),setHookId:Kn(({event:e})=>e.type==="START_HOOK"?{hookId:e.hookId}:{}),clearHookId:Kn({hookId:void 0}),setContinuationScope:Kn(({event:e})=>e.type==="START_CONTINUATION"?{continuationScope:e.scope}:{}),clearContinuationScope:Kn({continuationScope:void 0}),setFailureReason:Kn(({event:e})=>e.type==="FAIL"?{failureReason:e.reason}:{})}}).createMachine({id:"loginSession",initial:"pending",context:{},states:{pending:{on:{AUTHENTICATE:{target:"authenticated",actions:"setUserId"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},authenticated:{on:{REQUIRE_EMAIL_VERIFICATION:{target:"awaiting_email_verification"},START_HOOK:{target:"awaiting_hook",actions:"setHookId"},START_CONTINUATION:{target:"awaiting_continuation",actions:"setContinuationScope"},COMPLETE:{target:"completed"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},awaiting_email_verification:{on:{COMPLETE:{target:"authenticated"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},awaiting_hook:{on:{COMPLETE_HOOK:{target:"authenticated",actions:"clearHookId"},START_CONTINUATION:{target:"awaiting_continuation",actions:"setContinuationScope"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},awaiting_continuation:{on:{COMPLETE_CONTINUATION:{target:"authenticated",actions:"clearContinuationScope"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},completed:{type:"final"},failed:{type:"final"},expired:{type:"final"}}});function CA(e,t={}){return g2.resolveState({value:e,context:t})}function ji(e,t,n={}){const r=CA(e,n),[i]=EA(g2,r,t),s={},a=i.context,c=n;return a.userId!==c.userId&&(s.userId=a.userId),a.hookId!==c.hookId&&(s.hookId=a.hookId),a.continuationScope!==c.continuationScope&&(s.continuationScope=a.continuationScope),a.failureReason!==c.failureReason&&(s.failureReason=a.failureReason),{state:i.value,context:s}}function IA(e,t){Object.keys(t).forEach(n=>{const r=t[n];r!=null&&r.length&&e.searchParams.set(n,r)})}function jA(e){try{const t=typeof e=="string"?new URL(e):e;let n=`${t.protocol}//${t.host}${t.pathname}`;if(t.search){const r=Array.from(t.searchParams.keys()).map(i=>`${i}=[REDACTED]`).join("&");n+=`?${r}`}return t.hash&&(n+="#[REDACTED]"),n}catch{const n=(typeof e=="string"?e:e.toString()).match(/^([^?#]*)(\?[^#]*)?(#.*)?$/);if(!n)return"[invalid-url]";const[,r="",i,s]=n;let a=r;if(i){const c=i.substring(1).split("&").map(l=>{const[u]=l.split("=");return`${u}=[REDACTED]`}).join("&");a+=`?${c}`}return s&&(a+="#[REDACTED]"),a}}const Mm=["sub","iss","aud","exp","nbf","iat","jti"];function qm(e,t,n){return{accessToken:{setCustomClaim:(r,i)=>{if(Mm.includes(r))throw new Error(`Cannot overwrite reserved claim '${r}'`);t[r]=i}},idToken:{setCustomClaim:(r,i)=>{if(Mm.includes(r))throw new Error(`Cannot overwrite reserved claim '${r}'`);n&&(n[r]=i)}},access:{deny:r=>{throw new W(400,{message:`Access denied: ${r}`})}},token:{createServiceToken:async r=>(await bu(e,e.var.tenant_id,r.scope,r.expiresInSeconds)).access_token}}}async function gu(e,t){const{authParams:n,user:r,client:i,session_id:s,organization:a,permissions:c,impersonatingUser:l,auth_time:u}=t,{signingKeys:d}=await e.env.data.keys.list({q:"type:jwt_signing"}),f=d.filter(E=>!E.revoked_at||new Date(E.revoked_at)>new Date),p=f[f.length-1];if(!p?.pkcs7)throw new W(500,{message:"No signing key available"});const h=yz(p.pkcs7),_=e.var.custom_domain?`https://${e.var.custom_domain}/`:e.env.ISSUER,g=n.audience||i.tenant.audience;if(!g)throw new W(400,{error:"invalid_request",error_description:"An audience must be specified in the request or configured as the tenant default_audience"});const y={aud:g,scope:n.scope||"",sub:r?.user_id||n.client_id,iss:_,tenant_id:e.var.tenant_id,sid:s,act:l?{sub:l.user_id}:void 0,org_id:a?a.id:void 0,org_name:a&&i.tenant.allow_organization_name_in_authentication_api?a.name.toLowerCase():void 0,permissions:c},m=n.scope?.split(" ")||[],v=m.includes("openid"),k=m.includes("profile"),x=m.includes("email"),b=n.response_type===ot.ID_TOKEN,S=i.auth0_conformant!==!1||b,A=r&&v?{aud:n.client_id,sub:r.user_id,iss:_,sid:s,nonce:n.nonce,...n.max_age!==void 0&&u!==void 0?{auth_time:u}:{},...n.acr_values?{acr:n.acr_values.split(" ")[0]}:{},...k&&S&&{given_name:r.given_name,family_name:r.family_name,nickname:r.nickname,picture:r.picture,locale:r.locale,name:r.name},...x&&S&&{email:r.email,email_verified:r.email_verified},act:l?{sub:l.user_id}:void 0,org_id:a?.id,org_name:a?.name.toLowerCase()}:void 0;e.env.hooks?.onExecuteCredentialsExchange&&await e.env.hooks.onExecuteCredentialsExchange({ctx:e,client:i,user:r,request:{ip:e.var.ip||"",user_agent:e.var.useragent||"",method:e.req.method,url:e.req.url},scope:n.scope||"",grant_type:""},qm(e,y,A));{const{hooks:E}=await e.env.data.hooks.list(e.var.tenant_id,{q:"trigger_id:credentials-exchange",page:0,per_page:100,include_totals:!1}),L=E.filter(H=>H.enabled&&al(H)),M=qm(e,y,A);if(r){for(const H of L)if(al(H))try{await c9(e,H.template_id,r,M)}catch(D){if(D instanceof I)throw D;console.warn(`[credentials-exchange] Failed to execute template hook: ${H.template_id}`,D)}}}const C={expiresIn:l?new ol(1,"h"):new ol(1,"d"),headers:{kid:p.kid}},P=await xm("RS256",h,y,C),R=A?await xm("RS256",h,A,C):void 0;return{access_token:P,refresh_token:t.refresh_token,id_token:R,token_type:"Bearer",expires_in:l?3600:86400}}async function y2(e,t){return{code:(await e.env.data.codes.create(t.client.tenant.id,{code_id:Oe(32),user_id:t.user.user_id,code_type:"authorization_code",login_id:t.login_id,expires_at:new Date(Date.now()+wz*1e3).toISOString(),code_challenge:t.authParams.code_challenge,code_challenge_method:t.authParams.code_challenge_method,redirect_uri:t.authParams.redirect_uri,state:t.authParams.state,nonce:t.authParams.nonce})).code_id,state:t.authParams.state}}async function b2(e,t){const{client:n,scope:r,audience:i=n.tenant.audience,session_id:s}=t;return await e.env.data.refreshTokens.create(n.tenant.id,{id:Uw(),session_id:s,client_id:n.client_id,idle_expires_at:new Date(Date.now()+pu*1e3).toISOString(),user_id:t.user.user_id,device:{last_ip:e.var.ip,initial_ip:e.var.ip,last_user_agent:e.var.useragent||"",initial_user_agent:e.var.useragent||"",initial_asn:"",last_asn:""},resource_servers:[{audience:i,scopes:r}],rotating:!1})}async function Fm(e,{user:t,client:n,loginSession:r}){return await e.env.data.sessions.create(n.tenant.id,{id:Uw(),user_id:t.user_id,login_session_id:r.id,idle_expires_at:new Date(Date.now()+pu*1e3).toISOString(),device:{last_ip:e.var.ip||"",initial_ip:e.var.ip||"",last_user_agent:e.var.useragent||"",initial_user_agent:e.var.useragent||"",initial_asn:"",last_asn:""},clients:[n.client_id]})}async function NA(e,{user:t,client:n,loginSession:r,existingSessionId:i}){const s=await e.env.data.loginSessions.get(n.tenant.id,r.id);if(!s)throw new I(400,{message:`Login session ${r.id} not found`});const a=s.state||We.PENDING;if(a===We.FAILED||a===We.EXPIRED||a===We.COMPLETED)throw new I(400,{message:`Cannot authenticate login session in ${a} state`});if(a===We.AUTHENTICATED){if(s.session_id)return s.session_id;throw new I(500,{message:"Login session is authenticated but has no session_id"})}let c;if(i){const u=await e.env.data.sessions.get(n.tenant.id,i);!u||u.revoked_at?c=(await Fm(e,{user:t,client:n,loginSession:r})).id:(c=i,u.clients.includes(n.client_id)||await e.env.data.sessions.update(n.tenant.id,i,{clients:[...u.clients,n.client_id]}))}else c=(await Fm(e,{user:t,client:n,loginSession:r})).id;const{state:l}=ji(a,{type:Pr.AUTHENTICATE,userId:t.user_id});return await e.env.data.loginSessions.update(n.tenant.id,r.id,{session_id:c,state:l,user_id:t.user_id}),c}async function TA(e,t,n,r){const i=await e.env.data.loginSessions.get(t,n.id);if(!i){console.warn(`Login session ${n.id} not found when trying to mark as failed`);return}const s=i.state||We.PENDING,{state:a,context:c}=ji(s,{type:Pr.FAIL,reason:r});a!==s&&await e.env.data.loginSessions.update(t,n.id,{state:a,failure_reason:c.failureReason})}async function fl(e,t,n,r){const i=await e.env.data.loginSessions.get(t,n.id);if(!i){console.warn(`Login session ${n.id} not found when trying to start hook`);return}const s=i.state||We.PENDING,{state:a,context:c}=ji(s,{type:Pr.START_HOOK,hookId:r});a!==s&&await e.env.data.loginSessions.update(t,n.id,{state:a,state_data:c.hookId?JSON.stringify({hookId:c.hookId}):void 0})}async function Oh(e,t,n){const r=await e.env.data.loginSessions.get(t,n.id);if(!r){console.warn(`Login session ${n.id} not found when trying to complete hook`);return}const i=r.state||We.PENDING,{state:s}=ji(i,{type:Pr.COMPLETE_HOOK});s!==i&&await e.env.data.loginSessions.update(t,n.id,{state:s,state_data:void 0})}async function Hm(e,t,n){const r=await e.env.data.loginSessions.get(t,n.id);if(!r){console.warn(`Login session ${n.id} not found when trying to mark as completed`);return}const i=r.state||We.PENDING,{state:s}=ji(i,{type:Pr.COMPLETE});s!==i&&await e.env.data.loginSessions.update(t,n.id,{state:s})}async function yu(e,t,n,r,i){const s=await e.env.data.loginSessions.get(t,n.id);if(!s){console.warn(`Login session ${n.id} not found when trying to start continuation`);return}const a=s.state||We.PENDING,{state:c}=ji(a,{type:Pr.START_CONTINUATION,scope:r});c!==a?await e.env.data.loginSessions.update(t,n.id,{state:c,state_data:JSON.stringify({continuationScope:r,continuationReturnUrl:i})}):console.warn(`Failed to start continuation for login session ${n.id}: cannot transition from ${a} to AWAITING_CONTINUATION. Scope: ${JSON.stringify(r)}, Return URL: ${jA(i)}`)}async function PA(e,t,n){const r=await e.env.data.loginSessions.get(t,n.id);if(!r){console.warn(`Login session ${n.id} not found when trying to complete continuation`);return}let i;if(r.state_data)try{i=JSON.parse(r.state_data).continuationReturnUrl}catch{}const s=r.state||We.PENDING,{state:a}=ji(s,{type:Pr.COMPLETE_CONTINUATION});return a!==s?await e.env.data.loginSessions.update(t,n.id,{state:a,state_data:void 0}):console.warn(`completeLoginSessionContinuation: State transition from ${s} with COMPLETE_CONTINUATION was invalid or no-op`),i}function OA(e){if(!e.state_data)return null;try{return JSON.parse(e.state_data).continuationScope||null}catch{return null}}function RA(e,t){if(e.state!==We.AWAITING_CONTINUATION)return!1;const n=OA(e);return n?n.includes(t):!1}async function gt(e,t){const{authParams:n,client:r,ticketAuth:i}=t;let{user:s}=t;const a=n.response_type||ot.CODE,c=n.response_mode||pn.QUERY;if(i){if(!t.loginSession)throw new W(500,{message:"Login session not found for ticket auth."});s&&!t.skipHooks&&(t.authStrategy&&s.app_metadata?.strategy!==t.authStrategy.strategy&&(s.app_metadata={...s.app_metadata,strategy:t.authStrategy.strategy},await e.env.data.users.update(r.tenant.id,s.user_id,{app_metadata:{...s.app_metadata||{},strategy:t.authStrategy.strategy}})),await v2(e,e.env.data,r.tenant.id,s,t.loginSession,{client:r,authParams:n,authStrategy:t.authStrategy}));const h=gz(),_=Oe(12),g=await e.env.data.codes.create(r.tenant.id,{code_id:Oe(32),code_type:"ticket",login_id:t.loginSession.id,expires_at:new Date(Date.now()+$z).toISOString(),code_verifier:[_,h].join("|"),redirect_uri:n.redirect_uri,state:n.state,nonce:n.nonce});return e.json({login_ticket:g.code_id,co_verifier:h,co_id:_})}let l=t.refreshToken,u;if(t.loginSession){const h=await e.env.data.loginSessions.get(r.tenant.id,t.loginSession.id);if(!h)throw new W(500,{message:"Login session not found."});const _=h.state||We.PENDING;if(_===We.COMPLETED)throw new W(400,{error:"invalid_request",error_description:"Login session has already been completed"});if(_===We.FAILED)throw new W(400,{error:"access_denied",error_description:`Login session failed: ${h.failure_reason||"unknown reason"}`});if(_===We.EXPIRED)throw new W(400,{error:"invalid_request",error_description:"Login session has expired"});if(_===We.PENDING)u=await NA(e,{user:s,client:r,loginSession:t.loginSession,existingSessionId:t.existingSessionIdToLink});else if(u=h.session_id,!u)throw new W(500,{message:`Login session in ${_} state but has no session_id`})}else throw new W(500,{message:"loginSession must be provided for front-channel auth responses."});if(!l&&n.scope?.split(" ").includes("offline_access")&&![ot.TOKEN,ot.CODE].includes(a)&&!t.impersonatingUser&&(l=(await b2(e,{user:s,client:r,session_id:u,scope:n.scope,audience:n.audience})).id),c===pn.SAML_POST){if(!u)throw new I(500,{message:"Session ID not available for SAML response"});return e9(e,t.client,t.authParams,s,u)}const d=await LA(e,{authParams:n,user:s,client:r,session_id:u,refresh_token:l,authStrategy:t.authStrategy,loginSession:t.loginSession,responseType:a,skipHooks:t.skipHooks,organization:t.organization,impersonatingUser:t.impersonatingUser});if(d instanceof Response)return d;if(c===pn.WEB_MESSAGE){if(!n.redirect_uri)throw new W(400,{message:"Redirect URI not allowed for WEB_MESSAGE response mode."});const h=new Headers;u?sl(r.tenant.id,u,e.var.host||"").forEach(m=>{h.append("set-cookie",m)}):console.warn("Session ID not available for WEB_MESSAGE, cookie will not be set.");const _=new URL(n.redirect_uri),g=`${_.protocol}//${_.host}`;return _f(e,g,JSON.stringify({...d,state:n.state}),h)}if(!n.redirect_uri)throw new W(400,{message:"Redirect uri not found for this response mode."});const f=new Headers;u&&sl(r.tenant.id,u,e.var.custom_domain||e.req.header("host")||"").forEach(_=>{f.append("set-cookie",_)});const p=new URL(n.redirect_uri);if("code"in d)p.searchParams.set("code",d.code),d.state&&p.searchParams.set("state",d.state);else if("access_token"in d)p.hash=new URLSearchParams({access_token:d.access_token,...d.id_token&&{id_token:d.id_token},token_type:d.token_type,expires_in:d.expires_in.toString(),...n.state&&{state:n.state},...n.scope&&{scope:n.scope}}).toString();else throw new W(500,{message:"Invalid token response for implicit flow."});return f.set("location",p.toString()),new Response("Redirecting",{status:302,headers:f})}async function LA(e,t){let{user:n}=t;const r=t.responseType||ot.TOKEN;if(n&&t.organization&&!(await e.env.data.userOrganizations.list(t.client.tenant.id,{q:`user_id:${n.user_id}`,per_page:1e3})).userOrganizations.some(u=>u.organization_id===t.organization.id))throw new W(403,{error:"access_denied",error_description:"User is not a member of the specified organization"});let i=t.authParams.scope||"",s=[];if(t.authParams.audience)try{let c;if(t.grantType===an.ClientCredential||!n&&!t.user)c=await Ys(e,{grantType:an.ClientCredential,tenantId:t.client.tenant.id,clientId:t.client.client_id,audience:t.authParams.audience,requestedScopes:t.authParams.scope?.split(" ")||[],organizationId:t.organization?.id});else{const l=n?.user_id||t.user?.user_id;if(!l)throw new W(400,{error:"invalid_request",error_description:"User ID is required for user-based grants"});c=await Ys(e,{grantType:t.grantType,tenantId:t.client.tenant.id,userId:l,clientId:t.client.client_id,audience:t.authParams.audience,requestedScopes:t.authParams.scope?.split(" ")||[],organizationId:t.organization?.id})}i=c.scopes.join(" "),s=c.permissions}catch(c){if(c instanceof I)throw c}const a={...t.authParams,scope:i};if(t.loginSession&&n&&!t.skipHooks){t.authStrategy&&n.app_metadata?.strategy!==t.authStrategy.strategy&&(n.app_metadata={...n.app_metadata,strategy:t.authStrategy.strategy},await e.env.data.users.update(t.client.tenant.id,n.user_id,{app_metadata:{...n.app_metadata||{},strategy:t.authStrategy.strategy}}));const c=await v2(e,e.env.data,t.client.tenant.id,n,t.loginSession,{client:t.client,authParams:a,authStrategy:t.authStrategy});if(c instanceof Response)return c;n=c}if(r===ot.CODE){if(!n||!t.loginSession)throw new W(500,{message:"User and loginSession is required for code flow"});const c=await y2(e,{user:n,client:t.client,authParams:a,login_id:t.loginSession.id});return await Hm(e,t.client.tenant.id,t.loginSession),c}else{const c=await gu(e,{...t,user:n,authParams:a,permissions:s});return t.loginSession&&await Hm(e,t.client.tenant.id,t.loginSession),c}}const Vm="auth-service";async function bu(e,t,n,r){const i=await e.env.data.tenants.get(t);if(!i)throw new Error(`Tenant not found: ${t}`);const s={client_id:Vm,tenant:i,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),name:"Auth Service",global:!1,is_first_party:!0,oidc_conformant:!1,auth0_conformant:!0,sso:!1,sso_disabled:!1,cross_origin_authentication:!1,custom_login_page_on:!1,require_pushed_authorization_requests:!1,require_proof_of_possession:!1,client_metadata:{disable_sign_ups:"false",email_validation:"disabled"},disable_sign_ups:!1,email_validation:"disabled",connections:[]},a=await gu(e,{client:s,authParams:{client_id:Vm,response_type:ot.TOKEN,scope:n}});return{access_token:a.access_token,token_type:a.token_type,expires_in:r||3600}}async function vu(e,t,n){const r=await bu(e,n.tenant_id,"webhook");for await(const i of t.filter(s=>"url"in s)){let s,a;try{const c=await fetch(i.url,{method:"POST",headers:{Authorization:`Bearer ${r.access_token}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(a=c.status,!c.ok){try{s=await c.text()}catch{}fe(e,n.tenant_id,{type:ue.FAILED_HOOK,description:`Failed to invoke hook ${i.hook_id} - ${c.status} ${c.statusText}`,userId:n.user?.user_id,body:{trigger_id:n.trigger_id,hook_id:i.hook_id,hook_url:i.url,payload:n,response:{statusCode:a,body:s}},connection:n.user?.connection})}}catch(c){fe(e,n.tenant_id,{type:ue.FAILED_HOOK,description:`Failed to invoke hook ${i.hook_id} - ${c instanceof Error?c.message:"Unknown error"}`,userId:n.user?.user_id,body:{trigger_id:n.trigger_id,hook_id:i.hook_id,hook_url:i.url,payload:n,error:c instanceof Error?c.message:String(c)},connection:n.user?.connection})}}}function DA(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t);return await vu(e,r,{tenant_id:t,user:n,trigger_id:"post-user-registration"}),n}}function UA(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t,{q:"trigger_id:pre-user-registration",page:0,per_page:100,include_totals:!1});await vu(e,r,{tenant_id:t,email:n,trigger_id:"pre-user-registration"})}}async function BA(e,t){const{hooks:n}=await e.env.data.hooks.list(t,{q:"trigger_id:validate-registration-username",page:0,per_page:1,include_totals:!1});return n.find(r=>"url"in r&&r.enabled)||null}function MA(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t,{q:"trigger_id:pre-user-deletion",page:0,per_page:100,include_totals:!1});return await vu(e,r,{tenant_id:t,user:n,trigger_id:"pre-user-deletion"}),n}}function qA(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t,{q:"trigger_id:post-user-deletion",page:0,per_page:100,include_totals:!1});return await vu(e,r,{tenant_id:t,user:n,trigger_id:"post-user-deletion"}),n}}function wu(e){return e.ISSUER}function _t(e){return e.UNIVERSAL_LOGIN_URL||`${e.ISSUER}u/`}function Le(e){return e.OAUTH_API_URL||e.ISSUER}o.z.object({...Qr.shape,tenant:el,connections:o.z.array(_r)});async function He(e,t,n){let r,i=n;if(!i){const p=await e.data.clients.getByClientId(t);if(!p)throw new W(403,{message:"Client not found"});const{tenant_id:h,..._}=p;r=_,i=h}const[s,a,c,l]=await Promise.all([r?Promise.resolve(r):e.data.clients.get(i,t),e.data.tenants.get(i),e.data.clientConnections.listByClient(i,t),e.data.connections.list(i)]),u=r||s;if(!u)throw new W(403,{message:"Client not found"});if(!a)throw new W(404,{message:"Tenant not found"});const d=c.length>0?c:l.connections||[],f=_t(e);return{...u,web_origins:[...u.web_origins||[],`${f}login`],allowed_logout_urls:[...u.allowed_logout_urls||[],e.ISSUER],callbacks:[...u.callbacks||[],`${f}info`],tenant:a,connections:d}}function Km(e){return typeof e.form_id=="string"}function yo(e,t){const n=e.match(/^\{\{context\.user\.(.+)\}\}$/);if(n&&n[1])return Gm(t.user,n[1]);const r=e.match(/^\{\{user\.(.+)\}\}$/);if(r&&r[1])return Gm(t.user,r[1]);const i=e.match(/^\{\{\$form\.(.+)\}\}$/);if(i&&i[1]&&t.submittedFields){const s=t.submittedFields[i[1]];return s!==void 0?String(s):void 0}return e}function Gm(e,t){const n=t.split(".");let r=e;for(const i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return;return typeof r=="string"?r:r==null?void 0:String(r)}function FA(e,t){const n={};for(const[r,i]of Object.entries(e))if(typeof i=="string"){const s=yo(i,t);s!==void 0&&(n[r]=s)}else i!=null&&(n[r]=String(i));return n}function Wm(e,t){const n=e.operator?.toLowerCase(),r=e.field?yo(e.field,t):"",i=e.value||"";switch(n){case"exists":return r!=null&&r!=="";case"not_exists":return r==null||r==="";case"ends_with":return typeof r=="string"&&r.endsWith(i);case"starts_with":return typeof r=="string"&&r.startsWith(i);case"contains":return typeof r=="string"&&r.includes(i);case"not_contains":return typeof r!="string"||!r.includes(i);case"equals":case"eq":return r===i;case"not_equals":case"neq":return r!==i;default:if(e.operands&&Array.isArray(e.operands)){for(const s of e.operands)if(s.operator==="ENDS_WITH"&&Array.isArray(s.operands)&&s.operands.length>=2){const a=s.operands[0],c=s.operands[1];if(a&&c){const l=yo(`{{context.user.${a}}}`,t);if(typeof l=="string"&&l.endsWith(c))return!0}}}return!1}}function HA(e,t){return e.type==="and"&&Array.isArray(e.conditions)?e.conditions.every(n=>Wm(n,t)):Wm(e,t)}function ku(e,t){const n={};for(const[r,i]of Object.entries(e))if(r.startsWith("user_metadata.")||r.startsWith("metadata.")){const s=r.startsWith("user_metadata.")?r.slice(14):r.slice(9),a=t.user_metadata||{};n.user_metadata={...a,...n.user_metadata||{},[s]:i}}else if(r.startsWith("address.")){const s=r.slice(8),a=t.address||{};n.address={...a,...n.address||{},[s]:i}}else n[r]=i;return n}function $u(e){const t=new Map;for(const n of e){const r=t.get(n.user_id);r?r.changes={...r.changes,...n.changes}:t.set(n.user_id,{user_id:n.user_id,changes:{...n.changes}})}return Array.from(t.values())}function xu(e,t,n){switch(e){case"change-email":return`/u/account/change-email?state=${encodeURIComponent(n)}`;case"account":return`/u/account?state=${encodeURIComponent(n)}`;case"custom":if(!t)throw new I(400,{message:"Custom URL is required for custom redirect target"});const r=new URL(t,"http://placeholder");return r.searchParams.set("state",n),r.pathname+r.search;default:throw new I(400,{message:`Unknown redirect target: ${e}`})}}async function Su(e,t,n,r,i=10){let s=t,a=0;const c=[];for(;a<i;){if(s==="$ending")return{type:"end",userUpdates:c.length>0?c:void 0};const l=e.find(u=>u.id===s);if(!l)return null;if(l.type==="STEP")return{type:"step",nodeId:l.id,userUpdates:c.length>0?c:void 0};if(l.type==="ACTION"){const u=l;if(u.config.action_type==="REDIRECT")return{type:"redirect",target:u.config.target,customUrl:u.config.custom_url,userUpdates:c.length>0?c:void 0};s=u.config.next_node,a++;continue}if(l.type==="ROUTER"){const u=l;let d=null;for(const f of u.config.rules)if(HA(f.condition,n)){d=f.next_node;break}if(d||(d=u.config.fallback),!d)return null;s=d,a++;continue}if(l.type==="FLOW"){const u=l;if(r&&u.config.flow_id){const d=await r(u.config.flow_id);if(d&&d.actions&&d.actions.length>0)for(const f of d.actions){if(f.type==="REDIRECT"&&f.action==="REDIRECT_USER"){const p=f.params?.target;if(p)return{type:"redirect",target:p,customUrl:f.params?.custom_url,userUpdates:c.length>0?c:void 0}}if(f.type==="AUTH0"&&f.action==="UPDATE_USER"&&f.params){const p=f.params.user_id&&yo(f.params.user_id,n)||n.user.user_id,h=f.params.changes?FA(f.params.changes,n):{};Object.keys(h).length>0&&c.push({user_id:p,changes:h})}}}if(u.config.next_node){s=u.config.next_node,a++;continue}return{type:"end",userUpdates:c.length>0?c:void 0}}return null}return null}async function VA(e,t,n,r,i){const s=e.env.data,a=e.var.tenant_id||e.req.header("tenant-id");if(!a)throw new I(400,{message:"Missing tenant_id in context"});const c=i?.client_metadata?.universal_login_version==="2"?"/u2":"/u",l=await s.forms.get(a,t);if(!l)throw new I(404,{message:"Form not found for post-user-login hook"});let u=l.start?.next_node;if(!u&&l.nodes&&l.nodes.length>0&&(u=l.nodes.find(p=>p.type==="STEP")?.id),!u)throw new I(400,{message:"No start node found in form"});if(r&&l.nodes){const f=async h=>{const _=await s.flows.get(a,h);return _?{actions:_.actions?.map(g=>({type:g.type,action:g.action,params:"params"in g&&g.params?g.params:void 0}))}:null},p=await Su(l.nodes,u,{user:r},f);if(p&&p.userUpdates&&p.userUpdates.length>0){const h=$u(p.userUpdates);for(const _ of h){const g=ku(_.changes,r);await s.users.update(a,_.user_id,g)}}if(!p||p.type==="end")return r;if(p.type==="redirect"){const h=p.target,_=xu(h,p.customUrl,n.id);if(h==="change-email"||h==="account"){const g=`${c}/continue?state=${encodeURIComponent(n.id)}`;await yu(e,a,n,[h],g)}else await fl(e,a,n,`form:${t}`);return new Response(null,{status:302,headers:{location:_}})}u=p.nodeId}await fl(e,a,n,`form:${t}`);let d=`${c}/forms/${l.id}/nodes/${u}?state=${encodeURIComponent(n.id)}`;return new Response(null,{status:302,headers:{location:d}})}function Jm(e){return typeof e.page_id=="string"&&typeof e.enabled=="boolean"}async function KA(e,t,n,r,i){const s=e.env.data,a=e.var.tenant_id||e.req.header("tenant-id");if(!a)throw new I(400,{message:"Missing tenant_id in context"});if(i&&!(await s.userPermissions.list(a,r.user_id)).some(f=>f.permission_name===i))return r;await fl(e,a,n,`page:${t}`);let c="/u";if(n.authParams.client_id)try{(await He(e.env,n.authParams.client_id,a))?.client_metadata?.universal_login_version==="2"&&(c="/u2")}catch{}let l=`${c}/${t}?state=${encodeURIComponent(n.id)}`;return new Response(null,{status:302,headers:{location:l}})}function pi(e,t){return{createServiceToken:async n=>(await bu(e,t,n.scope,n.expiresInSeconds)).access_token}}function Zm(e){return typeof e.url=="string"}function GA(e,t){return async(n,r)=>{if(e.var.client_id){const a=await He(e.env,e.var.client_id,e.var.tenant_id);r.email&&await JA(e,a,t,r.email)}const i={method:e.req.method,ip:e.req.query("x-real-ip")||"",user_agent:e.req.query("user-agent"),url:e.var.loginSession?.authorization_url||e.req.url};if(e.env.hooks?.onExecutePreUserRegistration)try{await e.env.hooks.onExecutePreUserRegistration({ctx:e,user:r,request:i},{user:{setUserMetadata:async(a,c)=>{r[a]=c},setLinkedTo:a=>{r.linked_to=a}},token:pi(e,n)})}catch{fe(e,n,{type:ue.FAILED_SIGNUP,description:"Pre user registration hook failed"})}let s=await ez(t)(n,r);if(e.env.hooks?.onExecutePostUserRegistration)try{await e.env.hooks.onExecutePostUserRegistration({ctx:e,user:r,request:i},{user:{},token:pi(e,n)})}catch{fe(e,n,{type:ue.FAILED_SIGNUP,description:"Post user registration hook failed"})}return await DA(e)(n,s),s}}function WA(e,t){return async(n,r,i)=>{if(Object.keys(i).length===1&&"linked_to"in i)return t.users.update(n,r,i);const s=await t.users.get(n,r);if(!s)throw new W(404,{message:"User not found"});const a={method:e.req.method,ip:e.var.ip||e.get("ip")||"",user_agent:e.var.useragent||e.get("useragent")||"",url:e.req.url};if(e.env.hooks?.onExecutePreUserUpdate)try{await e.env.hooks.onExecutePreUserUpdate({ctx:e,tenant:{id:n},user_id:r,user:s,updates:i,request:a},{user:{setUserMetadata:async(c,l)=>{i[c]=l}},cancel:()=>{throw new W(400,{message:"User update cancelled by pre-update hook"})},token:pi(e,n)})}catch(c){throw fe(e,n,{type:ue.ACTIONS_EXECUTION_FAILED,description:`Pre user update hook failed: ${c instanceof Error?c.message:"Unknown error"}`,userId:r}),new W(400,{message:"Pre user update hook failed"})}if(await t.users.update(n,r,i),i.email||i.email_verified){const c=await t.users.get(n,r);if(c&&c.email&&c.email_verified){const{users:l}=await t.users.list(n,{page:0,per_page:10,include_totals:!1,q:`email:${c.email}`}),u=l.filter(d=>d.email_verified&&d.user_id!==r&&!d.linked_to);u.length>0&&await t.users.update(n,r,{linked_to:u[0].user_id})}}return i.email&&fe(e,n,{type:ue.SUCCESS_CHANGE_EMAIL,description:`Email updated to ${i.email}`,userId:r}),!0}}async function zu(e,t,n,r,i="email"){if(t.client_metadata?.disable_sign_ups==="true"){const a=e.var.loginSession?.authorization_url;if(a&&new URL(a).searchParams.get("screen_hint")==="signup")return{allowed:!0};if(!await Uo({userAdapter:n.users,tenant_id:t.tenant.id,email:r}))return{allowed:!1,reason:"User account does not exist"}}if(e.env.hooks?.onExecuteValidateRegistrationUsername){const a={method:e.req.method,ip:e.var.ip||e.get("ip")||"",user_agent:e.var.useragent||e.get("useragent")||"",url:e.req.url};let c=!1,l;try{if(await e.env.hooks.onExecuteValidateRegistrationUsername({ctx:e,client:t,request:a,tenant:{id:t.tenant.id},user:{email:r,connection:i}},{deny:u=>{c=!0,l=u},token:pi(e,t.tenant.id)}),c)return{allowed:!1,reason:l}}catch{return{allowed:!1,reason:"Signup validation hook failed"}}}const s=await BA(e,t.tenant.id);if(s&&"url"in s)try{const a=await bu(e,t.tenant.id,"webhook"),c=await fetch(s.url,{method:"POST",headers:{Authorization:`Bearer ${a.access_token}`,"Content-Type":"application/json"},body:JSON.stringify({tenant_id:t.tenant.id,email:r,connection:i,client_id:t.client_id,trigger_id:"validate-registration-username"})});if(!c.ok)return{allowed:!1,reason:await c.text()||"Signup not allowed by webhook"};const l=await c.json();if(l.allowed===!1)return{allowed:!1,reason:l.reason||"Signup not allowed by webhook"}}catch{fe(e,t.tenant.id,{type:ue.FAILED_HOOK,description:"Validate signup email webhook failed"})}return{allowed:!0}}async function JA(e,t,n,r){const i=await zu(e,t,n,r);if(!i.allowed)throw fe(e,t.tenant.id,{type:ue.FAILED_SIGNUP,description:i.reason||"Signup not allowed"}),new W(400,{message:i.reason||"Signups are disabled for this client"});await UA(e)(t.tenant.id,r)}function ZA(e,t){return async(n,r)=>{const i=await t.users.get(n,r);if(!i)return!1;const s={method:e.req.method,ip:e.var.ip||e.get("ip")||"",user_agent:e.var.useragent||e.get("useragent")||"",url:e.req.url};if(e.env.hooks?.onExecutePreUserDeletion)try{await e.env.hooks.onExecutePreUserDeletion({ctx:e,user:i,user_id:r,request:s,tenant:{id:n}},{cancel:()=>{throw new W(400,{message:"User deletion cancelled by pre-deletion hook"})},token:pi(e,n)})}catch(l){throw l instanceof I?l:(fe(e,n,{type:ue.FAILED_HOOK,description:`Pre user deletion hook failed: ${l instanceof Error?l.message:String(l)}`}),new W(400,{message:"Pre user deletion hook failed"}))}try{await MA(e)(n,i)}catch(l){throw fe(e,n,{type:ue.FAILED_HOOK,description:`Pre user deletion webhook failed: ${l instanceof Error?l.message:String(l)}`}),new W(400,{message:"Pre user deletion webhook failed"})}const a=await t.users.list(n,{q:`linked_to:${r}`});for(const l of a.users){const[u,...d]=l.user_id.split("|");u&&await t.users.unlink(n,r,u,d.join("|"))}const c=await t.users.remove(n,r);if(c){fe(e,n,{type:ue.SUCCESS_USER_DELETION,description:`Deleted user: ${i.email||r}`,userId:r,strategy:i.provider||"auth0",strategy_type:i.is_social?"social":"database",connection:i.connection||"",body:{tenant:n,connection:i.connection||""}});try{await qA(e)(n,i)}catch(l){fe(e,n,{type:ue.FAILED_HOOK,description:`Post user deletion webhook failed: ${l instanceof Error?l.message:String(l)}`})}}if(c&&e.env.hooks?.onExecutePostUserDeletion)try{await e.env.hooks.onExecutePostUserDeletion({ctx:e,user:i,user_id:r,request:s,tenant:{id:n}},{token:pi(e,n)})}catch(l){fe(e,n,{type:ue.FAILED_HOOK,description:`Post user deletion hook failed: ${l instanceof Error?l.message:String(l)}`})}return c}}function Do(e,t){const n=t;return{...t,users:{...t.users,create:GA(e,n),update:WA(e,n),remove:ZA(e,n)}}}async function XA(e,t,n,r,i,s){let a=[];try{a=(await t.userRoles.list(n,r.user_id,void 0,"")).map(p=>p.name||p.id)}catch(d){console.error("Error fetching user roles:",d)}let c={};if(r.connection)try{const f=(await t.connections.list(n,{page:0,per_page:100,include_totals:!1})).connections.find(p=>p.name===r.connection);f&&(c={id:f.id,name:f.name,strategy:f.strategy||r.provider,metadata:f.options||{}})}catch(d){console.error("Error fetching connection info:",d)}let l;try{if(i.authParams?.organization){const d=await t.organizations.get(n,i.authParams.organization);d&&(l={id:d.id,name:d.name,display_name:d.display_name||d.name,metadata:d.metadata||{}})}}catch(d){console.error("Error fetching organization info:",d)}const u=e.get("countryCode");return{ctx:e,client:s.client,user:r,request:{asn:void 0,ip:e.get("ip")||"",user_agent:e.get("useragent"),method:e.req.method,url:e.req.url,geoip:{cityName:void 0,continentCode:void 0,countryCode:u||void 0,countryName:void 0,latitude:void 0,longitude:void 0,timeZone:void 0}},transaction:{id:i.id,locale:i.authParams?.ui_locales||"en",login_hint:void 0,prompt:i.authParams?.prompt,redirect_uri:i.authParams?.redirect_uri,requested_scopes:i.authParams?.scope?.split(" ")||[],response_mode:i.authParams?.response_mode,response_type:i.authParams?.response_type,state:i.authParams?.state,ui_locales:i.authParams?.ui_locales},scope:s.authParams?.scope||"",grant_type:s.authParams?.grant_type||"",audience:s.authParams?.audience,authentication:{methods:[{name:r.is_social?"federated":"pwd",timestamp:new Date().toISOString()}]},authorization:{roles:a},connection:Object.keys(c).length>0?c:{id:r.connection||"Username-Password-Authentication",name:r.connection||"Username-Password-Authentication",strategy:r.provider||"auth0"},organization:l,resource_server:s.authParams?.audience?{identifier:s.authParams.audience}:void 0,stats:{logins_count:r.login_count||0},tenant:{id:n},session:{id:i.id,created_at:i.created_at,authenticated_at:new Date().toISOString(),clients:[{client_id:s.client.client_id}],device:{initial_ip:e.get("ip"),initial_user_agent:e.get("useragent"),last_ip:r.last_ip||e.get("ip"),last_user_agent:e.get("useragent")}}}}async function v2(e,t,n,r,i,s){const a=s?.authStrategy?.strategy_type?s.authStrategy.strategy_type:r.is_social?"social":"database",c=s?.authStrategy?.strategy||r.connection||"";if(fe(e,n,{type:ue.SUCCESS_LOGIN,description:`Successful login for ${r.user_id}`,userId:r.user_id,strategy_type:a,strategy:c,connection:c,audience:s?.authParams?.audience,scope:s?.authParams?.scope}),await t.users.update(n,r.user_id,{last_login:new Date().toISOString(),last_ip:e.var.ip||"",login_count:r.login_count+1}),e.env.hooks?.onExecutePostLogin&&s?.client&&s?.authParams&&i){let f=null;const p=await XA(e,t,n,r,i,{client:s.client,authParams:s.authParams});if(await e.env.hooks.onExecutePostLogin(p,{prompt:{render:h=>{}},redirect:{sendUserTo:(h,_)=>{const g=new URL(h,e.req.url);g.searchParams.set("state",i.id),_?.query&&Object.entries(_.query).forEach(([y,m])=>{g.searchParams.set(y,m)}),f=g.toString()},encodeToken:h=>JSON.stringify({payload:h.payload,exp:Date.now()+(h.expiresInSeconds||900)*1e3}),validateToken:h=>null},token:pi(e,n)}),f)return await fl(e,n,i,"onExecutePostLogin"),new Response(null,{status:302,headers:{location:f}})}const{hooks:l}=await t.hooks.list(n,{q:"trigger_id:post-user-login",page:0,per_page:100,include_totals:!1});if(i){const f=l.find(h=>h.enabled&&Km(h));if(f&&Km(f))return VA(e,f.form_id,i,r,s?.client);const p=l.find(h=>h.enabled&&Jm(h));if(p&&Jm(p))return KA(e,p.page_id,i,r,p.permission_required)}const u=l.filter(f=>f.enabled&&al(f));for(const f of u)if(al(f))try{r=await a9(e,f.template_id,r)}catch{fe(e,n,{type:ue.FAILED_HOOK,description:`Failed to execute template hook: ${f.template_id}`})}const d=l.filter(f=>f.enabled&&Zm(f));for(const f of d)if(Zm(f))try{await fetch(f.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tenant_id:n,user:r,trigger_id:"post-user-login"})})}catch{fe(e,n,{type:ue.FAILED_HOOK,description:`Failed to invoke post-user-login webhook: ${f.url}`})}return r}function YA(e){return Do(e,e.env.data)}async function Rh(e,t,n){return(await e.list(t,{page:0,per_page:10,include_totals:!1,q:`email:${n}`})).users}async function Or({userAdapter:e,tenant_id:t,username:n,provider:r}){let i;r==="sms"?i=`phone_number:${n}`:n.includes("@")?i=`email:${n}`:i=`username:${n}`;const{users:s}=await e.list(t,{page:0,per_page:10,include_totals:!1,q:`${i} provider:${r}`});return s.length>1&&console.error("More than one user found for same username and provider"),s[0]||null}async function Uo({userAdapter:e,tenant_id:t,email:n}){const{users:r}=await e.list(t,{page:0,per_page:10,include_totals:!1,q:`email:${n}`});if(r.length===0)return;const i=r.filter(a=>!a.linked_to);if(i.length>0)return i.length>1&&console.error("More than one primary user found for same email"),i[0];const s=await e.get(t,r[0]?.linked_to);if(!s)throw new Error("Primary account not found");return s}async function Xn({userAdapter:e,tenant_id:t,username:n,provider:r}){const i=await Or({userAdapter:e,tenant_id:t,username:n,provider:r});return i?i.linked_to?e.get(t,i.linked_to):i:null}async function Au(e,t){const{username:n,provider:r,connection:i,client:s,userId:a,isSocial:c,profileData:l={},ip:u=""}=t;let d=await Xn({userAdapter:e.env.data.users,tenant_id:t.client.tenant.id,username:n,provider:r});if(!d){const f={user_id:`${r}|${a||Ii()}`,email:i!=="sms"&&n.includes("@")?n:void 0,phone_number:i==="sms"?n:void 0,username:!n.includes("@")&&i!=="sms"?n:void 0,name:n,provider:r,connection:i,email_verified:!0,last_ip:u,is_social:c,last_login:new Date().toISOString(),profileData:JSON.stringify(l)};d=await YA(e).users.create(s.tenant.id,f),e.set("user_id",d.user_id)}return d}const rt=o.z.object({page:o.z.string().min(0).optional().default("0").transform(e=>parseInt(e,10)).openapi({description:"Page index of the results to return. First page is 0."}),per_page:o.z.string().min(1).optional().default("10").transform(e=>parseInt(e,10)).openapi({description:"Number of results per page. Defaults to 50."}),include_totals:o.z.string().optional().default("false").transform(e=>e==="true").openapi({description:"Return results inside an object that contains the total result count (true) or as a direct array of results (false, default)."}),from:o.z.string().optional().openapi({description:"Optional Id from which to start selection."}),take:o.z.string().optional().transform(e=>e?parseInt(e,10):void 0).openapi({description:"Number of results per page. Defaults to 50."}),sort:o.z.string().regex(/^.+:(-1|1)$/).optional().openapi({description:"Field to sort by. Use field:order where order is 1 for ascending and -1 for descending. e.g. created_at:1."}),q:o.z.string().optional().openapi({description:"A lucene query string used to filter the results"})});function ft(e){if(!e)return;const[t,n]=e.split(":"),r=n==="1"?"asc":"desc";if(!(!t||!r))return{sort_by:t,sort_order:r}}const w2={},QA=Object.freeze(Object.defineProperty({__proto__:null,default:w2},Symbol.toStringTag,{value:"Module"}));var $f=null;function eE(e){try{return crypto.getRandomValues(new Uint8Array(e))}catch{}try{return w2.randomBytes(e)}catch{}if(!$f)throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative");return $f(e)}function tE(e){$f=e}function Lh(e,t){if(e=e||Dh,typeof e!="number")throw Error("Illegal arguments: "+typeof e+", "+typeof t);e<4?e=4:e>31&&(e=31);var n=[];return n.push("$2b$"),e<10&&n.push("0"),n.push(e.toString()),n.push("$"),n.push(hl(eE(ea),ea)),n.join("")}function k2(e,t,n){if(typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof e>"u")e=Dh;else if(typeof e!="number")throw Error("illegal arguments: "+typeof e);function r(i){cn(function(){try{i(null,Lh(e))}catch(s){i(s)}})}if(n){if(typeof n!="function")throw Error("Illegal callback: "+typeof n);r(n)}else return new Promise(function(i,s){r(function(a,c){if(a){s(a);return}i(c)})})}function $2(e,t){if(typeof t>"u"&&(t=Dh),typeof t=="number"&&(t=Lh(t)),typeof e!="string"||typeof t!="string")throw Error("Illegal arguments: "+typeof e+", "+typeof t);return xf(e,t)}function x2(e,t,n,r){function i(s){typeof e=="string"&&typeof t=="number"?k2(t,function(a,c){xf(e,c,s,r)}):typeof e=="string"&&typeof t=="string"?xf(e,t,s,r):cn(s.bind(this,Error("Illegal arguments: "+typeof e+", "+typeof t)))}if(n){if(typeof n!="function")throw Error("Illegal callback: "+typeof n);i(n)}else return new Promise(function(s,a){i(function(c,l){if(c){a(c);return}s(l)})})}function S2(e,t){for(var n=e.length^t.length,r=0;r<e.length;++r)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function nE(e,t){if(typeof e!="string"||typeof t!="string")throw Error("Illegal arguments: "+typeof e+", "+typeof t);return t.length!==60?!1:S2($2(e,t.substring(0,t.length-31)),t)}function rE(e,t,n,r){function i(s){if(typeof e!="string"||typeof t!="string"){cn(s.bind(this,Error("Illegal arguments: "+typeof e+", "+typeof t)));return}if(t.length!==60){cn(s.bind(this,null,!1));return}x2(e,t.substring(0,29),function(a,c){a?s(a):s(null,S2(c,t))},r)}if(n){if(typeof n!="function")throw Error("Illegal callback: "+typeof n);i(n)}else return new Promise(function(s,a){i(function(c,l){if(c){a(c);return}s(l)})})}function iE(e){if(typeof e!="string")throw Error("Illegal arguments: "+typeof e);return parseInt(e.split("$")[2],10)}function oE(e){if(typeof e!="string")throw Error("Illegal arguments: "+typeof e);if(e.length!==60)throw Error("Illegal hash length: "+e.length+" != 60");return e.substring(0,29)}function sE(e){if(typeof e!="string")throw Error("Illegal arguments: "+typeof e);return z2(e)>72}var cn=typeof setImmediate=="function"?setImmediate:typeof scheduler=="object"&&typeof scheduler.postTask=="function"?scheduler.postTask.bind(scheduler):setTimeout;function z2(e){for(var t=0,n=0,r=0;r<e.length;++r)n=e.charCodeAt(r),n<128?t+=1:n<2048?t+=2:(n&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320?(++r,t+=4):t+=3;return t}function aE(e){for(var t=0,n,r,i=new Array(z2(e)),s=0,a=e.length;s<a;++s)n=e.charCodeAt(s),n<128?i[t++]=n:n<2048?(i[t++]=n>>6|192,i[t++]=n&63|128):(n&64512)===55296&&((r=e.charCodeAt(s+1))&64512)===56320?(n=65536+((n&1023)<<10)+(r&1023),++s,i[t++]=n>>18|240,i[t++]=n>>12&63|128,i[t++]=n>>6&63|128,i[t++]=n&63|128):(i[t++]=n>>12|224,i[t++]=n>>6&63|128,i[t++]=n&63|128);return i}var Mi="./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),lr=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,54,55,56,57,58,59,60,61,62,63,-1,-1,-1,-1,-1,-1,-1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,-1,-1,-1,-1,-1,-1,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,-1,-1,-1,-1,-1];function hl(e,t){var n=0,r=[],i,s;if(t<=0||t>e.length)throw Error("Illegal len: "+t);for(;n<t;){if(i=e[n++]&255,r.push(Mi[i>>2&63]),i=(i&3)<<4,n>=t){r.push(Mi[i&63]);break}if(s=e[n++]&255,i|=s>>4&15,r.push(Mi[i&63]),i=(s&15)<<2,n>=t){r.push(Mi[i&63]);break}s=e[n++]&255,i|=s>>6&3,r.push(Mi[i&63]),r.push(Mi[s&63])}return r.join("")}function A2(e,t){var n=0,r=e.length,i=0,s=[],a,c,l,u,d,f;if(t<=0)throw Error("Illegal len: "+t);for(;n<r-1&&i<t&&(f=e.charCodeAt(n++),a=f<lr.length?lr[f]:-1,f=e.charCodeAt(n++),c=f<lr.length?lr[f]:-1,!(a==-1||c==-1||(d=a<<2>>>0,d|=(c&48)>>4,s.push(String.fromCharCode(d)),++i>=t||n>=r)||(f=e.charCodeAt(n++),l=f<lr.length?lr[f]:-1,l==-1)||(d=(c&15)<<4>>>0,d|=(l&60)>>2,s.push(String.fromCharCode(d)),++i>=t||n>=r)));)f=e.charCodeAt(n++),u=f<lr.length?lr[f]:-1,d=(l&3)<<6>>>0,d|=u,s.push(String.fromCharCode(d)),++i;var p=[];for(n=0;n<i;n++)p.push(s[n].charCodeAt(0));return p}var ea=16,Dh=10,cE=16,lE=100,Xm=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],Ym=[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946,1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055,3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504,976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462],E2=[1332899944,1700884034,1701343084,1684370003,1668446532,1869963892];function ta(e,t,n,r){var i,s=e[t],a=e[t+1];return s^=n[0],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[1],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[2],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[3],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[4],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[5],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[6],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[7],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[8],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[9],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[10],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[11],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[12],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[13],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[14],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[15],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[16],e[t]=a^n[cE+1],e[t+1]=s,e}function Ki(e,t){for(var n=0,r=0;n<4;++n)r=r<<8|e[t]&255,t=(t+1)%e.length;return{key:r,offp:t}}function Qm(e,t,n){for(var r=0,i=[0,0],s=t.length,a=n.length,c,l=0;l<s;l++)c=Ki(e,r),r=c.offp,t[l]=t[l]^c.key;for(l=0;l<s;l+=2)i=ta(i,0,t,n),t[l]=i[0],t[l+1]=i[1];for(l=0;l<a;l+=2)i=ta(i,0,t,n),n[l]=i[0],n[l+1]=i[1]}function uE(e,t,n,r){for(var i=0,s=[0,0],a=n.length,c=r.length,l,u=0;u<a;u++)l=Ki(t,i),i=l.offp,n[u]=n[u]^l.key;for(i=0,u=0;u<a;u+=2)l=Ki(e,i),i=l.offp,s[0]^=l.key,l=Ki(e,i),i=l.offp,s[1]^=l.key,s=ta(s,0,n,r),n[u]=s[0],n[u+1]=s[1];for(u=0;u<c;u+=2)l=Ki(e,i),i=l.offp,s[0]^=l.key,l=Ki(e,i),i=l.offp,s[1]^=l.key,s=ta(s,0,n,r),r[u]=s[0],r[u+1]=s[1]}function eg(e,t,n,r,i){var s=E2.slice(),a=s.length,c;if(n<4||n>31)if(c=Error("Illegal number of rounds (4-31): "+n),r){cn(r.bind(this,c));return}else throw c;if(t.length!==ea)if(c=Error("Illegal salt length: "+t.length+" != "+ea),r){cn(r.bind(this,c));return}else throw c;n=1<<n>>>0;var l,u,d=0,f;typeof Int32Array=="function"?(l=new Int32Array(Xm),u=new Int32Array(Ym)):(l=Xm.slice(),u=Ym.slice()),uE(t,e,l,u);function p(){if(i&&i(d/n),d<n)for(var _=Date.now();d<n&&(d=d+1,Qm(e,l,u),Qm(t,l,u),!(Date.now()-_>lE)););else{for(d=0;d<64;d++)for(f=0;f<a>>1;f++)ta(s,f<<1,l,u);var g=[];for(d=0;d<a;d++)g.push((s[d]>>24&255)>>>0),g.push((s[d]>>16&255)>>>0),g.push((s[d]>>8&255)>>>0),g.push((s[d]&255)>>>0);if(r){r(null,g);return}else return g}r&&cn(p)}if(typeof r<"u")p();else for(var h;;)if(typeof(h=p())<"u")return h||[]}function xf(e,t,n,r){var i;if(typeof e!="string"||typeof t!="string")if(i=Error("Invalid string / salt: Not a string"),n){cn(n.bind(this,i));return}else throw i;var s,a;if(t.charAt(0)!=="$"||t.charAt(1)!=="2")if(i=Error("Invalid salt version: "+t.substring(0,2)),n){cn(n.bind(this,i));return}else throw i;if(t.charAt(2)==="$")s="\0",a=3;else{if(s=t.charAt(2),s!=="a"&&s!=="b"&&s!=="y"||t.charAt(3)!=="$")if(i=Error("Invalid salt revision: "+t.substring(2,4)),n){cn(n.bind(this,i));return}else throw i;a=4}if(t.charAt(a+2)>"$")if(i=Error("Missing salt rounds"),n){cn(n.bind(this,i));return}else throw i;var c=parseInt(t.substring(a,a+1),10)*10,l=parseInt(t.substring(a+1,a+2),10),u=c+l,d=t.substring(a+3,a+25);e+=s>="a"?"\0":"";var f=aE(e),p=A2(d,ea);function h(_){var g=[];return g.push("$2"),s>="a"&&g.push(s),g.push("$"),u<10&&g.push("0"),g.push(u.toString()),g.push("$"),g.push(hl(p,p.length)),g.push(hl(_,E2.length*4-1)),g.join("")}if(typeof n>"u")return h(eg(f,p,u));eg(f,p,u,function(_,g){_?n(_,null):n(null,h(g))},r)}function dE(e,t){return hl(e,t)}function pE(e,t){return A2(e,t)}const Bo={setRandomFallback:tE,genSaltSync:Lh,genSalt:k2,hashSync:$2,hash:x2,compareSync:nE,compare:rE,getRounds:iE,getSalt:oE,truncates:sE,encodeBase64:dE,decodeBase64:pE},ur={TOO_SHORT:"password_too_short",MISSING_LOWERCASE:"password_missing_lowercase",MISSING_UPPERCASE:"password_missing_uppercase",MISSING_NUMBER:"password_missing_number",MISSING_SPECIAL:"password_missing_special",REUSED:"password_reused",CONTAINS_PERSONAL_INFO:"password_contains_personal_info",CONTAINS_FORBIDDEN_WORD:"password_contains_forbidden_word"};class Sn extends Error{code;params;constructor(t,n,r){super(n),this.code=t,this.params=r,this.name="PasswordPolicyError"}}async function Ea(e,t){const{newPassword:n,userData:r,data:i,tenantId:s,userId:a}=t,c=e.passwordPolicy!==void 0||e.password_complexity_options!==void 0||e.password_history!==void 0||e.password_no_personal_info!==void 0||e.password_dictionary!==void 0,l=c?e.passwordPolicy:"good",u=c?e.password_complexity_options?.min_length:8;if(u&&n.length<u)throw new Sn(ur.TOO_SHORT,`Password must be at least ${u} characters`,{minLength:u});if(l&&l!=="none"&&l==="good"){if(!/[a-z]/.test(n))throw new Sn(ur.MISSING_LOWERCASE,"Password must contain at least one lowercase letter");if(!/[A-Z]/.test(n))throw new Sn(ur.MISSING_UPPERCASE,"Password must contain at least one uppercase letter");if(!/\d/.test(n))throw new Sn(ur.MISSING_NUMBER,"Password must contain at least one number");if(!/[^A-Za-z0-9]/.test(n))throw new Sn(ur.MISSING_SPECIAL,"Password must contain at least one special character")}if(e.password_history?.enable){const d=e.password_history.size||5,f=await i.passwords.list(s,a,d);for(const p of f)if(await Bo.compare(n,p.password))throw new Sn(ur.REUSED,"Password was used recently and cannot be reused",{historySize:d})}if(e.password_no_personal_info?.enable&&r&&[r.email,r.name].filter(Boolean).join(" ").toLowerCase().includes(n.toLowerCase()))throw new Sn(ur.CONTAINS_PERSONAL_INFO,"Password cannot contain personal information like your name or email");if(e.password_dictionary?.enable&&e.password_dictionary.dictionary&&e.password_dictionary.dictionary.some(d=>n.toLowerCase().includes(d.toLowerCase())))throw new Sn(ur.CONTAINS_FORBIDDEN_WORD,"Password contains a forbidden word")}async function Ca(e,t,n){const{connections:r}=await e.connections.list(t,{page:0,per_page:100});return r.find(s=>s.name===n)?.options||{}}async function na(e){return{hash:await Bo.hash(e,10),algorithm:"bcrypt"}}var tg;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(tg||(tg={}));var ng;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(ng||(ng={}));function fE(e){return C2(e,hE,ra.Include)}function Uh(e){return C2(e,_E,ra.None)}function C2(e,t,n){let r="";for(let i=0;i<e.byteLength;i+=3){let s=0,a=0;for(let c=0;c<3&&i+c<e.byteLength;c++)s=s<<8|e[i+c],a+=8;for(let c=0;c<4;c++)a>=6?(r+=t[s>>a-6&63],a-=6):a>0?(r+=t[s<<6-a&63],a=0):n===ra.Include&&(r+="=")}return r}const hE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var ra;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(ra||(ra={}));var rg;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(rg||(rg={}));class mE{uint8(t,n){if(t.byteLength<n+1)throw new TypeError("Insufficient bytes");return t[n]}uint16(t,n){if(t.byteLength<n+2)throw new TypeError("Insufficient bytes");return t[n]<<8|t[n+1]}uint32(t,n){if(t.byteLength<n+4)throw new TypeError("Insufficient bytes");let r=0;for(let i=0;i<4;i++)r|=t[n+i]<<24-i*8;return r}uint64(t,n){if(t.byteLength<n+8)throw new TypeError("Insufficient bytes");let r=0n;for(let i=0;i<8;i++)r|=BigInt(t[n+i])<<BigInt(56-i*8);return r}putUint8(t,n,r){if(t.length<r+1)throw new TypeError("Not enough space");if(n<0||n>255)throw new TypeError("Invalid uint8 value");t[r]=n}putUint16(t,n,r){if(t.length<r+2)throw new TypeError("Not enough space");if(n<0||n>65535)throw new TypeError("Invalid uint16 value");t[r]=n>>8,t[r+1]=n&255}putUint32(t,n,r){if(t.length<r+4)throw new TypeError("Not enough space");if(n<0||n>4294967295)throw new TypeError("Invalid uint32 value");for(let i=0;i<4;i++)t[r+i]=n>>(3-i)*8&255}putUint64(t,n,r){if(t.length<r+8)throw new TypeError("Not enough space");if(n<0||n>18446744073709551615n)throw new TypeError("Invalid uint64 value");for(let i=0;i<8;i++)t[r+i]=Number(n>>BigInt((7-i)*8)&0xffn)}}const ig=new mE;function vn(e,t){return(e<<32-t|e>>>t)>>>0}function gE(e){const t=new yE;return t.update(e),t.digest()}class yE{blockSize=64;size=32;blocks=new Uint8Array(64);currentBlockSize=0;H=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);l=0n;w=new Uint32Array(64);update(t){if(this.l+=BigInt(t.byteLength)*8n,this.currentBlockSize+t.byteLength<64){this.blocks.set(t,this.currentBlockSize),this.currentBlockSize+=t.byteLength;return}let n=0;if(this.currentBlockSize>0){const r=t.slice(0,64-this.currentBlockSize);this.blocks.set(r,this.currentBlockSize),this.process(),n+=r.byteLength,this.currentBlockSize=0}for(;n+64<=t.byteLength;){const r=t.slice(n,n+64);this.blocks.set(r),this.process(),n+=64}if(t.byteLength-n>0){const r=t.slice(n);this.blocks.set(r),this.currentBlockSize=r.byteLength}}digest(){this.blocks[this.currentBlockSize]=128,this.currentBlockSize+=1,64-this.currentBlockSize<8&&(this.blocks.fill(0,this.currentBlockSize),this.process(),this.currentBlockSize=0),this.blocks.fill(0,this.currentBlockSize),ig.putUint64(this.blocks,this.l,this.blockSize-8),this.process();const t=new Uint8Array(32);for(let n=0;n<8;n++)ig.putUint32(t,this.H[n],n*4);return t}process(){for(let u=0;u<16;u++)this.w[u]=(this.blocks[u*4]<<24|this.blocks[u*4+1]<<16|this.blocks[u*4+2]<<8|this.blocks[u*4+3])>>>0;for(let u=16;u<64;u++){const d=(vn(this.w[u-2],17)^vn(this.w[u-2],19)^this.w[u-2]>>>10)>>>0,f=(vn(this.w[u-15],7)^vn(this.w[u-15],18)^this.w[u-15]>>>3)>>>0;this.w[u]=d+this.w[u-7]+f+this.w[u-16]|0}let t=this.H[0],n=this.H[1],r=this.H[2],i=this.H[3],s=this.H[4],a=this.H[5],c=this.H[6],l=this.H[7];for(let u=0;u<64;u++){const d=(vn(s,6)^vn(s,11)^vn(s,25))>>>0,f=(s&a^~s&c)>>>0,p=l+d+f+bE[u]+this.w[u]|0,h=(vn(t,2)^vn(t,13)^vn(t,22))>>>0,_=(t&n^t&r^n&r)>>>0,g=h+_|0;l=c,c=a,a=s,s=i+p|0,i=r,r=n,n=t,t=p+g|0}this.H[0]=t+this.H[0]|0,this.H[1]=n+this.H[1]|0,this.H[2]=r+this.H[2]|0,this.H[3]=i+this.H[3]|0,this.H[4]=s+this.H[4]|0,this.H[5]=a+this.H[5]|0,this.H[6]=c+this.H[6]|0,this.H[7]=l+this.H[7]|0}}const bE=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);new BigUint64Array([0x428a2f98d728ae22n,0x7137449123ef65cdn,0xb5c0fbcfec4d3b2fn,0xe9b5dba58189dbbcn,0x3956c25bf348b538n,0x59f111f1b605d019n,0x923f82a4af194f9bn,0xab1c5ed5da6d8118n,0xd807aa98a3030242n,0x12835b0145706fben,0x243185be4ee4b28cn,0x550c7dc3d5ffb4e2n,0x72be5d74f27b896fn,0x80deb1fe3b1696b1n,0x9bdc06a725c71235n,0xc19bf174cf692694n,0xe49b69c19ef14ad2n,0xefbe4786384f25e3n,0x0fc19dc68b8cd5b5n,0x240ca1cc77ac9c65n,0x2de92c6f592b0275n,0x4a7484aa6ea6e483n,0x5cb0a9dcbd41fbd4n,0x76f988da831153b5n,0x983e5152ee66dfabn,0xa831c66d2db43210n,0xb00327c898fb213fn,0xbf597fc7beef0ee4n,0xc6e00bf33da88fc2n,0xd5a79147930aa725n,0x06ca6351e003826fn,0x142929670a0e6e70n,0x27b70a8546d22ffcn,0x2e1b21385c26c926n,0x4d2c6dfc5ac42aedn,0x53380d139d95b3dfn,0x650a73548baf63den,0x766a0abb3c77b2a8n,0x81c2c92e47edaee6n,0x92722c851482353bn,0xa2bfe8a14cf10364n,0xa81a664bbc423001n,0xc24b8b70d0f89791n,0xc76c51a30654be30n,0xd192e819d6ef5218n,0xd69906245565a910n,0xf40e35855771202an,0x106aa07032bbd1b8n,0x19a4c116b8d2d0c8n,0x1e376c085141ab53n,0x2748774cdf8eeb99n,0x34b0bcb5e19b48a8n,0x391c0cb3c5c95a63n,0x4ed8aa4ae3418acbn,0x5b9cca4f7763e373n,0x682e6ff3d6b2b8a3n,0x748f82ee5defb2fcn,0x78a5636f43172f60n,0x84c87814a1f0ab72n,0x8cc702081a6439ecn,0x90befffa23631e28n,0xa4506cebde82bde9n,0xbef9a3f7b2c67915n,0xc67178f2e372532bn,0xca273eceea26619cn,0xd186b8c721c0c207n,0xeada7dd6cde0eb1en,0xf57d4f7fee6ed178n,0x06f067aa72176fban,0x0a637dc5a2c898a6n,0x113f9804bef90daen,0x1b710b35131c471bn,0x28db77f523047d84n,0x32caab7b40c72493n,0x3c9ebe0a15c9bebcn,0x431d67c49c100d4cn,0x4cc5d4becb3e42b6n,0x597f299cfc657e2an,0x5fcb6fab3ad6faecn,0x6c44198c4a475817n]);class I2{data;constructor(t){this.data=t}tokenType(){if("token_type"in this.data&&typeof this.data.token_type=="string")return this.data.token_type;throw new Error("Missing or invalid 'token_type' field")}accessToken(){if("access_token"in this.data&&typeof this.data.access_token=="string")return this.data.access_token;throw new Error("Missing or invalid 'access_token' field")}accessTokenExpiresInSeconds(){if("expires_in"in this.data&&typeof this.data.expires_in=="number")return this.data.expires_in;throw new Error("Missing or invalid 'expires_in' field")}accessTokenExpiresAt(){return new Date(Date.now()+this.accessTokenExpiresInSeconds()*1e3)}hasRefreshToken(){return"refresh_token"in this.data&&typeof this.data.refresh_token=="string"}refreshToken(){if("refresh_token"in this.data&&typeof this.data.refresh_token=="string")return this.data.refresh_token;throw new Error("Missing or invalid 'refresh_token' field")}hasScopes(){return"scope"in this.data&&typeof this.data.scope=="string"}scopes(){if("scope"in this.data&&typeof this.data.scope=="string")return this.data.scope.split(" ");throw new Error("Missing or invalid 'scope' field")}idToken(){if("id_token"in this.data&&typeof this.data.id_token=="string")return this.data.id_token;throw new Error("Missing or invalid field 'id_token'")}}function j2(e){const t=gE(new TextEncoder().encode(e));return Uh(t)}function Eu(){const e=new Uint8Array(32);return crypto.getRandomValues(e),Uh(e)}function N2(){const e=new Uint8Array(32);return crypto.getRandomValues(e),Uh(e)}function vE(e,t){if(t.length!==1)throw new TypeError("Invalid character string");let n=0;for(;n<e.length&&e[n]===t;)n++;return e.slice(n)}function og(e,t){if(t.length!==1)throw new TypeError("Invalid character string");let n=e.length;for(;n>0&&e[n-1]===t;)n--;return e.slice(0,n)}function sg(e,...t){let n=og(e,"/");for(const r of t)n=og(n,"/")+"/"+vE(r,"/");return n}function Zn(e,t){const n=new TextEncoder().encode(t.toString()),r=new Request(e,{method:"POST",body:n});return r.headers.set("Content-Type","application/x-www-form-urlencoded"),r.headers.set("Accept","application/json"),r.headers.set("User-Agent","arctic"),r.headers.set("Content-Length",n.byteLength.toString()),r}function si(e,t){const n=new TextEncoder().encode(`${e}:${t}`);return fE(n)}async function bo(e){let t;try{t=await fetch(e)}catch(n){throw new Mh(n)}if(t.status===400||t.status===401){let n;try{n=await t.json()}catch{throw new co(t.status)}if(typeof n!="object"||n===null)throw new kr(t.status,n);let r;try{r=Bh(n)}catch{throw new kr(t.status,n)}throw r}if(t.status===200){let n;try{n=await t.json()}catch{throw new co(t.status)}if(typeof n!="object"||n===null)throw new kr(t.status,n);return new I2(n)}throw t.body!==null&&await t.body.cancel(),new co(t.status)}async function wE(e){let t;try{t=await fetch(e)}catch(n){throw new Mh(n)}if(t.status===400||t.status===401){let n;try{n=await t.json()}catch{throw new kr(t.status,null)}if(typeof n!="object"||n===null)throw new kr(t.status,n);let r;try{r=Bh(n)}catch{throw new kr(t.status,n)}throw r}if(t.status===200){t.body!==null&&await t.body.cancel();return}throw t.body!==null&&await t.body.cancel(),new co(t.status)}function Bh(e){let t;if("error"in e&&typeof e.error=="string")t=e.error;else throw new Error("Invalid error response");let n=null,r=null,i=null;if("error_description"in e){if(typeof e.error_description!="string")throw new Error("Invalid data");n=e.error_description}if("error_uri"in e){if(typeof e.error_uri!="string")throw new Error("Invalid data");r=e.error_uri}if("state"in e){if(typeof e.state!="string")throw new Error("Invalid data");i=e.state}return new kE(t,n,r,i)}class Mh extends Error{constructor(t){super("Failed to send request",{cause:t})}}class kE extends Error{code;description;uri;state;constructor(t,n,r,i){super(`OAuth request error: ${t}`),this.code=t,this.description=n,this.uri=r,this.state=i}}class co extends Error{status;constructor(t){super("Unexpected error response"),this.status=t}}class kr extends Error{status;data;constructor(t,n){super("Unexpected error response body"),this.status=t,this.data=n}}class Ni{clientId;clientPassword;redirectURI;constructor(t,n,r){this.clientId=t,this.clientPassword=n,this.redirectURI=r}createAuthorizationURL(t,n,r){const i=new URL(t);return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",this.clientId),this.redirectURI!==null&&i.searchParams.set("redirect_uri",this.redirectURI),i.searchParams.set("state",n),r.length>0&&i.searchParams.set("scope",r.join(" ")),i}createAuthorizationURLWithPKCE(t,n,r,i,s){const a=new URL(t);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",this.clientId),this.redirectURI!==null&&a.searchParams.set("redirect_uri",this.redirectURI),a.searchParams.set("state",n),r===fi.S256){const c=j2(i);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",c)}else r===fi.Plain&&(a.searchParams.set("code_challenge_method","plain"),a.searchParams.set("code_challenge",i));return s.length>0&&a.searchParams.set("scope",s.join(" ")),a}async validateAuthorizationCode(t,n,r){const i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",n),this.redirectURI!==null&&i.set("redirect_uri",this.redirectURI),r!==null&&i.set("code_verifier",r),this.clientPassword===null&&i.set("client_id",this.clientId);const s=Zn(t,i);if(this.clientPassword!==null){const c=si(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await bo(s)}async refreshAccessToken(t,n,r){const i=new URLSearchParams;i.set("grant_type","refresh_token"),i.set("refresh_token",n),this.clientPassword===null&&i.set("client_id",this.clientId),r.length>0&&i.set("scope",r.join(" "));const s=Zn(t,i);if(this.clientPassword!==null){const c=si(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await bo(s)}async revokeToken(t,n){const r=new URLSearchParams;r.set("token",n),this.clientPassword===null&&r.set("client_id",this.clientId);const i=Zn(t,r);if(this.clientPassword!==null){const s=si(this.clientId,this.clientPassword);i.headers.set("Authorization",`Basic ${s}`)}await wE(i)}}var fi;(function(e){e[e.S256=0]="S256",e[e.Plain=1]="Plain"})(fi||(fi={}));var ag;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(ag||(ag={}));var cg;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(cg||(cg={}));function Us(e){return $E(e,xE,_l.None)}function $E(e,t,n){let r="";for(let i=0;i<e.byteLength;i+=3){let s=0,a=0;for(let c=0;c<3&&i+c<e.byteLength;c++)s=s<<8|e[i+c],a+=8;for(let c=0;c<4;c++)a>=6?(r+=t[s>>a-6&63],a-=6):a>0?(r+=t[s<<6-a&63],a=0):n===_l.Include&&(r+="=")}return r}const xE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var _l;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(_l||(_l={}));var lg;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(lg||(lg={}));function SE(e,t,n){const r=Us(new TextEncoder().encode(e)),i=Us(new TextEncoder().encode(t)),s=Us(n);return r+"."+i+"."+s}function zE(e,t){const n=Us(new TextEncoder().encode(e)),r=Us(new TextEncoder().encode(t)),i=n+"."+r;return new TextEncoder().encode(i)}const AE="https://appleid.apple.com/auth/authorize",EE="https://appleid.apple.com/auth/token";class T2{clientId;teamId;keyId;pkcs8PrivateKey;redirectURI;constructor(t,n,r,i,s){this.clientId=t,this.teamId=n,this.keyId=r,this.pkcs8PrivateKey=i,this.redirectURI=s}createAuthorizationURL(t,n){const r=new URL(AE);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",t),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(t){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId);const r=await this.createClientSecret();n.set("client_secret",r);const i=Zn(EE,n);return await bo(i)}async createClientSecret(){const t=await crypto.subtle.importKey("pkcs8",this.pkcs8PrivateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),n=Math.floor(Date.now()/1e3),r=JSON.stringify({typ:"JWT",alg:"ES256",kid:this.keyId}),i=JSON.stringify({iss:this.teamId,exp:n+300,aud:["https://appleid.apple.com"],sub:this.clientId,iat:n}),s=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},t,zE(r,i)));return SE(r,i,s)}}const CE="https://www.facebook.com/v16.0/dialog/oauth",IE="https://graph.facebook.com/v16.0/oauth/access_token";class P2{clientId;clientSecret;redirectURI;constructor(t,n,r){this.clientId=t,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(t,n){const r=new URL(CE);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",t),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(t){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId),n.set("client_secret",this.clientSecret);const r=Zn(IE,n);return await bo(r)}}const jE="https://github.com/login/oauth/authorize",ug="https://github.com/login/oauth/access_token";class O2{clientId;clientSecret;redirectURI;constructor(t,n,r){this.clientId=t,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(t,n){const r=new URL(jE);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",t),n.length>0&&r.searchParams.set("scope",n.join(" ")),this.redirectURI!==null&&r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(t){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t),this.redirectURI!==null&&n.set("redirect_uri",this.redirectURI);const r=Zn(ug,n),i=si(this.clientId,this.clientSecret);return r.headers.set("Authorization",`Basic ${i}`),await dg(r)}async refreshAccessToken(t){const n=new URLSearchParams;n.set("grant_type","refresh_token"),n.set("refresh_token",t);const r=Zn(ug,n),i=si(this.clientId,this.clientSecret);return r.headers.set("Authorization",`Basic ${i}`),await dg(r)}}async function dg(e){let t;try{t=await fetch(e)}catch(i){throw new Mh(i)}if(t.status!==200)throw t.body!==null&&await t.body.cancel(),new co(t.status);let n;try{n=await t.json()}catch{throw new co(t.status)}if(typeof n!="object"||n===null)throw new kr(t.status,n);if("error"in n&&typeof n.error=="string"){let i;try{i=Bh(n)}catch{throw new kr(t.status,n)}throw i}return new I2(n)}const NE="https://accounts.google.com/o/oauth2/v2/auth",pg="https://oauth2.googleapis.com/token",TE="https://oauth2.googleapis.com/revoke";let R2=class{client;constructor(t,n,r){this.client=new Ni(t,n,r)}createAuthorizationURL(t,n,r){return this.client.createAuthorizationURLWithPKCE(NE,t,fi.S256,n,r)}async validateAuthorizationCode(t,n){return await this.client.validateAuthorizationCode(pg,t,n)}async refreshAccessToken(t){return await this.client.refreshAccessToken(pg,t,[])}async revokeToken(t){await this.client.revokeToken(TE,t)}};class L2{authorizationEndpoint;tokenEndpoint;clientId;clientSecret;redirectURI;constructor(t,n,r,i){this.authorizationEndpoint=sg("https://login.microsoftonline.com",t,"/oauth2/v2.0/authorize"),this.tokenEndpoint=sg("https://login.microsoftonline.com",t,"/oauth2/v2.0/token"),this.clientId=n,this.clientSecret=r,this.redirectURI=i}createAuthorizationURL(t,n,r){const i=new URL(this.authorizationEndpoint);i.searchParams.set("response_type","code"),i.searchParams.set("client_id",this.clientId),i.searchParams.set("redirect_uri",this.redirectURI),i.searchParams.set("state",t);const s=j2(n);return i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("code_challenge",s),r.length>0&&i.searchParams.set("scope",r.join(" ")),i}async validateAuthorizationCode(t,n){const r=new URLSearchParams;r.set("grant_type","authorization_code"),r.set("code",t),r.set("redirect_uri",this.redirectURI),r.set("code_verifier",n),this.clientSecret===null&&r.set("client_id",this.clientId);const i=Zn(this.tokenEndpoint,r);if(this.clientSecret!==null){const a=si(this.clientId,this.clientSecret);i.headers.set("Authorization",`Basic ${a}`)}else i.headers.set("Origin","arctic");return await bo(i)}async refreshAccessToken(t,n){const r=new URLSearchParams;r.set("grant_type","refresh_token"),r.set("refresh_token",t),this.clientSecret===null&&r.set("client_id",this.clientId),n.length>0&&r.set("scope",n.join(" "));const i=Zn(this.tokenEndpoint,r);if(this.clientSecret!==null){const a=si(this.clientId,this.clientSecret);i.headers.set("Authorization",`Basic ${a}`)}else i.headers.set("Origin","arctic");return await bo(i)}}const Mo=o.z.object({iss:o.z.string().url(),sub:o.z.string(),aud:o.z.string(),exp:o.z.number(),email:o.z.string().optional(),given_name:o.z.string().optional(),family_name:o.z.string().optional(),name:o.z.string().optional(),iat:o.z.number(),auth_time:o.z.number().optional(),nonce:o.z.string().optional(),acr:o.z.string().optional(),amr:o.z.array(o.z.string()).optional(),azp:o.z.string().optional(),at_hash:o.z.string().optional(),c_hash:o.z.string().optional()}).passthrough();Mo.omit({iat:!0,auth_time:!0,nonce:!0,acr:!0,amr:!0,azp:!0,at_hash:!0,c_hash:!0});const PE="Apple",OE="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20fill%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M45%200H0V45H45V0Z%22%20fill%3D%22white%22%2F%3E%3Cpath%20d%3D%22M23.5344%2010.3846C25.5313%2010.3846%2028.0344%209.01144%2029.525%207.18055C30.875%205.5213%2031.8594%203.20407%2031.8594%200.886839C31.8594%200.572154%2031.8313%200.25747%2031.775%200C29.5531%200.0858233%2026.8813%201.51621%2025.2781%203.43293C24.0125%204.89193%2022.8594%207.18055%2022.8594%209.52638C22.8594%209.86968%2022.9156%2010.213%2022.9438%2010.3274C23.0844%2010.356%2023.3094%2010.3846%2023.5344%2010.3846ZM16.5031%2045C19.2313%2045%2020.4406%2043.1405%2023.8438%2043.1405C27.3031%2043.1405%2028.0625%2044.9428%2031.1%2044.9428C34.0813%2044.9428%2036.0781%2042.1392%2037.9625%2039.3929C40.0719%2036.246%2040.9438%2033.1564%2041%2033.0134C40.8031%2032.9561%2035.0938%2030.5817%2035.0938%2023.9161C35.0938%2018.1373%2039.5938%2015.534%2039.8469%2015.3338C36.8656%2010.9854%2032.3375%2010.8709%2031.1%2010.8709C27.7531%2010.8709%2025.025%2012.9307%2023.3094%2012.9307C21.4531%2012.9307%2019.0063%2010.9854%2016.1094%2010.9854C10.5969%2010.9854%205%2015.6198%205%2024.3738C5%2029.8093%207.08125%2035.5594%209.64063%2039.2784C11.8344%2042.4253%2013.7469%2045%2016.5031%2045Z%22%20fill%3D%22black%22%2F%3E%3C%2Fsvg%3E";function D2(e){const{options:t}=e;if(!t||!t.client_id||!t.team_id||!t.kid||!t.app_secret)throw new Error("Missing required Apple authentication parameters");const n=Buffer.from(t.app_secret,"utf-8"),r=n.toString().replace(/-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----|\s/g,""),i=Uint8Array.from(Buffer.from(r,"base64"));return n.fill(0),{options:t,keyArray:i}}async function RE(e,t){const{options:n,keyArray:r}=D2(t),i=`${Le(e.env)}callback`,s=new T2(n.client_id,n.team_id,n.kid,r,i),a=Oe(),c=await s.createAuthorizationURL(a,n.scope?.split(" ")||["name","email"]);return(n.scope?.split(" ")||["name","email"]).some(u=>["email","name"].includes(u))&&c.searchParams.set("response_mode","form_post"),{redirectUrl:c.href,code:a}}async function LE(e,t,n){const{options:r,keyArray:i}=D2(t),a=await new T2(r.client_id,r.team_id,r.kid,i,`${Le(e.env)}callback`).validateAuthorizationCode(n),c=za(a.idToken());if(!c)throw new Error("Invalid ID token");const l=Mo.parse(c.payload);return{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture,locale:l.locale}}const DE=Object.freeze(Object.defineProperty({__proto__:null,displayName:PE,getRedirect:RE,logoDataUri:OE,validateAuthorizationCodeAndGetUser:LE},Symbol.toStringTag,{value:"Module"})),UE="Facebook",BE="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M45%2022.5C45%2010.0736%2034.9264%200%2022.5%200C10.0736%200%200%2010.0736%200%2022.5C0%2033.7031%208.23242%2042.9785%2019.0039%2044.6953V28.9746H13.2861V22.5H19.0039V17.5391C19.0039%2011.8945%2022.3828%208.75977%2027.5391%208.75977C29.9658%208.75977%2032.5049%209.19922%2032.5049%209.19922V14.7656H29.7012C26.9414%2014.7656%2026.0156%2016.4824%2026.0156%2018.2432V22.5H32.2412L31.2012%2028.9746H26.0156V44.6953C36.7871%2042.9785%2045%2033.7031%2045%2022.5Z%22%20fill%3D%22%231877F2%22%2F%3E%3Cpath%20d%3D%22M31.2012%2028.9746L32.2412%2022.5H26.0156V18.2432C26.0156%2016.4824%2026.9414%2014.7656%2029.7012%2014.7656H32.5049V9.19922C32.5049%209.19922%2029.9658%208.75977%2027.5391%208.75977C22.3828%208.75977%2019.0039%2011.8945%2019.0039%2017.5391V22.5H13.2861V28.9746H19.0039V44.6953C20.1562%2044.8984%2021.3203%2045%2022.5%2045C23.6797%2045%2024.8438%2044.8984%2026.0156%2044.6953V28.9746H31.2012Z%22%20fill%3D%22white%22%2F%3E%3C%2Fsvg%3E";async function ME(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required authentication parameters");const r=`${Le(e.env)}callback`,i=new P2(n.client_id,n.client_secret,r),s=Oe();return{redirectUrl:i.createAuthorizationURL(s,n.scope?.split(" ")||["email"]).href,code:s}}async function qE(e,t,n){const{options:r}=t;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new P2(r.client_id,r.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode(n),a=await fetch("https://graph.facebook.com/v22.0/me?fields=id,email,name",{headers:{Authorization:`Bearer ${s.accessToken()}`}});if(!a.ok)throw new Error("Failed to fetch user info");const c=await a.json();return e.set("log",`Userinfo: ${JSON.stringify(c)}`),{sub:c.id,email:c.email,name:c.name}}const FE=Object.freeze(Object.defineProperty({__proto__:null,displayName:UE,getRedirect:ME,logoDataUri:BE,validateAuthorizationCodeAndGetUser:qE},Symbol.toStringTag,{value:"Module"})),HE="Google",VE=!0,KE="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M44.1035%2023.0123C44.1054%2021.4791%2043.9758%2019.9486%2043.716%2018.4375H22.498V27.1028H34.6507C34.4021%2028.4868%2033.8757%2029.8061%2033.1034%2030.9812C32.3311%2032.1562%2031.3289%2033.1628%2030.1571%2033.9401V39.5649H37.41C41.6567%2035.6494%2044.1035%2029.859%2044.1035%2023.0123Z%22%20fill%3D%22%234285F4%22%2F%3E%3Cpath%20d%3D%22M22.4982%2044.9997C28.5698%2044.9997%2033.6821%2043.0061%2037.4101%2039.5687L30.1573%2033.9439C28.1386%2035.3126%2025.5387%2036.0938%2022.4982%2036.0938C16.6296%2036.0938%2011.6485%2032.1377%209.86736%2026.8066H2.39575V32.6033C4.26839%2036.3297%207.13989%2039.4622%2010.6896%2041.6512C14.2394%2043.8402%2018.3277%2044.9995%2022.4982%2044.9997Z%22%20fill%3D%22%2334A853%22%2F%3E%3Cpath%20d%3D%22M9.86737%2026.8073C8.92572%2024.0138%208.92572%2020.9886%209.86737%2018.1951V12.3984H2.39576C0.820432%2015.5332%200%2018.9929%200%2022.5012C0%2026.0095%200.820432%2029.4692%202.39576%2032.604L9.86737%2026.8073Z%22%20fill%3D%22%23FBBC04%22%2F%3E%3Cpath%20d%3D%22M22.4982%208.90741C25.7068%208.85499%2028.8071%2010.0673%2031.1291%2012.2823L37.5507%205.86064C33.4788%202.03602%2028.0843%20-0.0637686%2022.4982%200.00147616C18.3277%200.00166623%2014.2394%201.16098%2010.6896%203.34999C7.13989%205.539%204.26839%208.67155%202.39575%2012.3979L9.86736%2018.1946C11.6485%2012.8635%2016.6296%208.90741%2022.4982%208.90741Z%22%20fill%3D%22%23EA4335%22%2F%3E%3C%2Fsvg%3E";async function GE(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required Google authentication parameters");const r=`${Le(e.env)}callback`,i=new R2(n.client_id,n.client_secret,r),s=Oe(),a=Eu();return{redirectUrl:i.createAuthorizationURL(s,a,n.scope?.split(" ")??["email","profile"]).href,code:s,codeVerifier:a}}async function WE(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.client_secret||!r)throw new Error("Missing required authentication parameters");const a=await new R2(i.client_id,i.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode(n,r),c=za(a.idToken());if(!c)throw new Error("Invalid ID token");const l=Mo.parse(c.payload);return{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture,locale:l.locale}}const JE=Object.freeze(Object.defineProperty({__proto__:null,disableEmbeddedBrowsers:VE,displayName:HE,getRedirect:GE,logoDataUri:KE,validateAuthorizationCodeAndGetUser:WE},Symbol.toStringTag,{value:"Module"})),ZE="Vipps",XE="data:image/svg+xml,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2048%2048%22%20width%3D%2245%22%20height%3D%2245%22%3E%3Cpath%20fill%3D%22%23FF5B24%22%20d%3D%22M3.5%2C8h41c1.9%2C0%2C3.5%2C1.6%2C3.5%2C3.5v25c0%2C1.9-1.6%2C3.5-3.5%2C3.5h-41C1.6%2C40%2C0%2C38.4%2C0%2C36.5v-25C0%2C9.6%2C1.6%2C8%2C3.5%2C8z%22%2F%3E%3Cpath%20fill-rule%3D%22evenodd%22%20clip-rule%3D%22evenodd%22%20fill%3D%22%23FFFFFF%22%20d%3D%22M27.9%2C20.3c1.4%2C0%2C2.6-1%2C2.6-2.5h0c0-1.5-1.2-2.5-2.6-2.5c-1.4%2C0-2.6%2C1-2.6%2C2.5C25.3%2C19.2%2C26.5%2C20.3%2C27.9%2C20.3z%20M31.2%2C24.4c-1.7%2C2.2-3.5%2C3.8-6.7%2C3.8h0c-3.2%2C0-5.8-2-7.7-4.8c-0.8-1.2-2-1.4-2.9-0.8c-0.8%2C0.6-1%2C1.8-0.3%2C2.9%20c2.7%2C4.1%2C6.5%2C6.6%2C10.9%2C6.6c4%2C0%2C7.2-2%2C9.6-5.2c0.9-1.2%2C0.9-2.5%2C0-3.1C33.3%2C22.9%2C32.1%2C23.2%2C31.2%2C24.4z%22%2F%3E%3C%2Fsvg%3E";async function YE(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required authentication parameters");const r=new Ni(n.client_id,n.client_secret,`${Le(e.env)}callback`),i=Oe(),s=r.createAuthorizationURL("https://api.vipps.no/access-management-1.0/access/oauth2/auth",i,n.scope?.split(" ")||["openid","email","phoneNumber","name","address","birthDate"]);return s.searchParams.set("response_type","code"),s.searchParams.set("response_mode","query"),{redirectUrl:s.href,code:i}}async function QE(e,t,n){const{options:r}=t;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new Ni(r.client_id,r.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode("https://api.vipps.no/access-management-1.0/access/oauth2/token",n,null),a=za(s.idToken());if(!a)throw new Error("Invalid ID token");const c=Mo.parse(a.payload);if(typeof c.msn!="string")throw new Error("msn not available in id token");const l=await fetch("https://api.vipps.no/vipps-userinfo-api/userinfo",{headers:{Authorization:`Bearer ${s.accessToken()}`,"Merchant-Serial-Number":c.msn}});if(!l.ok)throw new W(400,{message:"Failed to get user from vipps"});return await l.json()}const e7=Object.freeze(Object.defineProperty({__proto__:null,displayName:ZE,getRedirect:YE,logoDataUri:XE,validateAuthorizationCodeAndGetUser:QE},Symbol.toStringTag,{value:"Module"})),t7="GitHub",n7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill-rule%3D%22evenodd%22%20clip-rule%3D%22evenodd%22%20d%3D%22M22.5%200C10.074%200%200%2010.335%200%2023.077C0%2033.266%206.444%2041.895%2015.39%2044.955C16.515%2045.165%2016.935%2044.46%2016.935%2043.857C16.935%2043.32%2016.92%2041.865%2016.905%2039.99C10.65%2041.355%209.33%2036.99%209.33%2036.99C8.31%2034.32%206.825%2033.615%206.825%2033.615C4.77%2032.205%206.975%2032.235%206.975%2032.235C9.24%2032.385%2010.425%2034.59%2010.425%2034.59C12.45%2038.13%2015.75%2037.125%2017.01%2036.555C17.22%2035.07%2017.82%2034.065%2018.48%2033.51C13.455%2032.94%208.19%2030.93%208.19%2022.035C8.19%2019.5%209.075%2017.43%2010.47%2015.81C10.23%2015.24%209.435%2012.87%2010.695%209.66C10.695%209.66%2012.585%209.045%2016.875%2012.06C18.675%2011.565%2020.595%2011.31%2022.5%2011.31C24.405%2011.31%2026.325%2011.565%2028.125%2012.06C32.415%209.045%2034.305%209.66%2034.305%209.66C35.565%2012.87%2034.77%2015.24%2034.53%2015.81C35.925%2017.43%2036.81%2019.5%2036.81%2022.035C36.81%2030.96%2031.53%2032.925%2026.49%2033.48C27.33%2034.2%2028.095%2035.625%2028.095%2037.815C28.095%2040.95%2028.065%2043.47%2028.065%2043.857C28.065%2044.46%2028.485%2045.18%2029.625%2044.955C38.571%2041.88%2045%2033.252%2045%2023.077C45%2010.335%2034.926%200%2022.5%200Z%22%20fill%3D%22%23181717%22%2F%3E%3C%2Fsvg%3E";async function r7(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required GitHub authentication parameters");const r=`${Le(e.env)}callback`,i=new O2(n.client_id,n.client_secret,r),s=Oe();return{redirectUrl:i.createAuthorizationURL(s,n.scope?.split(" ")||["user:email"]).href,code:s}}async function i7(e,t,n){const{options:r}=t;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new O2(r.client_id,r.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode(n),a=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${s.accessToken()}`,"User-Agent":"AuthHero"}});if(!a.ok)throw new Error("Failed to fetch user info");const c=await a.json(),l=await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${s.accessToken()}`,"User-Agent":"AuthHero"}});let u=c.email;if(l.ok){const d=await l.json(),f=d.find(p=>p.primary&&p.verified)||d.find(p=>p.verified);f&&(u=f.email)}return e.set("log",`GitHub user: ${JSON.stringify(c)}`),{sub:c.id.toString(),email:u,name:c.name,given_name:c.name?.split(" ")[0],family_name:c.name?.split(" ").slice(1).join(" "),picture:c.avatar_url}}const o7=Object.freeze(Object.defineProperty({__proto__:null,displayName:t7,getRedirect:r7,logoDataUri:n7,validateAuthorizationCodeAndGetUser:i7},Symbol.toStringTag,{value:"Module"})),s7="Microsoft",a7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill%3D%22%23F25022%22%20d%3D%22M0%200H21.43V21.43H0V0Z%22%2F%3E%3Cpath%20fill%3D%22%237FBA00%22%20d%3D%22M23.57%200H45V21.43H23.57V0Z%22%2F%3E%3Cpath%20fill%3D%22%2300A4EF%22%20d%3D%22M0%2023.57H21.43V45H0V23.57Z%22%2F%3E%3Cpath%20fill%3D%22%23FFB900%22%20d%3D%22M23.57%2023.57H45V45H23.57V23.57Z%22%2F%3E%3C%2Fsvg%3E";async function c7(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required Microsoft authentication parameters");const r=`${Le(e.env)}callback`,i=n.realms||"common",s=new L2(i,n.client_id,n.client_secret,r),a=Oe(),c=Eu();return{redirectUrl:s.createAuthorizationURL(a,c,n.scope?.split(" ")||["openid","profile","email"]).href,code:a,codeVerifier:c}}async function l7(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.client_secret||!r)throw new Error("Missing required authentication parameters");const s=i.realms||"common",c=await new L2(s,i.client_id,i.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode(n,r),l=za(c.idToken());if(!l)throw new Error("Invalid ID token");const u=Mo.parse(l.payload);return e.set("log",`Microsoft user: ${JSON.stringify(u)}`),{sub:u.sub,email:u.email,given_name:u.given_name,family_name:u.family_name,name:u.name,picture:u.picture}}const u7=Object.freeze(Object.defineProperty({__proto__:null,displayName:s7,getRedirect:c7,logoDataUri:a7,validateAuthorizationCodeAndGetUser:l7},Symbol.toStringTag,{value:"Module"})),d7="OpenID Connect",p7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M22.5%200C10.074%200%200%2010.074%200%2022.5S10.074%2045%2022.5%2045%2045%2034.926%2045%2022.5%2034.926%200%2022.5%200zm0%2040.5c-9.941%200-18-8.059-18-18s8.059-18%2018-18%2018%208.059%2018%2018-8.059%2018-18%2018z%22%20fill%3D%22%23F7931E%22%2F%3E%3Cpath%20d%3D%22M22.5%209c-7.456%200-13.5%206.044-13.5%2013.5S15.044%2036%2022.5%2036%2036%2029.956%2036%2022.5%2029.956%209%2022.5%209zm0%2022.5c-4.971%200-9-4.029-9-9s4.029-9%209-9%209%204.029%209%209-4.029%209-9%209z%22%20fill%3D%22%23F7931E%22%2F%3E%3C%2Fsvg%3E";async function f7(e,t){const{options:n}=t;if(!n?.client_id||!n.authorization_endpoint)throw new Error("Missing required OIDC authentication parameters");const r=`${Le(e.env)}callback`,i=new Ni(n.client_id,n.client_secret||null,r),s=N2(),a=Eu(),c=n.scope?.split(" ")??["openid","profile","email"];return{redirectUrl:i.createAuthorizationURLWithPKCE(n.authorization_endpoint,s,fi.S256,a,c).href,code:s,codeVerifier:a}}async function h7(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.token_endpoint)throw new Error("Missing required authentication parameters");const s=`${Le(e.env)}callback`,c=await new Ni(i.client_id,i.client_secret||null,s).validateAuthorizationCode(i.token_endpoint,n,r||null);if(c.data.id_token){const u=za(c.idToken());if(u?.payload){const d=Mo.passthrough().parse(u.payload);return{sub:d.sub,email:d.email,given_name:d.given_name,family_name:d.family_name,name:d.name}}}if(i.userinfo_endpoint){const u=await fetch(i.userinfo_endpoint,{headers:{Authorization:`Bearer ${c.accessToken()}`}});if(!u.ok)throw new Error("Failed to fetch user info");const d=await u.json();if(!d.sub)throw new Error("Unable to get user identifier: userinfo response missing sub");return{sub:d.sub,email:d.email,given_name:d.given_name,family_name:d.family_name,name:d.name}}throw new Error("Unable to get user information: no ID token or userinfo endpoint")}const _7=Object.freeze(Object.defineProperty({__proto__:null,displayName:d7,getRedirect:f7,logoDataUri:p7,validateAuthorizationCodeAndGetUser:h7},Symbol.toStringTag,{value:"Module"})),m7="OAuth 2.0",g7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M22.5%200C14.492%200%208%206.492%208%2014.5V18H5v22h35V18h-3v-3.5C37%206.492%2030.508%200%2022.5%200zm0%204c5.799%200%2010.5%204.701%2010.5%2010.5V18h-21v-3.5C12%208.701%2016.701%204%2022.5%204z%22%20fill%3D%22%236B7280%22%2F%3E%3Ccircle%20cx%3D%2222.5%22%20cy%3D%2229%22%20r%3D%223%22%20fill%3D%22%236B7280%22%2F%3E%3C%2Fsvg%3E";async function y7(e,t){const{options:n}=t;if(!n?.client_id||!n.authorization_endpoint)throw new Error("Missing required OAuth2 authentication parameters");const r=`${Le(e.env)}callback`,i=new Ni(n.client_id,n.client_secret||null,r),s=N2(),a=Eu(),c=n.scope?.split(" ")??[];return{redirectUrl:i.createAuthorizationURLWithPKCE(n.authorization_endpoint,s,fi.S256,a,c).href,code:s,codeVerifier:a}}async function b7(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.token_endpoint)throw new Error("Missing required authentication parameters");const s=`${Le(e.env)}callback`,c=await new Ni(i.client_id,i.client_secret||null,s).validateAuthorizationCode(i.token_endpoint,n,r||null);if(!i.userinfo_endpoint)throw new Error("Missing userinfo_endpoint for OAuth2 provider");const l=await fetch(i.userinfo_endpoint,{headers:{Authorization:`Bearer ${c.accessToken()}`}});if(!l.ok)throw new Error("Failed to fetch user info");const u=await l.json(),d=u.sub||u.id||u.user_id;if(!d)throw new Error("Unable to get user identifier: response missing sub, id, or user_id");return{sub:d,email:u.email,given_name:u.given_name||u.first_name,family_name:u.family_name||u.last_name,name:u.name||`${u.given_name||u.first_name||""} ${u.family_name||u.last_name||""}`.trim()}}const v7=Object.freeze(Object.defineProperty({__proto__:null,displayName:m7,getRedirect:y7,logoDataUri:g7,validateAuthorizationCodeAndGetUser:b7},Symbol.toStringTag,{value:"Module"})),Cu={apple:DE,facebook:FE,"google-oauth2":JE,vipps:e7,github:o7,microsoft:u7,oidc:_7,oauth2:v7};function U2(e,t){const n=e.env.STRATEGIES||{},i={...Cu,...n}[t];if(!i)throw new Error(`Strategy ${t} not found`);return i}const w7=new Set(["oidc","samlp","waad","adfs","oauth2"]);function k7(e){return w7.has(e.strategy)?e.name:e.strategy}function B2(e){return e.options?.icon_url?e.options.icon_url:Cu[e.strategy]?.logoDataUri}const $7=["email","email_verified","phone_number","phone_verified","username"];function fg(e){const t={connection:e.connection,provider:e.provider,user_id:df(e.user_id),isSocial:e.is_social};for(const n of $7)e[n]!==void 0&&e[n]!==null&&(t[n]=e[n]);return t}const hg=It.extend({users:o.z.array(xn)}),x7=It.extend({sessions:o.z.array(du)}),S7=It.extend({organizations:o.z.array(mr)}),z7=new o.OpenAPIHono().openapi(o.createRoute({tags:["users"],method:"get",path:"/",request:{query:rt,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(xn),hg])}},description:"List of users"}}}),async e=>{const{page:t,per_page:n,include_totals:r,sort:i,q:s}=e.req.valid("query");if(s?.includes("identities.profileData.email")){const u=s.split("=")[1],f=(await e.env.data.users.list(e.var.tenant_id,{page:t,per_page:n,include_totals:r,q:`email:${u}`})).users.filter(_=>_.linked_to),[p]=f;if(!p)return e.json([]);const h=await e.env.data.users.get(e.var.tenant_id,p.linked_to);if(!h)throw new I(500,{message:"Primary account not found"});return e.json([xn.parse(h)])}const a=["-_exists_:linked_to"];s&&a.push(s);const c=await e.env.data.users.list(e.var.tenant_id,{page:t,per_page:n,include_totals:r,sort:ft(i),q:a.join(" ")}),l=c.users.filter(u=>!u.linked_to);return r?e.json(hg.parse({users:l,length:c.length,start:c.start,limit:c.limit})):e.json(o.z.array(xn).parse(l))}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:xn}},description:"List of users"}}}),async e=>{const{user_id:t}=e.req.valid("param"),n=await e.env.data.users.get(e.var.tenant_id,t);if(!n)throw new I(404);if(n.linked_to)throw new I(404,{message:"User is linked to another user"});return e.json(n)}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["delete:users","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{user_id:t}=e.req.valid("param");if(!await e.env.data.users.remove(e.var.tenant_id,t))throw new I(404);return await fe(e,e.var.tenant_id,{type:ue.SUCCESS_API_OPERATION,description:"Delete a User",response:{statusCode:204,body:{}}}),e.text("OK")}).openapi(o.createRoute({tags:["users"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({...Wc.shape,password:o.z.string().optional()})}}}},security:[{Bearer:["create:users","auth:write"]}],responses:{201:{content:{"application/json":{schema:xn}},description:"Status"}}}),async e=>{const t=e.req.valid("json");e.set("body",t);const{email:n,phone_number:r,name:i,linked_to:s,email_verified:a,provider:c,connection:l,password:u}=t,d=await e.env.data.connections.get(e.var.tenant_id,l),f=d?k7(d):c||l,p=t.user_id,h=p?df(p):Ii(),_=`${f}|${h}`;try{let g;u&&(g=await na(u));const y={email:n,user_id:_,name:i||n||r,phone_number:r,provider:f,connection:l,linked_to:s??void 0,email_verified:a||!1,last_ip:"",is_social:!1,last_login:new Date().toISOString(),...g&&{password:g}},m=await e.env.data.users.create(e.var.tenant_id,y);e.set("user_id",m.user_id),await fe(e,e.var.tenant_id,{type:ue.SUCCESS_API_OPERATION,description:"User created"});const v=m.identities?m:{...m,identities:[fg(m)]};return e.json(xn.parse(v),{status:201})}catch(g){throw g.message==="User already exists"?new I(409,{message:"User already exists"}):g}}).openapi(o.createRoute({tags:["users"],method:"patch",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({...Wc.shape,verify_email:o.z.boolean(),password:o.z.string()}).partial()}}},params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["update:users","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{data:t}=e.env,n=e.req.valid("json"),{user_id:r}=e.req.valid("param"),{verify_email:i,password:s,connection:a,...c}=n,l=await t.users.get(e.var.tenant_id,r);if(!l)throw new I(404);if(l.linked_to)throw new I(404,{message:"User is linked to another user"});let u=r,d=l;if(a)if(l.connection===a)u=r,d=l;else{const h=(await t.users.list(e.var.tenant_id,{page:0,per_page:100,include_totals:!1,q:`linked_to:${r}`})).users.find(_=>_.connection===a);if(!h)throw new I(404,{message:`No identity found with connection: ${a}`});u=h.user_id,d=h}if(c.email&&c.email!==d.email){const p=await Rh(e.env.data.users,e.var.tenant_id,c.email);if(p.length&&p.some(h=>h.user_id!==u))throw new I(409,{message:"Another user with the same email address already exists."})}if(await e.env.data.users.update(e.var.tenant_id,u,c),s){let p;if(a)if(a==="Username-Password-Authentication")p={provider:d.provider,user_id:df(u)};else throw new I(400,{message:`Cannot set password for connection: ${a}`});else if(p=l.identities?.find(m=>m.connection==="Username-Password-Authentication"),!p)throw new I(400,{message:"User does not have a password identity"});const h=`${p.provider}|${p.user_id}`,_=await t.passwords.get(e.var.tenant_id,h);_&&await t.passwords.update(e.var.tenant_id,{id:_.id,user_id:h,password:_.password,algorithm:_.algorithm,is_current:!1});const{hash:g,algorithm:y}=await na(s);await t.passwords.create(e.var.tenant_id,{user_id:h,password:g,algorithm:y,is_current:!0})}const f=await e.env.data.users.get(e.var.tenant_id,r);if(!f)throw new I(500);return await fe(e,e.var.tenant_id,{type:ue.SUCCESS_API_OPERATION,description:"Update a User",body:n,response:{statusCode:200,body:f}}),e.json(f)}).openapi(o.createRoute({tags:["users"],method:"post",path:"/{user_id}/identities",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.union([o.z.object({link_with:o.z.string()}),o.z.object({user_id:o.z.string(),provider:o.z.string(),connection:o.z.string().optional()})])}}},params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:o.z.array(Gc)}},description:"Status"}}}),async e=>{const t=e.req.valid("json"),{user_id:n}=e.req.valid("param"),r="link_with"in t?t.link_with:t.user_id,i=await e.env.data.users.get(e.var.tenant_id,n);if(!i)throw new I(400,{message:"Linking an inexistent identity is not allowed."});await e.env.data.users.update(e.var.tenant_id,r,{linked_to:n});const s=await e.env.data.users.list(e.var.tenant_id,{page:0,per_page:10,include_totals:!1,q:`linked_to:${n}`}),a=[i,...s.users].map(fg);return e.json(o.z.array(Gc).parse(a),{status:201})}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/identities/{provider}/{linked_user_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({user_id:o.z.string(),provider:o.z.string(),linked_user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:o.z.array(xn)}},description:"Status"}}}),async e=>{const{user_id:t,provider:n,linked_user_id:r}=e.req.valid("param");await e.env.data.users.unlink(e.var.tenant_id,t,n,r);const i=await e.env.data.users.get(e.var.tenant_id,t);if(!i)throw new I(404);return e.json([xn.parse(i)])}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/sessions",request:{query:rt,headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(du),x7])}},description:"List of sessions"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{include_totals:n,page:r,per_page:i}=e.req.valid("query"),s=await e.env.data.sessions.list(e.var.tenant_id,{page:r,per_page:i,include_totals:n,q:`user_id:${t}`});return n?e.json(s):e.json(s.sessions)}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/permissions",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),query:rt},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:xw}},description:"User permissions"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{page:n,per_page:r,sort:i,q:s}=e.req.valid("query");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});const c=await e.env.data.userPermissions.list(e.var.tenant_id,t,{page:n,per_page:r,include_totals:!1,sort:ft(i),q:s});return e.json(c)}).openapi(o.createRoute({tags:["users"],method:"post",path:"/{user_id}/permissions",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({permissions:o.z.array(o.z.object({permission_name:o.z.string(),resource_server_identifier:o.z.string()}))})}}}},security:[{Bearer:["update:users","auth:write"]}],responses:{201:{description:"Permissions assigned to user"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{permissions:n}=e.req.valid("json");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});for(const i of n)if(!await e.env.data.userPermissions.create(e.var.tenant_id,t,{user_id:t,resource_server_identifier:i.resource_server_identifier,permission_name:i.permission_name}))throw new I(500,{message:"Failed to assign permissions to user"});return e.json({message:"Permissions assigned successfully"},{status:201})}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/permissions",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({permissions:o.z.array(o.z.object({permission_name:o.z.string(),resource_server_identifier:o.z.string()}))})}}}},security:[{Bearer:["update:users","auth:write"]}],responses:{200:{description:"Permissions removed from user"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{permissions:n}=e.req.valid("json");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});for(const i of n)if(!await e.env.data.userPermissions.remove(e.var.tenant_id,t,i))throw new I(500,{message:"Failed to remove permissions from user"});return e.json({message:"Permissions removed successfully"})}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/roles",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:rl}},description:"User roles"}}}),async e=>{const{user_id:t}=e.req.valid("param");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});const r=await e.env.data.userRoles.list(e.var.tenant_id,t,void 0,"");return e.json(r)}).openapi(o.createRoute({tags:["users"],method:"post",path:"/{user_id}/roles",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object({roles:o.z.array(o.z.string())})}}}},security:[{Bearer:["update:users","auth:write"]}],responses:{201:{description:"Roles assigned to user"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{roles:n}=e.req.valid("json");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});for(const i of n)if(!await e.env.data.userRoles.create(e.var.tenant_id,t,i,""))throw new I(500,{message:"Failed to assign roles to user"});return e.json({message:"Roles assigned successfully"},{status:201})}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/roles",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object({roles:o.z.array(o.z.string())})}}}},security:[{Bearer:["update:users","auth:write"]}],responses:{200:{description:"Roles removed from user"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{roles:n}=e.req.valid("json");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});for(const i of n)if(!await e.env.data.userRoles.remove(e.var.tenant_id,t,i,""))throw new I(500,{message:"Failed to remove roles from user"});return e.json({message:"Roles removed successfully"})}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/organizations",request:{params:o.z.object({user_id:o.z.string()}),query:rt,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([S7,o.z.array(mr)])}},description:"List of user organizations"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{page:n,per_page:r,include_totals:i,sort:s}=e.req.valid("query");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});const c=await e.env.data.userOrganizations.listUserOrganizations(e.var.tenant_id,t,{page:n,per_page:r,sort:ft(s)});return i?e.json({organizations:c.organizations,start:c.start,limit:c.limit,length:c.length}):e.json(c.organizations)}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/organizations/{organization_id}",request:{params:o.z.object({user_id:o.z.string(),organization_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:users","auth:write"]}],responses:{200:{description:"User removed from organization successfully"}}}),async e=>{const{user_id:t,organization_id:n}=e.req.valid("param");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});const s=(await e.env.data.userOrganizations.list(e.var.tenant_id,{q:`user_id:${t}`,per_page:100})).userOrganizations.find(a=>a.organization_id===n);if(!s)throw new I(404,{message:"User is not a member of this organization"});return await e.env.data.userOrganizations.remove(e.var.tenant_id,s.id),e.json({message:"User removed from organization successfully"})});var _g={};var mg;function A7(){if(mg)return _g;mg=1;var e;return(function(t){(function(n){var r=typeof globalThis=="object"?globalThis:typeof zm=="object"?zm:typeof self=="object"?self:typeof this=="object"?this:l(),i=s(t);typeof r.Reflect<"u"&&(i=s(r.Reflect,i)),n(i,r),typeof r.Reflect>"u"&&(r.Reflect=t);function s(u,d){return function(f,p){Object.defineProperty(u,f,{configurable:!0,writable:!0,value:p}),d&&d(f,p)}}function a(){try{return Function("return this;")()}catch{}}function c(){try{return(0,eval)("(function() { return this; })()")}catch{}}function l(){return a()||c()}})(function(n,r){var i=Object.prototype.hasOwnProperty,s=typeof Symbol=="function",a=s&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",c=s&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",l=typeof Object.create=="function",u={__proto__:[]}instanceof Array,d=!l&&!u,f={create:l?function(){return Dd(Object.create(null))}:u?function(){return Dd({__proto__:null})}:function(){return Dd({})},has:d?function(O,U){return i.call(O,U)}:function(O,U){return U in O},get:d?function(O,U){return i.call(O,U)?O[U]:void 0}:function(O,U){return O[U]}},p=Object.getPrototypeOf(Function),h=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:ic(),_=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Ld(),g=typeof WeakMap=="function"?WeakMap:tx(),y=s?Symbol.for("@reflect-metadata:registry"):void 0,m=Rn(),v=Zt(m);function k(O,U,q,X){if(V(q)){if(!Y(O))throw new TypeError;if(!me(U))throw new TypeError;return M(O,U)}else{if(!Y(O))throw new TypeError;if(!ce(U))throw new TypeError;if(!ce(X)&&!V(X)&&!Te(X))throw new TypeError;return Te(X)&&(X=void 0),q=B(q),H(O,U,q,X)}}n("decorate",k);function x(O,U){function q(X,de){if(!ce(X))throw new TypeError;if(!V(de)&&!Xe(de))throw new TypeError;we(O,U,X,de)}return q}n("metadata",x);function b(O,U,q,X){if(!ce(q))throw new TypeError;return V(X)||(X=B(X)),we(O,U,q,X)}n("defineMetadata",b);function S(O,U,q){if(!ce(U))throw new TypeError;return V(q)||(q=B(q)),D(O,U,q)}n("hasMetadata",S);function A(O,U,q){if(!ce(U))throw new TypeError;return V(q)||(q=B(q)),Q(O,U,q)}n("hasOwnMetadata",A);function C(O,U,q){if(!ce(U))throw new TypeError;return V(q)||(q=B(q)),pe(O,U,q)}n("getMetadata",C);function P(O,U,q){if(!ce(U))throw new TypeError;return V(q)||(q=B(q)),se(O,U,q)}n("getOwnMetadata",P);function R(O,U){if(!ce(O))throw new TypeError;return V(U)||(U=B(U)),le(O,U)}n("getMetadataKeys",R);function E(O,U){if(!ce(O))throw new TypeError;return V(U)||(U=B(U)),be(O,U)}n("getOwnMetadataKeys",E);function L(O,U,q){if(!ce(U))throw new TypeError;if(V(q)||(q=B(q)),!ce(U))throw new TypeError;V(q)||(q=B(q));var X=Hr(U,q,!1);return V(X)?!1:X.OrdinaryDeleteMetadata(O,U,q)}n("deleteMetadata",L);function M(O,U){for(var q=O.length-1;q>=0;--q){var X=O[q],de=X(U);if(!V(de)&&!Te(de)){if(!me(de))throw new TypeError;U=de}}return U}function H(O,U,q,X){for(var de=O.length-1;de>=0;--de){var tt=O[de],Qe=tt(U,q,X);if(!V(Qe)&&!Te(Qe)){if(!ce(Qe))throw new TypeError;X=Qe}}return X}function D(O,U,q){var X=Q(O,U,q);if(X)return!0;var de=ze(U);return Te(de)?!1:D(O,de,q)}function Q(O,U,q){var X=Hr(U,q,!1);return V(X)?!1:Li(X.OrdinaryHasOwnMetadata(O,U,q))}function pe(O,U,q){var X=Q(O,U,q);if(X)return se(O,U,q);var de=ze(U);if(!Te(de))return pe(O,de,q)}function se(O,U,q){var X=Hr(U,q,!1);if(!V(X))return X.OrdinaryGetOwnMetadata(O,U,q)}function we(O,U,q,X){var de=Hr(q,X,!0);de.OrdinaryDefineOwnMetadata(O,U,q,X)}function le(O,U){var q=be(O,U),X=ze(O);if(X===null)return q;var de=le(X,U);if(de.length<=0)return q;if(q.length<=0)return de;for(var tt=new _,Qe=[],ke=0,ee=q;ke<ee.length;ke++){var re=ee[ke],oe=tt.has(re);oe||(tt.add(re),Qe.push(re))}for(var ae=0,$e=de;ae<$e.length;ae++){var re=$e[ae],oe=tt.has(re);oe||(tt.add(re),Qe.push(re))}return Qe}function be(O,U){var q=Hr(O,U,!1);return q?q.OrdinaryOwnMetadataKeys(O,U):[]}function Ee(O){if(O===null)return 1;switch(typeof O){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return O===null?1:6;default:return 6}}function V(O){return O===void 0}function Te(O){return O===null}function $t(O){return typeof O=="symbol"}function ce(O){return typeof O=="object"?O!==null:typeof O=="function"}function ut(O,U){switch(Ee(O)){case 0:return O;case 1:return O;case 2:return O;case 3:return O;case 4:return O;case 5:return O}var q="string",X=Od(O,a);if(X!==void 0){var de=X.call(O,q);if(ce(de))throw new TypeError;return de}return is(O)}function is(O,U){var q,X;{var de=O.toString;if(G(de)){var X=de.call(O);if(!ce(X))return X}var q=O.valueOf;if(G(q)){var X=q.call(O);if(!ce(X))return X}}throw new TypeError}function Li(O){return!!O}function Di(O){return""+O}function B(O){var U=ut(O);return $t(U)?U:Di(U)}function Y(O){return Array.isArray?Array.isArray(O):O instanceof Object?O instanceof Array:Object.prototype.toString.call(O)==="[object Array]"}function G(O){return typeof O=="function"}function me(O){return typeof O=="function"}function Xe(O){switch(Ee(O)){case 3:return!0;case 4:return!0;default:return!1}}function Ye(O,U){return O===U||O!==O&&U!==U}function Od(O,U){var q=O[U];if(q!=null){if(!G(q))throw new TypeError;return q}}function Rd(O){var U=Od(O,c);if(!G(U))throw new TypeError;var q=U.call(O);if(!ce(q))throw new TypeError;return q}function Ie(O){return O.value}function Se(O){var U=O.next();return U.done?!1:U}function Ui(O){var U=O.return;U&&U.call(O)}function ze(O){var U=Object.getPrototypeOf(O);if(typeof O!="function"||O===p||U!==p)return U;var q=O.prototype,X=q&&Object.getPrototypeOf(q);if(X==null||X===Object.prototype)return U;var de=X.constructor;return typeof de!="function"||de===O?U:de}function je(){var O;!V(y)&&typeof r.Reflect<"u"&&!(y in r.Reflect)&&typeof r.Reflect.defineMetadata=="function"&&(O=Tt(r.Reflect));var U,q,X,de=new g,tt={registerProvider:Qe,getProvider:ee,setProvider:oe};return tt;function Qe(ae){if(!Object.isExtensible(tt))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case O===ae:break;case V(U):U=ae;break;case U===ae:break;case V(q):q=ae;break;case q===ae:break;default:X===void 0&&(X=new _),X.add(ae);break}}function ke(ae,$e){if(!V(U)){if(U.isProviderFor(ae,$e))return U;if(!V(q)){if(q.isProviderFor(ae,$e))return U;if(!V(X))for(var Re=Rd(X);;){var Ke=Se(Re);if(!Ke)return;var Xt=Ie(Ke);if(Xt.isProviderFor(ae,$e))return Ui(Re),Xt}}}if(!V(O)&&O.isProviderFor(ae,$e))return O}function ee(ae,$e){var Re=de.get(ae),Ke;return V(Re)||(Ke=Re.get($e)),V(Ke)&&(Ke=ke(ae,$e),V(Ke)||(V(Re)&&(Re=new h,de.set(ae,Re)),Re.set($e,Ke))),Ke}function re(ae){if(V(ae))throw new TypeError;return U===ae||q===ae||!V(X)&&X.has(ae)}function oe(ae,$e,Re){if(!re(Re))throw new Error("Metadata provider not registered.");var Ke=ee(ae,$e);if(Ke!==Re){if(!V(Ke))return!1;var Xt=de.get(ae);V(Xt)&&(Xt=new h,de.set(ae,Xt)),Xt.set($e,Re)}return!0}}function Rn(){var O;return!V(y)&&ce(r.Reflect)&&Object.isExtensible(r.Reflect)&&(O=r.Reflect[y]),V(O)&&(O=je()),!V(y)&&ce(r.Reflect)&&Object.isExtensible(r.Reflect)&&Object.defineProperty(r.Reflect,y,{enumerable:!1,configurable:!1,writable:!1,value:O}),O}function Zt(O){var U=new g,q={isProviderFor:function(re,oe){var ae=U.get(re);return V(ae)?!1:ae.has(oe)},OrdinaryDefineOwnMetadata:Qe,OrdinaryHasOwnMetadata:de,OrdinaryGetOwnMetadata:tt,OrdinaryOwnMetadataKeys:ke,OrdinaryDeleteMetadata:ee};return m.registerProvider(q),q;function X(re,oe,ae){var $e=U.get(re),Re=!1;if(V($e)){if(!ae)return;$e=new h,U.set(re,$e),Re=!0}var Ke=$e.get(oe);if(V(Ke)){if(!ae)return;if(Ke=new h,$e.set(oe,Ke),!O.setProvider(re,oe,q))throw $e.delete(oe),Re&&U.delete(re),new Error("Wrong provider for target.")}return Ke}function de(re,oe,ae){var $e=X(oe,ae,!1);return V($e)?!1:Li($e.has(re))}function tt(re,oe,ae){var $e=X(oe,ae,!1);if(!V($e))return $e.get(re)}function Qe(re,oe,ae,$e){var Re=X(ae,$e,!0);Re.set(re,oe)}function ke(re,oe){var ae=[],$e=X(re,oe,!1);if(V($e))return ae;for(var Re=$e.keys(),Ke=Rd(Re),Xt=0;;){var sm=Se(Ke);if(!sm)return ae.length=Xt,ae;var nx=Ie(sm);try{ae[Xt]=nx}catch(rx){try{Ui(Ke)}finally{throw rx}}Xt++}}function ee(re,oe,ae){var $e=X(oe,ae,!1);if(V($e)||!$e.delete(re))return!1;if($e.size===0){var Re=U.get(oe);V(Re)||(Re.delete(ae),Re.size===0&&U.delete(Re))}return!0}}function Tt(O){var U=O.defineMetadata,q=O.hasOwnMetadata,X=O.getOwnMetadata,de=O.getOwnMetadataKeys,tt=O.deleteMetadata,Qe=new g,ke={isProviderFor:function(ee,re){var oe=Qe.get(ee);return!V(oe)&&oe.has(re)?!0:de(ee,re).length?(V(oe)&&(oe=new _,Qe.set(ee,oe)),oe.add(re),!0):!1},OrdinaryDefineOwnMetadata:U,OrdinaryHasOwnMetadata:q,OrdinaryGetOwnMetadata:X,OrdinaryOwnMetadataKeys:de,OrdinaryDeleteMetadata:tt};return ke}function Hr(O,U,q){var X=m.getProvider(O,U);if(!V(X))return X;if(q){if(m.setProvider(O,U,v))return v;throw new Error("Illegal state.")}}function ic(){var O={},U=[],q=(function(){function ke(ee,re,oe){this._index=0,this._keys=ee,this._values=re,this._selector=oe}return ke.prototype["@@iterator"]=function(){return this},ke.prototype[c]=function(){return this},ke.prototype.next=function(){var ee=this._index;if(ee>=0&&ee<this._keys.length){var re=this._selector(this._keys[ee],this._values[ee]);return ee+1>=this._keys.length?(this._index=-1,this._keys=U,this._values=U):this._index++,{value:re,done:!1}}return{value:void 0,done:!0}},ke.prototype.throw=function(ee){throw this._index>=0&&(this._index=-1,this._keys=U,this._values=U),ee},ke.prototype.return=function(ee){return this._index>=0&&(this._index=-1,this._keys=U,this._values=U),{value:ee,done:!0}},ke})(),X=(function(){function ke(){this._keys=[],this._values=[],this._cacheKey=O,this._cacheIndex=-2}return Object.defineProperty(ke.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),ke.prototype.has=function(ee){return this._find(ee,!1)>=0},ke.prototype.get=function(ee){var re=this._find(ee,!1);return re>=0?this._values[re]:void 0},ke.prototype.set=function(ee,re){var oe=this._find(ee,!0);return this._values[oe]=re,this},ke.prototype.delete=function(ee){var re=this._find(ee,!1);if(re>=0){for(var oe=this._keys.length,ae=re+1;ae<oe;ae++)this._keys[ae-1]=this._keys[ae],this._values[ae-1]=this._values[ae];return this._keys.length--,this._values.length--,Ye(ee,this._cacheKey)&&(this._cacheKey=O,this._cacheIndex=-2),!0}return!1},ke.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=O,this._cacheIndex=-2},ke.prototype.keys=function(){return new q(this._keys,this._values,de)},ke.prototype.values=function(){return new q(this._keys,this._values,tt)},ke.prototype.entries=function(){return new q(this._keys,this._values,Qe)},ke.prototype["@@iterator"]=function(){return this.entries()},ke.prototype[c]=function(){return this.entries()},ke.prototype._find=function(ee,re){if(!Ye(this._cacheKey,ee)){this._cacheIndex=-1;for(var oe=0;oe<this._keys.length;oe++)if(Ye(this._keys[oe],ee)){this._cacheIndex=oe;break}}return this._cacheIndex<0&&re&&(this._cacheIndex=this._keys.length,this._keys.push(ee),this._values.push(void 0)),this._cacheIndex},ke})();return X;function de(ke,ee){return ke}function tt(ke,ee){return ee}function Qe(ke,ee){return[ke,ee]}}function Ld(){var O=(function(){function U(){this._map=new h}return Object.defineProperty(U.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),U.prototype.has=function(q){return this._map.has(q)},U.prototype.add=function(q){return this._map.set(q,q),this},U.prototype.delete=function(q){return this._map.delete(q)},U.prototype.clear=function(){this._map.clear()},U.prototype.keys=function(){return this._map.keys()},U.prototype.values=function(){return this._map.keys()},U.prototype.entries=function(){return this._map.entries()},U.prototype["@@iterator"]=function(){return this.keys()},U.prototype[c]=function(){return this.keys()},U})();return O}function tx(){var O=16,U=f.create(),q=X();return(function(){function ee(){this._key=X()}return ee.prototype.has=function(re){var oe=de(re,!1);return oe!==void 0?f.has(oe,this._key):!1},ee.prototype.get=function(re){var oe=de(re,!1);return oe!==void 0?f.get(oe,this._key):void 0},ee.prototype.set=function(re,oe){var ae=de(re,!0);return ae[this._key]=oe,this},ee.prototype.delete=function(re){var oe=de(re,!1);return oe!==void 0?delete oe[this._key]:!1},ee.prototype.clear=function(){this._key=X()},ee})();function X(){var ee;do ee="@@WeakMap@@"+ke();while(f.has(U,ee));return U[ee]=!0,ee}function de(ee,re){if(!i.call(ee,q)){if(!re)return;Object.defineProperty(ee,q,{value:f.create()})}return ee[q]}function tt(ee,re){for(var oe=0;oe<re;++oe)ee[oe]=Math.random()*255|0;return ee}function Qe(ee){if(typeof Uint8Array=="function"){var re=new Uint8Array(ee);return typeof crypto<"u"?crypto.getRandomValues(re):typeof msCrypto<"u"?msCrypto.getRandomValues(re):tt(re,ee),re}return tt(new Array(ee),ee)}function ke(){var ee=Qe(O);ee[6]=ee[6]&79|64,ee[8]=ee[8]&191|128;for(var re="",oe=0;oe<O;++oe){var ae=ee[oe];(oe===4||oe===6||oe===8)&&(re+="-"),ae<16&&(re+="0"),re+=ae.toString(16).toLowerCase()}return re}}function Dd(O){return O.__=void 0,delete O.__,O}})})(e||(e={})),_g}A7();const E7="[object ArrayBuffer]";class Z{static isArrayBuffer(t){return Object.prototype.toString.call(t)===E7}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,n){if(t.constructor===n)return t;if(this.isArrayBuffer(t))return new n(t);if(this.isArrayBufferView(t))return new n(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,n){const r=Z.toUint8Array(t),i=Z.toUint8Array(n);if(r.length!==i.byteLength)return!1;for(let s=0;s<r.length;s++)if(r[s]!==i[s])return!1;return!0}static concat(...t){let n;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?n=t[0]:t[t.length-1]instanceof Function?n=t.slice(0,t.length-1):n=t;let r=0;for(const a of n)r+=a.byteLength;const i=new Uint8Array(r);let s=0;for(const a of n){const c=this.toUint8Array(a);i.set(c,s),s+=c.length}return t[t.length-1]instanceof Function?this.toView(i,t[t.length-1]):i.buffer}}const Vd="string",C7=/^[0-9a-f\s]+$/i,I7=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,j7=/^[a-zA-Z0-9-_]+$/;class gg{static fromString(t){const n=unescape(encodeURIComponent(t)),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r.buffer}static toString(t){const n=Z.toUint8Array(t);let r="";for(let s=0;s<n.length;s++)r+=String.fromCharCode(n[s]);return decodeURIComponent(escape(r))}}class wn{static toString(t,n=!1){const r=Z.toArrayBuffer(t),i=new DataView(r);let s="";for(let a=0;a<r.byteLength;a+=2){const c=i.getUint16(a,n);s+=String.fromCharCode(c)}return s}static fromString(t,n=!1){const r=new ArrayBuffer(t.length*2),i=new DataView(r);for(let s=0;s<t.length;s++)i.setUint16(s*2,t.charCodeAt(s),n);return r}}class ie{static isHex(t){return typeof t===Vd&&C7.test(t)}static isBase64(t){return typeof t===Vd&&I7.test(t)}static isBase64Url(t){return typeof t===Vd&&j7.test(t)}static ToString(t,n="utf8"){const r=Z.toUint8Array(t);switch(n.toLowerCase()){case"utf8":return this.ToUtf8String(r);case"binary":return this.ToBinary(r);case"hex":return this.ToHex(r);case"base64":return this.ToBase64(r);case"base64url":return this.ToBase64Url(r);case"utf16le":return wn.toString(r,!0);case"utf16":case"utf16be":return wn.toString(r);default:throw new Error(`Unknown type of encoding '${n}'`)}}static FromString(t,n="utf8"){if(!t)return new ArrayBuffer(0);switch(n.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return wn.fromString(t,!0);case"utf16":case"utf16be":return wn.fromString(t);default:throw new Error(`Unknown type of encoding '${n}'`)}}static ToBase64(t){const n=Z.toUint8Array(t);if(typeof btoa<"u"){const r=this.ToString(n,"binary");return btoa(r)}else return Buffer.from(n).toString("base64")}static FromBase64(t){const n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!ie.isBase64(n))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(n)):new Uint8Array(Buffer.from(n,"base64")).buffer}static FromBase64Url(t){const n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!ie.isBase64Url(n))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(n.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,n=ie.DEFAULT_UTF8_ENCODING){switch(n){case"ascii":return this.FromBinary(t);case"utf8":return gg.fromString(t);case"utf16":case"utf16be":return wn.fromString(t);case"utf16le":case"usc2":return wn.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${n}'`)}}static ToUtf8String(t,n=ie.DEFAULT_UTF8_ENCODING){switch(n){case"ascii":return this.ToBinary(t);case"utf8":return gg.toString(t);case"utf16":case"utf16be":return wn.toString(t);case"utf16le":case"usc2":return wn.toString(t,!0);default:throw new Error(`Unknown type of encoding '${n}'`)}}static FromBinary(t){const n=t.length,r=new Uint8Array(n);for(let i=0;i<n;i++)r[i]=t.charCodeAt(i);return r.buffer}static ToBinary(t){const n=Z.toUint8Array(t);let r="";for(let i=0;i<n.length;i++)r+=String.fromCharCode(n[i]);return r}static ToHex(t){const n=Z.toUint8Array(t);let r="";const i=n.length;for(let s=0;s<i;s++){const a=n[s];a<16&&(r+="0"),r+=a.toString(16)}return r}static FromHex(t){let n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!ie.isHex(n))throw new TypeError("Argument 'hexString' is not HEX encoded");n.length%2&&(n=`0${n}`);const r=new Uint8Array(n.length/2);for(let i=0;i<n.length;i=i+2){const s=n.slice(i,i+2);r[i/2]=parseInt(s,16)}return r.buffer}static ToUtf16String(t,n=!1){return wn.toString(t,n)}static FromUtf16String(t,n=!1){return wn.fromString(t,n)}static Base64Padding(t){const n=4-t.length%4;if(n<4)for(let r=0;r<n;r++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}}ie.DEFAULT_UTF8_ENCODING="utf8";function N7(...e){const t=e.map(i=>i.byteLength).reduce((i,s)=>i+s),n=new Uint8Array(t);let r=0;return e.map(i=>new Uint8Array(i)).forEach(i=>{for(const s of i)n[r++]=s}),n.buffer}function M2(e,t){if(!(e&&t)||e.byteLength!==t.byteLength)return!1;const n=new Uint8Array(e),r=new Uint8Array(t);for(let i=0;i<e.byteLength;i++)if(n[i]!==r[i])return!1;return!0}function vo(e,t){let n=0;if(e.length===1)return e[0];for(let r=e.length-1;r>=0;r--)n+=e[e.length-1-r]*Math.pow(2,t*r);return n}function hi(e,t,n=-1){const r=n;let i=e,s=0,a=Math.pow(2,t);for(let c=1;c<8;c++){if(e<a){let l;if(r<0)l=new ArrayBuffer(c),s=c;else{if(r<c)return new ArrayBuffer(0);l=new ArrayBuffer(r),s=r}const u=new Uint8Array(l);for(let d=c-1;d>=0;d--){const f=Math.pow(2,d*t);u[s-d-1]=Math.floor(i/f),i-=u[s-d-1]*f}return l}a*=Math.pow(2,t)}return new ArrayBuffer(0)}function Sf(...e){let t=0,n=0;for(const s of e)t+=s.length;const r=new ArrayBuffer(t),i=new Uint8Array(r);for(const s of e)i.set(s,n),n+=s.length;return i}function q2(){const e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const c=e[0]===255&&e[1]&128,l=e[0]===0&&(e[1]&128)===0;(c||l)&&this.warnings.push("Needlessly long format")}const t=new ArrayBuffer(this.valueHex.byteLength),n=new Uint8Array(t);for(let c=0;c<this.valueHex.byteLength;c++)n[c]=0;n[0]=e[0]&128;const r=vo(n,8),i=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(i);for(let c=0;c<this.valueHex.byteLength;c++)s[c]=e[c];return s[0]&=127,vo(s,8)-r}function T7(e){const t=e<0?e*-1:e;let n=128;for(let r=1;r<8;r++){if(t<=n){if(e<0){const a=n-t,c=hi(a,8,r),l=new Uint8Array(c);return l[0]|=128,c}let i=hi(t,8,r),s=new Uint8Array(i);if(s[0]&128){const a=i.slice(0),c=new Uint8Array(a);i=new ArrayBuffer(i.byteLength+1),s=new Uint8Array(i);for(let l=0;l<a.byteLength;l++)s[l+1]=c[l];s[0]=0}return i}n*=Math.pow(2,8)}return new ArrayBuffer(0)}function P7(e,t){if(e.byteLength!==t.byteLength)return!1;const n=new Uint8Array(e),r=new Uint8Array(t);for(let i=0;i<n.length;i++)if(n[i]!==r[i])return!1;return!0}function Pt(e,t){const n=e.toString(10);if(t<n.length)return"";const r=t-n.length,i=new Array(r);for(let a=0;a<r;a++)i[a]="0";return i.join("").concat(n)}function ml(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function qh(e){let t=0,n=0;for(let i=0;i<e.length;i++){const s=e[i];t+=s.byteLength}const r=new Uint8Array(t);for(let i=0;i<e.length;i++){const s=e[i];r.set(new Uint8Array(s),n),n+=s.byteLength}return r.buffer}function or(e,t,n,r){return t instanceof Uint8Array?t.byteLength?n<0?(e.error="Wrong parameter: inputOffset less than zero",!1):r<0?(e.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-n-r<0?(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class Iu{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return qh(this.items)}}const as=[new Uint8Array([1])],yg="0123456789",Kd="name",bg="valueHexView",O7="isHexOnly",R7="idBlock",L7="tagClass",D7="tagNumber",U7="isConstructed",B7="fromBER",M7="toBER",q7="local",Et="",Nn=new ArrayBuffer(0),ju=new Uint8Array(0),ia="EndOfContent",F2="OCTET STRING",H2="BIT STRING";function Tn(e){var t;return t=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(r){this.valueHexView=new Uint8Array(r)}constructor(...r){var i;super(...r);const s=r[0]||{};this.isHexOnly=(i=s.isHexOnly)!==null&&i!==void 0?i:!1,this.valueHexView=s.valueHex?Z.toUint8Array(s.valueHex):ju}fromBER(r,i,s){const a=r instanceof ArrayBuffer?new Uint8Array(r):r;if(!or(this,a,i,s))return-1;const c=i+s;return this.valueHexView=a.subarray(i,c),this.valueHexView.length?(this.blockLength=s,c):(this.warnings.push("Zero buffer length"),i)}toBER(r=!1){return this.isHexOnly?r?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Nn)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:ie.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class Ti{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}constructor({blockLength:t=0,error:n=Et,warnings:r=[],valueBeforeDecode:i=ju}={}){this.blockLength=t,this.error=n,this.warnings=r,this.valueBeforeDecodeView=Z.toUint8Array(i)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:ie.ToHex(this.valueBeforeDecodeView)}}}Ti.NAME="baseBlock";class kt extends Ti{fromBER(t,n,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}kt.NAME="valueBlock";class V2 extends Tn(Ti){constructor({idBlock:t={}}={}){var n,r,i,s;super(),t?(this.isHexOnly=(n=t.isHexOnly)!==null&&n!==void 0?n:!1,this.valueHexView=t.valueHex?Z.toUint8Array(t.valueHex):ju,this.tagClass=(r=t.tagClass)!==null&&r!==void 0?r:-1,this.tagNumber=(i=t.tagNumber)!==null&&i!==void 0?i:-1,this.isConstructed=(s=t.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let n=0;switch(this.tagClass){case 1:n|=0;break;case 2:n|=64;break;case 3:n|=128;break;case 4:n|=192;break;default:return this.error="Unknown tag class",Nn}if(this.isConstructed&&(n|=32),this.tagNumber<31&&!this.isHexOnly){const i=new Uint8Array(1);if(!t){let s=this.tagNumber;s&=31,n|=s,i[0]=n}return i.buffer}if(!this.isHexOnly){const i=hi(this.tagNumber,7),s=new Uint8Array(i),a=i.byteLength,c=new Uint8Array(a+1);if(c[0]=n|31,!t){for(let l=0;l<a-1;l++)c[l+1]=s[l]|128;c[a]=s[a-1]}return c.buffer}const r=new Uint8Array(this.valueHexView.byteLength+1);if(r[0]=n|31,!t){const i=this.valueHexView;for(let s=0;s<i.length-1;s++)r[s+1]=i[s]|128;r[this.valueHexView.byteLength]=i[i.length-1]}return r.buffer}fromBER(t,n,r){const i=Z.toUint8Array(t);if(!or(this,i,n,r))return-1;const s=i.subarray(n,n+r);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;const c=s[0]&31;if(c!==31)this.tagNumber=c,this.blockLength=1;else{let l=1,u=this.valueHexView=new Uint8Array(255),d=255;for(;s[l]&128;){if(u[l-1]=s[l]&127,l++,l>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(l===d){d+=255;const p=new Uint8Array(d);for(let h=0;h<u.length;h++)p[h]=u[h];u=this.valueHexView=new Uint8Array(d)}}this.blockLength=l+1,u[l-1]=s[l]&127;const f=new Uint8Array(l);for(let p=0;p<l;p++)f[p]=u[p];u=this.valueHexView=new Uint8Array(l),u.set(f),this.blockLength<=9?this.tagNumber=vo(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return n+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}V2.NAME="identificationBlock";class K2 extends Ti{constructor({lenBlock:t={}}={}){var n,r,i;super(),this.isIndefiniteForm=(n=t.isIndefiniteForm)!==null&&n!==void 0?n:!1,this.longFormUsed=(r=t.longFormUsed)!==null&&r!==void 0?r:!1,this.length=(i=t.length)!==null&&i!==void 0?i:0}fromBER(t,n,r){const i=Z.toUint8Array(t);if(!or(this,i,n,r))return-1;const s=i.subarray(n,n+r);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,n+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,n+this.blockLength;const a=s[0]&127;if(a>8)return this.error="Too big integer",-1;if(a+1>s.length)return this.error="End of input reached before message was fully decoded",-1;const c=n+1,l=i.subarray(c,c+a);return l[a-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=vo(l,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=a+1,n+this.blockLength}toBER(t=!1){let n,r;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return n=new ArrayBuffer(1),t===!1&&(r=new Uint8Array(n),r[0]=128),n;if(this.longFormUsed){const i=hi(this.length,8);if(i.byteLength>127)return this.error="Too big length",Nn;if(n=new ArrayBuffer(i.byteLength+1),t)return n;const s=new Uint8Array(i);r=new Uint8Array(n),r[0]=i.byteLength|128;for(let a=0;a<i.byteLength;a++)r[a+1]=s[a];return n}return n=new ArrayBuffer(1),t===!1&&(r=new Uint8Array(n),r[0]=this.length),n}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}K2.NAME="lengthBlock";const ne={};class at extends Ti{constructor({name:t=Et,optional:n=!1,primitiveSchema:r,...i}={},s){super(i),this.name=t,this.optional=n,r&&(this.primitiveSchema=r),this.idBlock=new V2(i),this.lenBlock=new K2(i),this.valueBlock=s?new s(i):new kt(i)}fromBER(t,n,r){const i=this.valueBlock.fromBER(t,n,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}toBER(t,n){const r=n||new Iu;n||G2(this);const i=this.idBlock.toBER(t);if(r.write(i),this.lenBlock.isIndefiniteForm)r.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,r),r.write(new ArrayBuffer(2));else{const s=this.valueBlock.toBER(t);this.lenBlock.length=s.byteLength;const a=this.lenBlock.toBER(t);r.write(a),r.write(s)}return n?Nn:r.final()}toJSON(){const t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():ie.ToHex(this.toBER())}onAsciiEncoding(){const t=this.constructor.NAME,n=ie.ToHex(this.valueBlock.valueBeforeDecodeView);return`${t} : ${n}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;const n=this.toBER(),r=t.toBER();return P7(n,r)}}at.NAME="BaseBlock";function G2(e){var t;if(e instanceof ne.Constructed)for(const n of e.valueBlock.value)G2(n)&&(e.lenBlock.isIndefiniteForm=!0);return!!(!((t=e.lenBlock)===null||t===void 0)&&t.isIndefiniteForm)}class Fh extends at{getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}constructor({value:t=Et,...n}={},r){super(n,r),t&&this.fromString(t)}fromBER(t,n,r){const i=this.valueBlock.fromBER(t,n,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return i===-1?(this.error=this.valueBlock.error,i):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}Fh.NAME="BaseStringBlock";class W2 extends Tn(kt){constructor({isHexOnly:t=!0,...n}={}){super(n),this.isHexOnly=t}}W2.NAME="PrimitiveValueBlock";var J2;class Ia extends at{constructor(t={}){super(t,W2),this.idBlock.isConstructed=!1}}J2=Ia;ne.Primitive=J2;Ia.NAME="PRIMITIVE";function F7(e,t){if(e instanceof t)return e;const n=new t;return n.idBlock=e.idBlock,n.lenBlock=e.lenBlock,n.warnings=e.warnings,n.valueBeforeDecodeView=e.valueBeforeDecodeView,n}function qo(e,t=0,n=e.length){const r=t;let i=new at({},kt);const s=new Ti;if(!or(s,e,t,n))return i.error=s.error,{offset:-1,result:i};if(!e.subarray(t,t+n).length)return i.error="Zero buffer length",{offset:-1,result:i};let c=i.idBlock.fromBER(e,t,n);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),c===-1)return i.error=i.idBlock.error,{offset:-1,result:i};if(t=c,n-=i.idBlock.blockLength,c=i.lenBlock.fromBER(e,t,n),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),c===-1)return i.error=i.lenBlock.error,{offset:-1,result:i};if(t=c,n-=i.lenBlock.blockLength,!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};let l=at;switch(i.idBlock.tagClass){case 1:if(i.idBlock.tagNumber>=37&&i.idBlock.isHexOnly===!1)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};l=ne.EndOfContent;break;case 1:l=ne.Boolean;break;case 2:l=ne.Integer;break;case 3:l=ne.BitString;break;case 4:l=ne.OctetString;break;case 5:l=ne.Null;break;case 6:l=ne.ObjectIdentifier;break;case 10:l=ne.Enumerated;break;case 12:l=ne.Utf8String;break;case 13:l=ne.RelativeObjectIdentifier;break;case 14:l=ne.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:l=ne.Sequence;break;case 17:l=ne.Set;break;case 18:l=ne.NumericString;break;case 19:l=ne.PrintableString;break;case 20:l=ne.TeletexString;break;case 21:l=ne.VideotexString;break;case 22:l=ne.IA5String;break;case 23:l=ne.UTCTime;break;case 24:l=ne.GeneralizedTime;break;case 25:l=ne.GraphicString;break;case 26:l=ne.VisibleString;break;case 27:l=ne.GeneralString;break;case 28:l=ne.UniversalString;break;case 29:l=ne.CharacterString;break;case 30:l=ne.BmpString;break;case 31:l=ne.DATE;break;case 32:l=ne.TimeOfDay;break;case 33:l=ne.DateTime;break;case 34:l=ne.Duration;break;default:{const u=i.idBlock.isConstructed?new ne.Constructed:new ne.Primitive;u.idBlock=i.idBlock,u.lenBlock=i.lenBlock,u.warnings=i.warnings,i=u}}break;default:l=i.idBlock.isConstructed?ne.Constructed:ne.Primitive}return i=F7(i,l),c=i.fromBER(e,t,i.lenBlock.isIndefiniteForm?n:i.lenBlock.length),i.valueBeforeDecodeView=e.subarray(r,r+i.blockLength),{offset:c,result:i}}function lo(e){if(!e.byteLength){const t=new at({},kt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return qo(Z.toUint8Array(e).slice(),0,e.byteLength)}function H7(e,t){return e?1:t}class $r extends kt{constructor({value:t=[],isIndefiniteForm:n=!1,...r}={}){super(r),this.value=t,this.isIndefiniteForm=n}fromBER(t,n,r){const i=Z.toUint8Array(t);if(!or(this,i,n,r))return-1;if(this.valueBeforeDecodeView=i.subarray(n,n+r),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),n;let s=n;for(;H7(this.isIndefiniteForm,r)>0;){const a=qo(i,s,r);if(a.offset===-1)return this.error=a.result.error,this.warnings.concat(a.result.warnings),-1;if(s=a.offset,this.blockLength+=a.result.blockLength,r-=a.result.blockLength,this.value.push(a.result),this.isIndefiniteForm&&a.result.constructor.NAME===ia)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===ia?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,n){const r=n||new Iu;for(let i=0;i<this.value.length;i++)this.value[i].toBER(t,r);return n?Nn:r.final()}toJSON(){const t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const n of this.value)t.value.push(n.toJSON());return t}}$r.NAME="ConstructedValueBlock";var Z2;class wt extends at{constructor(t={}){super(t,$r),this.idBlock.isConstructed=!0}fromBER(t,n,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const i=this.valueBlock.fromBER(t,n,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}onAsciiEncoding(){const t=[];for(const r of this.valueBlock.value)t.push(r.toString("ascii").split(`
|
|
67
|
+
${f.message}`)}if(d){i.push(...c.actions),s=c;break}}return s?[s]:void 0}get events(){return Bi(this,"events",()=>{const{states:t}=this,n=new Set(this.ownEvents);if(t)for(const r of Object.keys(t)){const i=t[r];if(i.states)for(const s of i.events)n.add(`${s}`)}return Array.from(n)})}get ownEvents(){const t=Object.keys(Object.fromEntries(this.transitions)),n=new Set(t.filter(r=>this.transitions.get(r).some(i=>!(!i.target&&!i.actions.length&&!i.reenter))));return Array.from(n)}}const hA="#";class Th{constructor(t,n){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:n?.actors??{},actions:n?.actions??{},delays:n?.delays??{},guards:n?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new pl(t,{_key:this.id,_machine:this}),this.root._initialize(),L9(this.root),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:n,guards:r,actors:i,delays:s}=this.implementations;return new Th(this.config,{actions:{...n,...t.actions},guards:{...r,...t.guards},actors:{...i,...t.actors},delays:{...s,...t.delays}})}resolveState(t){const n=eA(this.root,t.value),r=ll(dl(this.root,n));return Ec({_nodes:[...r],context:t.context||{},children:{},status:Ch(r,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,n,r){return Hd(t,n,r,[]).snapshot}microstep(t,n,r){return Hd(t,n,r,[]).microsteps.map(([i])=>i)}getTransitionData(t,n){return Ih(this.root,t.value,t,n)||[]}_getPreInitialState(t,n,r){const{context:i}=this.config,s=Ec({context:typeof i!="function"&&i?i:{},_nodes:[this.root],children:{},status:"active"},this);return typeof i=="function"?go(s,n,t,[Kn(({spawn:c,event:l,self:u})=>i({spawn:c,input:l.input,self:u}))],r,void 0):s}getInitialSnapshot(t,n){const r=Qw(n),i=[],s=this._getPreInitialState(t,r,i),[a]=G9(this.root,s,t,r,i),{snapshot:c}=Hd(a,r,t,i);return c}start(t){Object.values(t.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(t){const n=$h(t),r=n.slice(1),i=mu(n[0])?n[0].slice(hA.length):n[0],s=this.idMap.get(i);if(!s)throw new Error(`Child state node '#${i}' does not exist on machine '${this.id}'`);return ul(s,r)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,n){return cA(t,n)}restoreSnapshot(t,n){const r={},i=t.children;Object.keys(i).forEach(f=>{const p=i[f],h=p.snapshot,_=p.src,g=typeof _=="string"?xh(this,_):_;if(!g)return;const y=Qs(g,{id:f,parent:n.self,syncSnapshot:p.syncSnapshot,snapshot:h,src:_,systemId:p.systemId});r[f]=y});function s(f,p){if(p instanceof pl)return p;try{return f.machine.getStateNodeById(p.id)}catch{}}function a(f,p){if(!p||typeof p!="object")return{};const h={};for(const _ in p){const g=p[_];for(const y of g){const m=s(f,y);m&&(h[_]??=[],h[_].push(m))}}return h}const c=a(this.root,t.historyValue),l=Ec({...t,children:r,_nodes:Array.from(ll(dl(this.root,t.value))),historyValue:c},this),u=new Set;function d(f,p){if(!u.has(f)){u.add(f);for(const h in f){const _=f[h];if(_&&typeof _=="object"){if("xstate$$type"in _&&_.xstate$$type===Sh){f[h]=p[_.id];continue}d(_,p)}}}}return d(l.context,r),l}}function _A(e,t,n,r,{event:i}){const s=typeof i=="function"?i(n,r):i;return[t,{event:s},void 0]}function mA(e,{event:t}){e.defer(()=>e.emit(t))}function _2(e){function t(n,r){}return t.type="xstate.emit",t.event=e,t.resolve=_A,t.execute=mA,t}let kf=(function(e){return e.Parent="#_parent",e.Internal="#_internal",e})({});function gA(e,t,n,r,{to:i,event:s,id:a,delay:c},l){const u=t.machine.implementations.delays;if(typeof s=="string")throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${s}" }) instead`);const d=typeof s=="function"?s(n,r):s;let f;if(typeof c=="string"){const _=u&&u[c];f=typeof _=="function"?_(n,r):_}else f=typeof c=="function"?c(n,r):c;const p=typeof i=="function"?i(n,r):i;let h;if(typeof p=="string"){if(p===kf.Parent?h=e.self._parent:p===kf.Internal?h=e.self:p.startsWith("#_")?h=t.children[p.slice(2)]:h=l.deferredActorIds?.includes(p)?p:t.children[p],!h)throw new Error(`Unable to send event to actor '${p}' from machine '${t.machine.id}'.`)}else h=p||e.self;return[t,{to:h,targetId:typeof p=="string"?p:void 0,event:d,id:a,delay:f},void 0]}function yA(e,t,n){typeof n.to=="string"&&(n.to=t.children[n.to])}function bA(e,t){e.defer(()=>{const{to:n,event:r,delay:i,id:s}=t;if(typeof i=="number"){e.system.scheduler.schedule(e.self,n,r,i,s);return}e.system._relay(e.self,n,r.type===g9?Yw(e.self.id,r.data):r)})}function Ph(e,t,n){function r(i,s){}return r.type="xstate.sendTo",r.to=e,r.event=t,r.id=n?.id,r.delay=n?.delay,r.resolve=gA,r.retryResolve=yA,r.execute=bA,r}function vA(e,t){return Ph(kf.Parent,e,t)}function wA(e,t,n,r,{collect:i}){const s=[],a=function(l){s.push(l)};return a.assign=(...c)=>{s.push(Kn(...c))},a.cancel=(...c)=>{s.push(zh(...c))},a.raise=(...c)=>{s.push(Nh(...c))},a.sendTo=(...c)=>{s.push(Ph(...c))},a.sendParent=(...c)=>{s.push(vA(...c))},a.spawnChild=(...c)=>{s.push(Ah(...c))},a.stopChild=(...c)=>{s.push(hu(...c))},a.emit=(...c)=>{s.push(_2(...c))},i({context:n.context,event:n.event,enqueue:a,check:c=>_u(c,t.context,n.event,t),self:e.self,system:e.system},r),[t,void 0,s]}function kA(e){function t(n,r){}return t.type="xstate.enqueueActions",t.collect=e,t.resolve=wA,t}function $A(e,t,n,r,{value:i,label:s}){return[t,{value:typeof i=="function"?i(n,r):i,label:s},void 0]}function xA({logger:e},{value:t,label:n}){n?e(n,t):e(t)}function SA(e=({context:n,event:r})=>({context:n,event:r}),t){function n(r,i){}return n.type="xstate.log",n.value=e,n.label=t,n.resolve=$A,n.execute=xA,n}function zA(e,t){return new Th(e,t)}function AA(e){const t=Qs(e);return{self:t,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:t.system,emit:()=>{},actionExecutor:()=>{}}}function m2({schemas:e,actors:t,actions:n,guards:r,delays:i}){return{assign:Kn,sendTo:Ph,raise:Nh,log:SA,cancel:zh,stopChild:hu,enqueueActions:kA,emit:_2,spawnChild:Ah,createStateConfig:s=>s,createAction:s=>s,createMachine:s=>zA({...s,schemas:e},{actors:t,actions:n,guards:r,delays:i}),extend:s=>m2({schemas:e,actors:t,actions:{...n,...s.actions},guards:{...r,...s.guards},delays:{...i,...s.delays}})}}function EA(e,t,n){const r=[],i=AA(e);return i.actionExecutor=a=>{r.push(a)},[e.transition(t,n,i),r]}var Pr=(e=>(e.AUTHENTICATE="AUTHENTICATE",e.REQUIRE_EMAIL_VERIFICATION="REQUIRE_EMAIL_VERIFICATION",e.START_HOOK="START_HOOK",e.COMPLETE_HOOK="COMPLETE_HOOK",e.START_CONTINUATION="START_CONTINUATION",e.COMPLETE_CONTINUATION="COMPLETE_CONTINUATION",e.COMPLETE="COMPLETE",e.FAIL="FAIL",e.EXPIRE="EXPIRE",e))(Pr||{});const g2=m2({actions:{setUserId:Kn(({event:e})=>e.type==="AUTHENTICATE"?{userId:e.userId}:{}),setHookId:Kn(({event:e})=>e.type==="START_HOOK"?{hookId:e.hookId}:{}),clearHookId:Kn({hookId:void 0}),setContinuationScope:Kn(({event:e})=>e.type==="START_CONTINUATION"?{continuationScope:e.scope}:{}),clearContinuationScope:Kn({continuationScope:void 0}),setFailureReason:Kn(({event:e})=>e.type==="FAIL"?{failureReason:e.reason}:{})}}).createMachine({id:"loginSession",initial:"pending",context:{},states:{pending:{on:{AUTHENTICATE:{target:"authenticated",actions:"setUserId"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},authenticated:{on:{REQUIRE_EMAIL_VERIFICATION:{target:"awaiting_email_verification"},START_HOOK:{target:"awaiting_hook",actions:"setHookId"},START_CONTINUATION:{target:"awaiting_continuation",actions:"setContinuationScope"},COMPLETE:{target:"completed"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},awaiting_email_verification:{on:{COMPLETE:{target:"authenticated"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},awaiting_hook:{on:{COMPLETE_HOOK:{target:"authenticated",actions:"clearHookId"},START_CONTINUATION:{target:"awaiting_continuation",actions:"setContinuationScope"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},awaiting_continuation:{on:{COMPLETE_CONTINUATION:{target:"authenticated",actions:"clearContinuationScope"},FAIL:{target:"failed",actions:"setFailureReason"},EXPIRE:{target:"expired"}}},completed:{type:"final"},failed:{type:"final"},expired:{type:"final"}}});function CA(e,t={}){return g2.resolveState({value:e,context:t})}function ji(e,t,n={}){const r=CA(e,n),[i]=EA(g2,r,t),s={},a=i.context,c=n;return a.userId!==c.userId&&(s.userId=a.userId),a.hookId!==c.hookId&&(s.hookId=a.hookId),a.continuationScope!==c.continuationScope&&(s.continuationScope=a.continuationScope),a.failureReason!==c.failureReason&&(s.failureReason=a.failureReason),{state:i.value,context:s}}function IA(e,t){Object.keys(t).forEach(n=>{const r=t[n];r!=null&&r.length&&e.searchParams.set(n,r)})}function jA(e){try{const t=typeof e=="string"?new URL(e):e;let n=`${t.protocol}//${t.host}${t.pathname}`;if(t.search){const r=Array.from(t.searchParams.keys()).map(i=>`${i}=[REDACTED]`).join("&");n+=`?${r}`}return t.hash&&(n+="#[REDACTED]"),n}catch{const n=(typeof e=="string"?e:e.toString()).match(/^([^?#]*)(\?[^#]*)?(#.*)?$/);if(!n)return"[invalid-url]";const[,r="",i,s]=n;let a=r;if(i){const c=i.substring(1).split("&").map(l=>{const[u]=l.split("=");return`${u}=[REDACTED]`}).join("&");a+=`?${c}`}return s&&(a+="#[REDACTED]"),a}}const Mm=["sub","iss","aud","exp","nbf","iat","jti"];function qm(e,t,n){return{accessToken:{setCustomClaim:(r,i)=>{if(Mm.includes(r))throw new Error(`Cannot overwrite reserved claim '${r}'`);t[r]=i}},idToken:{setCustomClaim:(r,i)=>{if(Mm.includes(r))throw new Error(`Cannot overwrite reserved claim '${r}'`);n&&(n[r]=i)}},access:{deny:r=>{throw new W(400,{message:`Access denied: ${r}`})}},token:{createServiceToken:async r=>(await bu(e,e.var.tenant_id,r.scope,r.expiresInSeconds)).access_token}}}async function gu(e,t){const{authParams:n,user:r,client:i,session_id:s,organization:a,permissions:c,impersonatingUser:l,auth_time:u}=t,{signingKeys:d}=await e.env.data.keys.list({q:"type:jwt_signing"}),f=d.filter(E=>!E.revoked_at||new Date(E.revoked_at)>new Date),p=f[f.length-1];if(!p?.pkcs7)throw new W(500,{message:"No signing key available"});const h=yz(p.pkcs7),_=e.var.custom_domain?`https://${e.var.custom_domain}/`:e.env.ISSUER,g=n.audience||i.tenant.audience;if(!g)throw new W(400,{error:"invalid_request",error_description:"An audience must be specified in the request or configured as the tenant default_audience"});const y={aud:g,scope:n.scope||"",sub:r?.user_id||n.client_id,iss:_,tenant_id:e.var.tenant_id,sid:s,act:l?{sub:l.user_id}:void 0,org_id:a?a.id:void 0,org_name:a&&i.tenant.allow_organization_name_in_authentication_api?a.name.toLowerCase():void 0,permissions:c},m=n.scope?.split(" ")||[],v=m.includes("openid"),k=m.includes("profile"),x=m.includes("email"),b=n.response_type===ot.ID_TOKEN,S=i.auth0_conformant!==!1||b,A=r&&v?{aud:n.client_id,sub:r.user_id,iss:_,sid:s,nonce:n.nonce,...n.max_age!==void 0&&u!==void 0?{auth_time:u}:{},...n.acr_values?{acr:n.acr_values.split(" ")[0]}:{},...k&&S&&{given_name:r.given_name,family_name:r.family_name,nickname:r.nickname,picture:r.picture,locale:r.locale,name:r.name},...x&&S&&{email:r.email,email_verified:r.email_verified},act:l?{sub:l.user_id}:void 0,org_id:a?.id,org_name:a?.name.toLowerCase()}:void 0;e.env.hooks?.onExecuteCredentialsExchange&&await e.env.hooks.onExecuteCredentialsExchange({ctx:e,client:i,user:r,request:{ip:e.var.ip||"",user_agent:e.var.useragent||"",method:e.req.method,url:e.req.url},scope:n.scope||"",grant_type:""},qm(e,y,A));{const{hooks:E}=await e.env.data.hooks.list(e.var.tenant_id,{q:"trigger_id:credentials-exchange",page:0,per_page:100,include_totals:!1}),L=E.filter(H=>H.enabled&&al(H)),M=qm(e,y,A);if(r){for(const H of L)if(al(H))try{await c9(e,H.template_id,r,M)}catch(D){if(D instanceof I)throw D;console.warn(`[credentials-exchange] Failed to execute template hook: ${H.template_id}`,D)}}}const C={expiresIn:l?new ol(1,"h"):new ol(1,"d"),headers:{kid:p.kid}},P=await xm("RS256",h,y,C),R=A?await xm("RS256",h,A,C):void 0;return{access_token:P,refresh_token:t.refresh_token,id_token:R,token_type:"Bearer",expires_in:l?3600:86400}}async function y2(e,t){return{code:(await e.env.data.codes.create(t.client.tenant.id,{code_id:Oe(32),user_id:t.user.user_id,code_type:"authorization_code",login_id:t.login_id,expires_at:new Date(Date.now()+wz*1e3).toISOString(),code_challenge:t.authParams.code_challenge,code_challenge_method:t.authParams.code_challenge_method,redirect_uri:t.authParams.redirect_uri,state:t.authParams.state,nonce:t.authParams.nonce})).code_id,state:t.authParams.state}}async function b2(e,t){const{client:n,scope:r,audience:i=n.tenant.audience,session_id:s}=t;return await e.env.data.refreshTokens.create(n.tenant.id,{id:Uw(),session_id:s,client_id:n.client_id,idle_expires_at:new Date(Date.now()+pu*1e3).toISOString(),user_id:t.user.user_id,device:{last_ip:e.var.ip,initial_ip:e.var.ip,last_user_agent:e.var.useragent||"",initial_user_agent:e.var.useragent||"",initial_asn:"",last_asn:""},resource_servers:[{audience:i,scopes:r}],rotating:!1})}async function Fm(e,{user:t,client:n,loginSession:r}){return await e.env.data.sessions.create(n.tenant.id,{id:Uw(),user_id:t.user_id,login_session_id:r.id,idle_expires_at:new Date(Date.now()+pu*1e3).toISOString(),device:{last_ip:e.var.ip||"",initial_ip:e.var.ip||"",last_user_agent:e.var.useragent||"",initial_user_agent:e.var.useragent||"",initial_asn:"",last_asn:""},clients:[n.client_id]})}async function NA(e,{user:t,client:n,loginSession:r,existingSessionId:i}){const s=await e.env.data.loginSessions.get(n.tenant.id,r.id);if(!s)throw new I(400,{message:`Login session ${r.id} not found`});const a=s.state||We.PENDING;if(a===We.FAILED||a===We.EXPIRED||a===We.COMPLETED)throw new I(400,{message:`Cannot authenticate login session in ${a} state`});if(a===We.AUTHENTICATED){if(s.session_id)return s.session_id;throw new I(500,{message:"Login session is authenticated but has no session_id"})}let c;if(i){const u=await e.env.data.sessions.get(n.tenant.id,i);!u||u.revoked_at?c=(await Fm(e,{user:t,client:n,loginSession:r})).id:(c=i,u.clients.includes(n.client_id)||await e.env.data.sessions.update(n.tenant.id,i,{clients:[...u.clients,n.client_id]}))}else c=(await Fm(e,{user:t,client:n,loginSession:r})).id;const{state:l}=ji(a,{type:Pr.AUTHENTICATE,userId:t.user_id});return await e.env.data.loginSessions.update(n.tenant.id,r.id,{session_id:c,state:l,user_id:t.user_id}),c}async function TA(e,t,n,r){const i=await e.env.data.loginSessions.get(t,n.id);if(!i){console.warn(`Login session ${n.id} not found when trying to mark as failed`);return}const s=i.state||We.PENDING,{state:a,context:c}=ji(s,{type:Pr.FAIL,reason:r});a!==s&&await e.env.data.loginSessions.update(t,n.id,{state:a,failure_reason:c.failureReason})}async function fl(e,t,n,r){const i=await e.env.data.loginSessions.get(t,n.id);if(!i){console.warn(`Login session ${n.id} not found when trying to start hook`);return}const s=i.state||We.PENDING,{state:a,context:c}=ji(s,{type:Pr.START_HOOK,hookId:r});a!==s&&await e.env.data.loginSessions.update(t,n.id,{state:a,state_data:c.hookId?JSON.stringify({hookId:c.hookId}):void 0})}async function Oh(e,t,n){const r=await e.env.data.loginSessions.get(t,n.id);if(!r){console.warn(`Login session ${n.id} not found when trying to complete hook`);return}const i=r.state||We.PENDING,{state:s}=ji(i,{type:Pr.COMPLETE_HOOK});s!==i&&await e.env.data.loginSessions.update(t,n.id,{state:s,state_data:void 0})}async function Hm(e,t,n){const r=await e.env.data.loginSessions.get(t,n.id);if(!r){console.warn(`Login session ${n.id} not found when trying to mark as completed`);return}const i=r.state||We.PENDING,{state:s}=ji(i,{type:Pr.COMPLETE});s!==i&&await e.env.data.loginSessions.update(t,n.id,{state:s})}async function yu(e,t,n,r,i){const s=await e.env.data.loginSessions.get(t,n.id);if(!s){console.warn(`Login session ${n.id} not found when trying to start continuation`);return}const a=s.state||We.PENDING,{state:c}=ji(a,{type:Pr.START_CONTINUATION,scope:r});c!==a?await e.env.data.loginSessions.update(t,n.id,{state:c,state_data:JSON.stringify({continuationScope:r,continuationReturnUrl:i})}):console.warn(`Failed to start continuation for login session ${n.id}: cannot transition from ${a} to AWAITING_CONTINUATION. Scope: ${JSON.stringify(r)}, Return URL: ${jA(i)}`)}async function PA(e,t,n){const r=await e.env.data.loginSessions.get(t,n.id);if(!r){console.warn(`Login session ${n.id} not found when trying to complete continuation`);return}let i;if(r.state_data)try{i=JSON.parse(r.state_data).continuationReturnUrl}catch{}const s=r.state||We.PENDING,{state:a}=ji(s,{type:Pr.COMPLETE_CONTINUATION});return a!==s?await e.env.data.loginSessions.update(t,n.id,{state:a,state_data:void 0}):console.warn(`completeLoginSessionContinuation: State transition from ${s} with COMPLETE_CONTINUATION was invalid or no-op`),i}function OA(e){if(!e.state_data)return null;try{return JSON.parse(e.state_data).continuationScope||null}catch{return null}}function RA(e,t){if(e.state!==We.AWAITING_CONTINUATION)return!1;const n=OA(e);return n?n.includes(t):!1}async function gt(e,t){const{authParams:n,client:r,ticketAuth:i}=t;let{user:s}=t;const a=n.response_type||ot.CODE,c=n.response_mode||pn.QUERY;if(i){if(!t.loginSession)throw new W(500,{message:"Login session not found for ticket auth."});s&&!t.skipHooks&&(t.authStrategy&&s.app_metadata?.strategy!==t.authStrategy.strategy&&(s.app_metadata={...s.app_metadata,strategy:t.authStrategy.strategy},await e.env.data.users.update(r.tenant.id,s.user_id,{app_metadata:{...s.app_metadata||{},strategy:t.authStrategy.strategy}})),await v2(e,e.env.data,r.tenant.id,s,t.loginSession,{client:r,authParams:n,authStrategy:t.authStrategy}));const h=gz(),_=Oe(12),g=await e.env.data.codes.create(r.tenant.id,{code_id:Oe(32),code_type:"ticket",login_id:t.loginSession.id,expires_at:new Date(Date.now()+$z).toISOString(),code_verifier:[_,h].join("|"),redirect_uri:n.redirect_uri,state:n.state,nonce:n.nonce});return e.json({login_ticket:g.code_id,co_verifier:h,co_id:_})}let l=t.refreshToken,u;if(t.loginSession){const h=await e.env.data.loginSessions.get(r.tenant.id,t.loginSession.id);if(!h)throw new W(500,{message:"Login session not found."});const _=h.state||We.PENDING;if(_===We.COMPLETED)throw new W(400,{error:"invalid_request",error_description:"Login session has already been completed"});if(_===We.FAILED)throw new W(400,{error:"access_denied",error_description:`Login session failed: ${h.failure_reason||"unknown reason"}`});if(_===We.EXPIRED)throw new W(400,{error:"invalid_request",error_description:"Login session has expired"});if(_===We.PENDING)u=await NA(e,{user:s,client:r,loginSession:t.loginSession,existingSessionId:t.existingSessionIdToLink});else if(u=h.session_id,!u)throw new W(500,{message:`Login session in ${_} state but has no session_id`})}else throw new W(500,{message:"loginSession must be provided for front-channel auth responses."});if(!l&&n.scope?.split(" ").includes("offline_access")&&![ot.TOKEN,ot.CODE].includes(a)&&!t.impersonatingUser&&(l=(await b2(e,{user:s,client:r,session_id:u,scope:n.scope,audience:n.audience})).id),c===pn.SAML_POST){if(!u)throw new I(500,{message:"Session ID not available for SAML response"});return e9(e,t.client,t.authParams,s,u)}const d=await LA(e,{authParams:n,user:s,client:r,session_id:u,refresh_token:l,authStrategy:t.authStrategy,loginSession:t.loginSession,responseType:a,skipHooks:t.skipHooks,organization:t.organization,impersonatingUser:t.impersonatingUser});if(d instanceof Response)return d;if(c===pn.WEB_MESSAGE){if(!n.redirect_uri)throw new W(400,{message:"Redirect URI not allowed for WEB_MESSAGE response mode."});const h=new Headers;u?sl(r.tenant.id,u,e.var.host||"").forEach(m=>{h.append("set-cookie",m)}):console.warn("Session ID not available for WEB_MESSAGE, cookie will not be set.");const _=new URL(n.redirect_uri),g=`${_.protocol}//${_.host}`;return _f(e,g,JSON.stringify({...d,state:n.state}),h)}if(!n.redirect_uri)throw new W(400,{message:"Redirect uri not found for this response mode."});const f=new Headers;u&&sl(r.tenant.id,u,e.var.custom_domain||e.req.header("host")||"").forEach(_=>{f.append("set-cookie",_)});const p=new URL(n.redirect_uri);if("code"in d)p.searchParams.set("code",d.code),d.state&&p.searchParams.set("state",d.state);else if("access_token"in d)p.hash=new URLSearchParams({access_token:d.access_token,...d.id_token&&{id_token:d.id_token},token_type:d.token_type,expires_in:d.expires_in.toString(),...n.state&&{state:n.state},...n.scope&&{scope:n.scope}}).toString();else throw new W(500,{message:"Invalid token response for implicit flow."});return f.set("location",p.toString()),new Response("Redirecting",{status:302,headers:f})}async function LA(e,t){let{user:n}=t;const r=t.responseType||ot.TOKEN;if(n&&t.organization&&!(await e.env.data.userOrganizations.list(t.client.tenant.id,{q:`user_id:${n.user_id}`,per_page:1e3})).userOrganizations.some(u=>u.organization_id===t.organization.id))throw new W(403,{error:"access_denied",error_description:"User is not a member of the specified organization"});let i=t.authParams.scope||"",s=[];if(t.authParams.audience)try{let c;if(t.grantType===an.ClientCredential||!n&&!t.user)c=await Ys(e,{grantType:an.ClientCredential,tenantId:t.client.tenant.id,clientId:t.client.client_id,audience:t.authParams.audience,requestedScopes:t.authParams.scope?.split(" ")||[],organizationId:t.organization?.id});else{const l=n?.user_id||t.user?.user_id;if(!l)throw new W(400,{error:"invalid_request",error_description:"User ID is required for user-based grants"});c=await Ys(e,{grantType:t.grantType,tenantId:t.client.tenant.id,userId:l,clientId:t.client.client_id,audience:t.authParams.audience,requestedScopes:t.authParams.scope?.split(" ")||[],organizationId:t.organization?.id})}i=c.scopes.join(" "),s=c.permissions}catch(c){if(c instanceof I)throw c}const a={...t.authParams,scope:i};if(t.loginSession&&n&&!t.skipHooks){t.authStrategy&&n.app_metadata?.strategy!==t.authStrategy.strategy&&(n.app_metadata={...n.app_metadata,strategy:t.authStrategy.strategy},await e.env.data.users.update(t.client.tenant.id,n.user_id,{app_metadata:{...n.app_metadata||{},strategy:t.authStrategy.strategy}}));const c=await v2(e,e.env.data,t.client.tenant.id,n,t.loginSession,{client:t.client,authParams:a,authStrategy:t.authStrategy});if(c instanceof Response)return c;n=c}if(r===ot.CODE){if(!n||!t.loginSession)throw new W(500,{message:"User and loginSession is required for code flow"});const c=await y2(e,{user:n,client:t.client,authParams:a,login_id:t.loginSession.id});return await Hm(e,t.client.tenant.id,t.loginSession),c}else{const c=await gu(e,{...t,user:n,authParams:a,permissions:s});return t.loginSession&&await Hm(e,t.client.tenant.id,t.loginSession),c}}const Vm="auth-service";async function bu(e,t,n,r){const i=await e.env.data.tenants.get(t);if(!i)throw new Error(`Tenant not found: ${t}`);const s={client_id:Vm,tenant:i,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),name:"Auth Service",global:!1,is_first_party:!0,oidc_conformant:!1,auth0_conformant:!0,sso:!1,sso_disabled:!1,cross_origin_authentication:!1,custom_login_page_on:!1,require_pushed_authorization_requests:!1,require_proof_of_possession:!1,client_metadata:{disable_sign_ups:"false",email_validation:"disabled"},disable_sign_ups:!1,email_validation:"disabled",connections:[]},a=await gu(e,{client:s,authParams:{client_id:Vm,response_type:ot.TOKEN,scope:n}});return{access_token:a.access_token,token_type:a.token_type,expires_in:r||3600}}async function vu(e,t,n){const r=e.env.webhookInvoker,i=new Map,s=async(a="webhook")=>{const c=i.get(a);if(c)return c;const l=await bu(e,n.tenant_id,a);return i.set(a,l.access_token),l.access_token};for await(const a of t.filter(c=>"url"in c)){let c,l;try{const u=r?await r({hook:a,data:n,tenant_id:n.tenant_id,createServiceToken:s}):await fetch(a.url,{method:"POST",headers:{Authorization:`Bearer ${await s()}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(l=u.status,!u.ok){try{c=await u.text()}catch{}fe(e,n.tenant_id,{type:ue.FAILED_HOOK,description:`Failed to invoke hook ${a.hook_id} - ${u.status} ${u.statusText}`,userId:n.user?.user_id,details:{trigger_id:n.trigger_id,hook_id:a.hook_id,hook_url:a.url,user_id:n.user?.user_id,user_name:n.user?.name||n.user?.email,connection:n.user?.connection,response:{statusCode:l,body:c?.substring(0,512)}},connection:n.user?.connection})}}catch(u){fe(e,n.tenant_id,{type:ue.FAILED_HOOK,description:`Failed to invoke hook ${a.hook_id} - ${u instanceof Error?u.message:"Unknown error"}`,userId:n.user?.user_id,details:{trigger_id:n.trigger_id,hook_id:a.hook_id,hook_url:a.url,user_id:n.user?.user_id,user_name:n.user?.name||n.user?.email,connection:n.user?.connection,error:u instanceof Error?u.message:String(u)},connection:n.user?.connection})}}}function DA(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t);return await vu(e,r,{tenant_id:t,user:n,trigger_id:"post-user-registration"}),n}}function UA(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t,{q:"trigger_id:pre-user-registration",page:0,per_page:100,include_totals:!1});await vu(e,r,{tenant_id:t,email:n,trigger_id:"pre-user-registration"})}}async function BA(e,t){const{hooks:n}=await e.env.data.hooks.list(t,{q:"trigger_id:validate-registration-username",page:0,per_page:1,include_totals:!1});return n.find(r=>"url"in r&&r.enabled)||null}function MA(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t,{q:"trigger_id:pre-user-deletion",page:0,per_page:100,include_totals:!1});return await vu(e,r,{tenant_id:t,user:n,trigger_id:"pre-user-deletion"}),n}}function qA(e){return async(t,n)=>{const{hooks:r}=await e.env.data.hooks.list(t,{q:"trigger_id:post-user-deletion",page:0,per_page:100,include_totals:!1});return await vu(e,r,{tenant_id:t,user:n,trigger_id:"post-user-deletion"}),n}}function wu(e){return e.ISSUER}function _t(e){return e.UNIVERSAL_LOGIN_URL||`${e.ISSUER}u/`}function Le(e){return e.OAUTH_API_URL||e.ISSUER}o.z.object({...Qr.shape,tenant:el,connections:o.z.array(_r)});async function He(e,t,n){let r,i=n;if(!i){const p=await e.data.clients.getByClientId(t);if(!p)throw new W(403,{message:"Client not found"});const{tenant_id:h,..._}=p;r=_,i=h}const[s,a,c,l]=await Promise.all([r?Promise.resolve(r):e.data.clients.get(i,t),e.data.tenants.get(i),e.data.clientConnections.listByClient(i,t),e.data.connections.list(i)]),u=r||s;if(!u)throw new W(403,{message:"Client not found"});if(!a)throw new W(404,{message:"Tenant not found"});const d=c.length>0?c:l.connections||[],f=_t(e);return{...u,web_origins:[...u.web_origins||[],`${f}login`],allowed_logout_urls:[...u.allowed_logout_urls||[],e.ISSUER],callbacks:[...u.callbacks||[],`${f}info`],tenant:a,connections:d}}function Km(e){return typeof e.form_id=="string"}function yo(e,t){const n=e.match(/^\{\{context\.user\.(.+)\}\}$/);if(n&&n[1])return Gm(t.user,n[1]);const r=e.match(/^\{\{user\.(.+)\}\}$/);if(r&&r[1])return Gm(t.user,r[1]);const i=e.match(/^\{\{\$form\.(.+)\}\}$/);if(i&&i[1]&&t.submittedFields){const s=t.submittedFields[i[1]];return s!==void 0?String(s):void 0}return e}function Gm(e,t){const n=t.split(".");let r=e;for(const i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return;return typeof r=="string"?r:r==null?void 0:String(r)}function FA(e,t){const n={};for(const[r,i]of Object.entries(e))if(typeof i=="string"){const s=yo(i,t);s!==void 0&&(n[r]=s)}else i!=null&&(n[r]=String(i));return n}function Wm(e,t){const n=e.operator?.toLowerCase(),r=e.field?yo(e.field,t):"",i=e.value||"";switch(n){case"exists":return r!=null&&r!=="";case"not_exists":return r==null||r==="";case"ends_with":return typeof r=="string"&&r.endsWith(i);case"starts_with":return typeof r=="string"&&r.startsWith(i);case"contains":return typeof r=="string"&&r.includes(i);case"not_contains":return typeof r!="string"||!r.includes(i);case"equals":case"eq":return r===i;case"not_equals":case"neq":return r!==i;default:if(e.operands&&Array.isArray(e.operands)){for(const s of e.operands)if(s.operator==="ENDS_WITH"&&Array.isArray(s.operands)&&s.operands.length>=2){const a=s.operands[0],c=s.operands[1];if(a&&c){const l=yo(`{{context.user.${a}}}`,t);if(typeof l=="string"&&l.endsWith(c))return!0}}}return!1}}function HA(e,t){return e.type==="and"&&Array.isArray(e.conditions)?e.conditions.every(n=>Wm(n,t)):Wm(e,t)}function ku(e,t){const n={};for(const[r,i]of Object.entries(e))if(r.startsWith("user_metadata.")||r.startsWith("metadata.")){const s=r.startsWith("user_metadata.")?r.slice(14):r.slice(9),a=t.user_metadata||{};n.user_metadata={...a,...n.user_metadata||{},[s]:i}}else if(r.startsWith("address.")){const s=r.slice(8),a=t.address||{};n.address={...a,...n.address||{},[s]:i}}else n[r]=i;return n}function $u(e){const t=new Map;for(const n of e){const r=t.get(n.user_id);r?r.changes={...r.changes,...n.changes}:t.set(n.user_id,{user_id:n.user_id,changes:{...n.changes}})}return Array.from(t.values())}function xu(e,t,n){switch(e){case"change-email":return`/u/account/change-email?state=${encodeURIComponent(n)}`;case"account":return`/u/account?state=${encodeURIComponent(n)}`;case"custom":if(!t)throw new I(400,{message:"Custom URL is required for custom redirect target"});const r=new URL(t,"http://placeholder");return r.searchParams.set("state",n),r.pathname+r.search;default:throw new I(400,{message:`Unknown redirect target: ${e}`})}}async function Su(e,t,n,r,i=10){let s=t,a=0;const c=[];for(;a<i;){if(s==="$ending")return{type:"end",userUpdates:c.length>0?c:void 0};const l=e.find(u=>u.id===s);if(!l)return null;if(l.type==="STEP")return{type:"step",nodeId:l.id,userUpdates:c.length>0?c:void 0};if(l.type==="ACTION"){const u=l;if(u.config.action_type==="REDIRECT")return{type:"redirect",target:u.config.target,customUrl:u.config.custom_url,userUpdates:c.length>0?c:void 0};s=u.config.next_node,a++;continue}if(l.type==="ROUTER"){const u=l;let d=null;for(const f of u.config.rules)if(HA(f.condition,n)){d=f.next_node;break}if(d||(d=u.config.fallback),!d)return null;s=d,a++;continue}if(l.type==="FLOW"){const u=l;if(r&&u.config.flow_id){const d=await r(u.config.flow_id);if(d&&d.actions&&d.actions.length>0)for(const f of d.actions){if(f.type==="REDIRECT"&&f.action==="REDIRECT_USER"){const p=f.params?.target;if(p)return{type:"redirect",target:p,customUrl:f.params?.custom_url,userUpdates:c.length>0?c:void 0}}if(f.type==="AUTH0"&&f.action==="UPDATE_USER"&&f.params){const p=f.params.user_id&&yo(f.params.user_id,n)||n.user.user_id,h=f.params.changes?FA(f.params.changes,n):{};Object.keys(h).length>0&&c.push({user_id:p,changes:h})}}}if(u.config.next_node){s=u.config.next_node,a++;continue}return{type:"end",userUpdates:c.length>0?c:void 0}}return null}return null}async function VA(e,t,n,r,i){const s=e.env.data,a=e.var.tenant_id||e.req.header("tenant-id");if(!a)throw new I(400,{message:"Missing tenant_id in context"});const c=i?.client_metadata?.universal_login_version==="2"?"/u2":"/u",l=await s.forms.get(a,t);if(!l)throw new I(404,{message:"Form not found for post-user-login hook"});let u=l.start?.next_node;if(!u&&l.nodes&&l.nodes.length>0&&(u=l.nodes.find(p=>p.type==="STEP")?.id),!u)throw new I(400,{message:"No start node found in form"});if(r&&l.nodes){const f=async h=>{const _=await s.flows.get(a,h);return _?{actions:_.actions?.map(g=>({type:g.type,action:g.action,params:"params"in g&&g.params?g.params:void 0}))}:null},p=await Su(l.nodes,u,{user:r},f);if(p&&p.userUpdates&&p.userUpdates.length>0){const h=$u(p.userUpdates);for(const _ of h){const g=ku(_.changes,r);await s.users.update(a,_.user_id,g)}}if(!p||p.type==="end")return r;if(p.type==="redirect"){const h=p.target,_=xu(h,p.customUrl,n.id);if(h==="change-email"||h==="account"){const g=`${c}/continue?state=${encodeURIComponent(n.id)}`;await yu(e,a,n,[h],g)}else await fl(e,a,n,`form:${t}`);return new Response(null,{status:302,headers:{location:_}})}u=p.nodeId}await fl(e,a,n,`form:${t}`);let d=`${c}/forms/${l.id}/nodes/${u}?state=${encodeURIComponent(n.id)}`;return new Response(null,{status:302,headers:{location:d}})}function Jm(e){return typeof e.page_id=="string"&&typeof e.enabled=="boolean"}async function KA(e,t,n,r,i){const s=e.env.data,a=e.var.tenant_id||e.req.header("tenant-id");if(!a)throw new I(400,{message:"Missing tenant_id in context"});if(i&&!(await s.userPermissions.list(a,r.user_id)).some(f=>f.permission_name===i))return r;await fl(e,a,n,`page:${t}`);let c="/u";if(n.authParams.client_id)try{(await He(e.env,n.authParams.client_id,a))?.client_metadata?.universal_login_version==="2"&&(c="/u2")}catch{}let l=`${c}/${t}?state=${encodeURIComponent(n.id)}`;return new Response(null,{status:302,headers:{location:l}})}function pi(e,t){return{createServiceToken:async n=>(await bu(e,t,n.scope,n.expiresInSeconds)).access_token}}function Zm(e){return typeof e.url=="string"}function GA(e,t){return async(n,r)=>{if(e.var.client_id){const a=await He(e.env,e.var.client_id,e.var.tenant_id);r.email&&await JA(e,a,t,r.email)}const i={method:e.req.method,ip:e.req.query("x-real-ip")||"",user_agent:e.req.query("user-agent"),url:e.var.loginSession?.authorization_url||e.req.url};if(e.env.hooks?.onExecutePreUserRegistration)try{await e.env.hooks.onExecutePreUserRegistration({ctx:e,user:r,request:i},{user:{setUserMetadata:async(a,c)=>{r[a]=c},setLinkedTo:a=>{r.linked_to=a}},token:pi(e,n)})}catch{fe(e,n,{type:ue.FAILED_SIGNUP,description:"Pre user registration hook failed"})}let s=await ez(t)(n,r);if(e.env.hooks?.onExecutePostUserRegistration)try{await e.env.hooks.onExecutePostUserRegistration({ctx:e,user:r,request:i},{user:{},token:pi(e,n)})}catch{fe(e,n,{type:ue.FAILED_SIGNUP,description:"Post user registration hook failed"})}return await DA(e)(n,s),s}}function WA(e,t){return async(n,r,i)=>{if(Object.keys(i).length===1&&"linked_to"in i)return t.users.update(n,r,i);const s=await t.users.get(n,r);if(!s)throw new W(404,{message:"User not found"});const a={method:e.req.method,ip:e.var.ip||e.get("ip")||"",user_agent:e.var.useragent||e.get("useragent")||"",url:e.req.url};if(e.env.hooks?.onExecutePreUserUpdate)try{await e.env.hooks.onExecutePreUserUpdate({ctx:e,tenant:{id:n},user_id:r,user:s,updates:i,request:a},{user:{setUserMetadata:async(c,l)=>{i[c]=l}},cancel:()=>{throw new W(400,{message:"User update cancelled by pre-update hook"})},token:pi(e,n)})}catch(c){throw fe(e,n,{type:ue.ACTIONS_EXECUTION_FAILED,description:`Pre user update hook failed: ${c instanceof Error?c.message:"Unknown error"}`,userId:r}),new W(400,{message:"Pre user update hook failed"})}if(await t.users.update(n,r,i),i.email||i.email_verified){const c=await t.users.get(n,r);if(c&&c.email&&c.email_verified){const{users:l}=await t.users.list(n,{page:0,per_page:10,include_totals:!1,q:`email:${c.email}`}),u=l.filter(d=>d.email_verified&&d.user_id!==r&&!d.linked_to);u.length>0&&await t.users.update(n,r,{linked_to:u[0].user_id})}}return i.email&&fe(e,n,{type:ue.SUCCESS_CHANGE_EMAIL,description:`Email updated to ${i.email}`,userId:r}),!0}}async function zu(e,t,n,r,i="email"){if(t.client_metadata?.disable_sign_ups==="true"){const a=e.var.loginSession?.authorization_url;if(a&&new URL(a).searchParams.get("screen_hint")==="signup")return{allowed:!0};if(!await Uo({userAdapter:n.users,tenant_id:t.tenant.id,email:r}))return{allowed:!1,reason:"User account does not exist"}}if(e.env.hooks?.onExecuteValidateRegistrationUsername){const a={method:e.req.method,ip:e.var.ip||e.get("ip")||"",user_agent:e.var.useragent||e.get("useragent")||"",url:e.req.url};let c=!1,l;try{if(await e.env.hooks.onExecuteValidateRegistrationUsername({ctx:e,client:t,request:a,tenant:{id:t.tenant.id},user:{email:r,connection:i}},{deny:u=>{c=!0,l=u},token:pi(e,t.tenant.id)}),c)return{allowed:!1,reason:l}}catch{return{allowed:!1,reason:"Signup validation hook failed"}}}const s=await BA(e,t.tenant.id);if(s&&"url"in s)try{const a=await bu(e,t.tenant.id,"webhook"),c=await fetch(s.url,{method:"POST",headers:{Authorization:`Bearer ${a.access_token}`,"Content-Type":"application/json"},body:JSON.stringify({tenant_id:t.tenant.id,email:r,connection:i,client_id:t.client_id,trigger_id:"validate-registration-username"})});if(!c.ok)return{allowed:!1,reason:await c.text()||"Signup not allowed by webhook"};const l=await c.json();if(l.allowed===!1)return{allowed:!1,reason:l.reason||"Signup not allowed by webhook"}}catch{fe(e,t.tenant.id,{type:ue.FAILED_HOOK,description:"Validate signup email webhook failed"})}return{allowed:!0}}async function JA(e,t,n,r){const i=await zu(e,t,n,r);if(!i.allowed)throw fe(e,t.tenant.id,{type:ue.FAILED_SIGNUP,description:i.reason||"Signup not allowed"}),new W(400,{message:i.reason||"Signups are disabled for this client"});await UA(e)(t.tenant.id,r)}function ZA(e,t){return async(n,r)=>{const i=await t.users.get(n,r);if(!i)return!1;const s={method:e.req.method,ip:e.var.ip||e.get("ip")||"",user_agent:e.var.useragent||e.get("useragent")||"",url:e.req.url};if(e.env.hooks?.onExecutePreUserDeletion)try{await e.env.hooks.onExecutePreUserDeletion({ctx:e,user:i,user_id:r,request:s,tenant:{id:n}},{cancel:()=>{throw new W(400,{message:"User deletion cancelled by pre-deletion hook"})},token:pi(e,n)})}catch(l){throw l instanceof I?l:(fe(e,n,{type:ue.FAILED_HOOK,description:`Pre user deletion hook failed: ${l instanceof Error?l.message:String(l)}`}),new W(400,{message:"Pre user deletion hook failed"}))}try{await MA(e)(n,i)}catch(l){throw fe(e,n,{type:ue.FAILED_HOOK,description:`Pre user deletion webhook failed: ${l instanceof Error?l.message:String(l)}`}),new W(400,{message:"Pre user deletion webhook failed"})}const a=await t.users.list(n,{q:`linked_to:${r}`});for(const l of a.users){const[u,...d]=l.user_id.split("|");u&&await t.users.unlink(n,r,u,d.join("|"))}const c=await t.users.remove(n,r);if(c){fe(e,n,{type:ue.SUCCESS_USER_DELETION,description:`Deleted user: ${i.email||r}`,userId:r,strategy:i.provider||"auth0",strategy_type:i.is_social?"social":"database",connection:i.connection||"",body:{tenant:n,connection:i.connection||""}});try{await qA(e)(n,i)}catch(l){fe(e,n,{type:ue.FAILED_HOOK,description:`Post user deletion webhook failed: ${l instanceof Error?l.message:String(l)}`})}}if(c&&e.env.hooks?.onExecutePostUserDeletion)try{await e.env.hooks.onExecutePostUserDeletion({ctx:e,user:i,user_id:r,request:s,tenant:{id:n}},{token:pi(e,n)})}catch(l){fe(e,n,{type:ue.FAILED_HOOK,description:`Post user deletion hook failed: ${l instanceof Error?l.message:String(l)}`})}return c}}function Do(e,t){const n=t;return{...t,users:{...t.users,create:GA(e,n),update:WA(e,n),remove:ZA(e,n)}}}async function XA(e,t,n,r,i,s){let a=[];try{a=(await t.userRoles.list(n,r.user_id,void 0,"")).map(p=>p.name||p.id)}catch(d){console.error("Error fetching user roles:",d)}let c={};if(r.connection)try{const f=(await t.connections.list(n,{page:0,per_page:100,include_totals:!1})).connections.find(p=>p.name===r.connection);f&&(c={id:f.id,name:f.name,strategy:f.strategy||r.provider,metadata:f.options||{}})}catch(d){console.error("Error fetching connection info:",d)}let l;try{if(i.authParams?.organization){const d=await t.organizations.get(n,i.authParams.organization);d&&(l={id:d.id,name:d.name,display_name:d.display_name||d.name,metadata:d.metadata||{}})}}catch(d){console.error("Error fetching organization info:",d)}const u=e.get("countryCode");return{ctx:e,client:s.client,user:r,request:{asn:void 0,ip:e.get("ip")||"",user_agent:e.get("useragent"),method:e.req.method,url:e.req.url,geoip:{cityName:void 0,continentCode:void 0,countryCode:u||void 0,countryName:void 0,latitude:void 0,longitude:void 0,timeZone:void 0}},transaction:{id:i.id,locale:i.authParams?.ui_locales||"en",login_hint:void 0,prompt:i.authParams?.prompt,redirect_uri:i.authParams?.redirect_uri,requested_scopes:i.authParams?.scope?.split(" ")||[],response_mode:i.authParams?.response_mode,response_type:i.authParams?.response_type,state:i.authParams?.state,ui_locales:i.authParams?.ui_locales},scope:s.authParams?.scope||"",grant_type:s.authParams?.grant_type||"",audience:s.authParams?.audience,authentication:{methods:[{name:r.is_social?"federated":"pwd",timestamp:new Date().toISOString()}]},authorization:{roles:a},connection:Object.keys(c).length>0?c:{id:r.connection||"Username-Password-Authentication",name:r.connection||"Username-Password-Authentication",strategy:r.provider||"auth0"},organization:l,resource_server:s.authParams?.audience?{identifier:s.authParams.audience}:void 0,stats:{logins_count:r.login_count||0},tenant:{id:n},session:{id:i.id,created_at:i.created_at,authenticated_at:new Date().toISOString(),clients:[{client_id:s.client.client_id}],device:{initial_ip:e.get("ip"),initial_user_agent:e.get("useragent"),last_ip:r.last_ip||e.get("ip"),last_user_agent:e.get("useragent")}}}}async function v2(e,t,n,r,i,s){const a=s?.authStrategy?.strategy_type?s.authStrategy.strategy_type:r.is_social?"social":"database",c=s?.authStrategy?.strategy||r.connection||"";if(fe(e,n,{type:ue.SUCCESS_LOGIN,description:`Successful login for ${r.user_id}`,userId:r.user_id,strategy_type:a,strategy:c,connection:c,audience:s?.authParams?.audience,scope:s?.authParams?.scope}),await t.users.update(n,r.user_id,{last_login:new Date().toISOString(),last_ip:e.var.ip||"",login_count:r.login_count+1}),e.env.hooks?.onExecutePostLogin&&s?.client&&s?.authParams&&i){let f=null;const p=await XA(e,t,n,r,i,{client:s.client,authParams:s.authParams});if(await e.env.hooks.onExecutePostLogin(p,{prompt:{render:h=>{}},redirect:{sendUserTo:(h,_)=>{const g=new URL(h,e.req.url);g.searchParams.set("state",i.id),_?.query&&Object.entries(_.query).forEach(([y,m])=>{g.searchParams.set(y,m)}),f=g.toString()},encodeToken:h=>JSON.stringify({payload:h.payload,exp:Date.now()+(h.expiresInSeconds||900)*1e3}),validateToken:h=>null},token:pi(e,n)}),f)return await fl(e,n,i,"onExecutePostLogin"),new Response(null,{status:302,headers:{location:f}})}const{hooks:l}=await t.hooks.list(n,{q:"trigger_id:post-user-login",page:0,per_page:100,include_totals:!1});if(i){const f=l.find(h=>h.enabled&&Km(h));if(f&&Km(f))return VA(e,f.form_id,i,r,s?.client);const p=l.find(h=>h.enabled&&Jm(h));if(p&&Jm(p))return KA(e,p.page_id,i,r,p.permission_required)}const u=l.filter(f=>f.enabled&&al(f));for(const f of u)if(al(f))try{r=await a9(e,f.template_id,r)}catch{fe(e,n,{type:ue.FAILED_HOOK,description:`Failed to execute template hook: ${f.template_id}`})}const d=l.filter(f=>f.enabled&&Zm(f));for(const f of d)if(Zm(f))try{await fetch(f.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tenant_id:n,user:r,trigger_id:"post-user-login"})})}catch{fe(e,n,{type:ue.FAILED_HOOK,description:`Failed to invoke post-user-login webhook: ${f.url}`})}return r}function YA(e){return Do(e,e.env.data)}async function Rh(e,t,n){return(await e.list(t,{page:0,per_page:10,include_totals:!1,q:`email:${n}`})).users}async function Or({userAdapter:e,tenant_id:t,username:n,provider:r}){let i;r==="sms"?i=`phone_number:${n}`:n.includes("@")?i=`email:${n}`:i=`username:${n}`;const{users:s}=await e.list(t,{page:0,per_page:10,include_totals:!1,q:`${i} provider:${r}`});return s.length>1&&console.error("More than one user found for same username and provider"),s[0]||null}async function Uo({userAdapter:e,tenant_id:t,email:n}){const{users:r}=await e.list(t,{page:0,per_page:10,include_totals:!1,q:`email:${n}`});if(r.length===0)return;const i=r.filter(a=>!a.linked_to);if(i.length>0)return i.length>1&&console.error("More than one primary user found for same email"),i[0];const s=await e.get(t,r[0]?.linked_to);if(!s)throw new Error("Primary account not found");return s}async function Xn({userAdapter:e,tenant_id:t,username:n,provider:r}){const i=await Or({userAdapter:e,tenant_id:t,username:n,provider:r});return i?i.linked_to?e.get(t,i.linked_to):i:null}async function Au(e,t){const{username:n,provider:r,connection:i,client:s,userId:a,isSocial:c,profileData:l={},ip:u=""}=t;let d=await Xn({userAdapter:e.env.data.users,tenant_id:t.client.tenant.id,username:n,provider:r});if(!d){const f={user_id:`${r}|${a||Ii()}`,email:i!=="sms"&&n.includes("@")?n:void 0,phone_number:i==="sms"?n:void 0,username:!n.includes("@")&&i!=="sms"?n:void 0,name:n,provider:r,connection:i,email_verified:!0,last_ip:u,is_social:c,last_login:new Date().toISOString(),profileData:JSON.stringify(l)};d=await YA(e).users.create(s.tenant.id,f),e.set("user_id",d.user_id)}return d}const rt=o.z.object({page:o.z.string().min(0).optional().default("0").transform(e=>parseInt(e,10)).openapi({description:"Page index of the results to return. First page is 0."}),per_page:o.z.string().min(1).optional().default("10").transform(e=>parseInt(e,10)).openapi({description:"Number of results per page. Defaults to 50."}),include_totals:o.z.string().optional().default("false").transform(e=>e==="true").openapi({description:"Return results inside an object that contains the total result count (true) or as a direct array of results (false, default)."}),from:o.z.string().optional().openapi({description:"Optional Id from which to start selection."}),take:o.z.string().optional().transform(e=>e?parseInt(e,10):void 0).openapi({description:"Number of results per page. Defaults to 50."}),sort:o.z.string().regex(/^.+:(-1|1)$/).optional().openapi({description:"Field to sort by. Use field:order where order is 1 for ascending and -1 for descending. e.g. created_at:1."}),q:o.z.string().optional().openapi({description:"A lucene query string used to filter the results"})});function ft(e){if(!e)return;const[t,n]=e.split(":"),r=n==="1"?"asc":"desc";if(!(!t||!r))return{sort_by:t,sort_order:r}}const w2={},QA=Object.freeze(Object.defineProperty({__proto__:null,default:w2},Symbol.toStringTag,{value:"Module"}));var $f=null;function eE(e){try{return crypto.getRandomValues(new Uint8Array(e))}catch{}try{return w2.randomBytes(e)}catch{}if(!$f)throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative");return $f(e)}function tE(e){$f=e}function Lh(e,t){if(e=e||Dh,typeof e!="number")throw Error("Illegal arguments: "+typeof e+", "+typeof t);e<4?e=4:e>31&&(e=31);var n=[];return n.push("$2b$"),e<10&&n.push("0"),n.push(e.toString()),n.push("$"),n.push(hl(eE(ea),ea)),n.join("")}function k2(e,t,n){if(typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof e>"u")e=Dh;else if(typeof e!="number")throw Error("illegal arguments: "+typeof e);function r(i){cn(function(){try{i(null,Lh(e))}catch(s){i(s)}})}if(n){if(typeof n!="function")throw Error("Illegal callback: "+typeof n);r(n)}else return new Promise(function(i,s){r(function(a,c){if(a){s(a);return}i(c)})})}function $2(e,t){if(typeof t>"u"&&(t=Dh),typeof t=="number"&&(t=Lh(t)),typeof e!="string"||typeof t!="string")throw Error("Illegal arguments: "+typeof e+", "+typeof t);return xf(e,t)}function x2(e,t,n,r){function i(s){typeof e=="string"&&typeof t=="number"?k2(t,function(a,c){xf(e,c,s,r)}):typeof e=="string"&&typeof t=="string"?xf(e,t,s,r):cn(s.bind(this,Error("Illegal arguments: "+typeof e+", "+typeof t)))}if(n){if(typeof n!="function")throw Error("Illegal callback: "+typeof n);i(n)}else return new Promise(function(s,a){i(function(c,l){if(c){a(c);return}s(l)})})}function S2(e,t){for(var n=e.length^t.length,r=0;r<e.length;++r)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}function nE(e,t){if(typeof e!="string"||typeof t!="string")throw Error("Illegal arguments: "+typeof e+", "+typeof t);return t.length!==60?!1:S2($2(e,t.substring(0,t.length-31)),t)}function rE(e,t,n,r){function i(s){if(typeof e!="string"||typeof t!="string"){cn(s.bind(this,Error("Illegal arguments: "+typeof e+", "+typeof t)));return}if(t.length!==60){cn(s.bind(this,null,!1));return}x2(e,t.substring(0,29),function(a,c){a?s(a):s(null,S2(c,t))},r)}if(n){if(typeof n!="function")throw Error("Illegal callback: "+typeof n);i(n)}else return new Promise(function(s,a){i(function(c,l){if(c){a(c);return}s(l)})})}function iE(e){if(typeof e!="string")throw Error("Illegal arguments: "+typeof e);return parseInt(e.split("$")[2],10)}function oE(e){if(typeof e!="string")throw Error("Illegal arguments: "+typeof e);if(e.length!==60)throw Error("Illegal hash length: "+e.length+" != 60");return e.substring(0,29)}function sE(e){if(typeof e!="string")throw Error("Illegal arguments: "+typeof e);return z2(e)>72}var cn=typeof setImmediate=="function"?setImmediate:typeof scheduler=="object"&&typeof scheduler.postTask=="function"?scheduler.postTask.bind(scheduler):setTimeout;function z2(e){for(var t=0,n=0,r=0;r<e.length;++r)n=e.charCodeAt(r),n<128?t+=1:n<2048?t+=2:(n&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320?(++r,t+=4):t+=3;return t}function aE(e){for(var t=0,n,r,i=new Array(z2(e)),s=0,a=e.length;s<a;++s)n=e.charCodeAt(s),n<128?i[t++]=n:n<2048?(i[t++]=n>>6|192,i[t++]=n&63|128):(n&64512)===55296&&((r=e.charCodeAt(s+1))&64512)===56320?(n=65536+((n&1023)<<10)+(r&1023),++s,i[t++]=n>>18|240,i[t++]=n>>12&63|128,i[t++]=n>>6&63|128,i[t++]=n&63|128):(i[t++]=n>>12|224,i[t++]=n>>6&63|128,i[t++]=n&63|128);return i}var Mi="./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),lr=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,54,55,56,57,58,59,60,61,62,63,-1,-1,-1,-1,-1,-1,-1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,-1,-1,-1,-1,-1,-1,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,-1,-1,-1,-1,-1];function hl(e,t){var n=0,r=[],i,s;if(t<=0||t>e.length)throw Error("Illegal len: "+t);for(;n<t;){if(i=e[n++]&255,r.push(Mi[i>>2&63]),i=(i&3)<<4,n>=t){r.push(Mi[i&63]);break}if(s=e[n++]&255,i|=s>>4&15,r.push(Mi[i&63]),i=(s&15)<<2,n>=t){r.push(Mi[i&63]);break}s=e[n++]&255,i|=s>>6&3,r.push(Mi[i&63]),r.push(Mi[s&63])}return r.join("")}function A2(e,t){var n=0,r=e.length,i=0,s=[],a,c,l,u,d,f;if(t<=0)throw Error("Illegal len: "+t);for(;n<r-1&&i<t&&(f=e.charCodeAt(n++),a=f<lr.length?lr[f]:-1,f=e.charCodeAt(n++),c=f<lr.length?lr[f]:-1,!(a==-1||c==-1||(d=a<<2>>>0,d|=(c&48)>>4,s.push(String.fromCharCode(d)),++i>=t||n>=r)||(f=e.charCodeAt(n++),l=f<lr.length?lr[f]:-1,l==-1)||(d=(c&15)<<4>>>0,d|=(l&60)>>2,s.push(String.fromCharCode(d)),++i>=t||n>=r)));)f=e.charCodeAt(n++),u=f<lr.length?lr[f]:-1,d=(l&3)<<6>>>0,d|=u,s.push(String.fromCharCode(d)),++i;var p=[];for(n=0;n<i;n++)p.push(s[n].charCodeAt(0));return p}var ea=16,Dh=10,cE=16,lE=100,Xm=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],Ym=[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946,1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055,3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504,976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462],E2=[1332899944,1700884034,1701343084,1684370003,1668446532,1869963892];function ta(e,t,n,r){var i,s=e[t],a=e[t+1];return s^=n[0],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[1],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[2],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[3],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[4],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[5],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[6],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[7],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[8],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[9],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[10],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[11],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[12],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[13],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[14],i=r[s>>>24],i+=r[256|s>>16&255],i^=r[512|s>>8&255],i+=r[768|s&255],a^=i^n[15],i=r[a>>>24],i+=r[256|a>>16&255],i^=r[512|a>>8&255],i+=r[768|a&255],s^=i^n[16],e[t]=a^n[cE+1],e[t+1]=s,e}function Ki(e,t){for(var n=0,r=0;n<4;++n)r=r<<8|e[t]&255,t=(t+1)%e.length;return{key:r,offp:t}}function Qm(e,t,n){for(var r=0,i=[0,0],s=t.length,a=n.length,c,l=0;l<s;l++)c=Ki(e,r),r=c.offp,t[l]=t[l]^c.key;for(l=0;l<s;l+=2)i=ta(i,0,t,n),t[l]=i[0],t[l+1]=i[1];for(l=0;l<a;l+=2)i=ta(i,0,t,n),n[l]=i[0],n[l+1]=i[1]}function uE(e,t,n,r){for(var i=0,s=[0,0],a=n.length,c=r.length,l,u=0;u<a;u++)l=Ki(t,i),i=l.offp,n[u]=n[u]^l.key;for(i=0,u=0;u<a;u+=2)l=Ki(e,i),i=l.offp,s[0]^=l.key,l=Ki(e,i),i=l.offp,s[1]^=l.key,s=ta(s,0,n,r),n[u]=s[0],n[u+1]=s[1];for(u=0;u<c;u+=2)l=Ki(e,i),i=l.offp,s[0]^=l.key,l=Ki(e,i),i=l.offp,s[1]^=l.key,s=ta(s,0,n,r),r[u]=s[0],r[u+1]=s[1]}function eg(e,t,n,r,i){var s=E2.slice(),a=s.length,c;if(n<4||n>31)if(c=Error("Illegal number of rounds (4-31): "+n),r){cn(r.bind(this,c));return}else throw c;if(t.length!==ea)if(c=Error("Illegal salt length: "+t.length+" != "+ea),r){cn(r.bind(this,c));return}else throw c;n=1<<n>>>0;var l,u,d=0,f;typeof Int32Array=="function"?(l=new Int32Array(Xm),u=new Int32Array(Ym)):(l=Xm.slice(),u=Ym.slice()),uE(t,e,l,u);function p(){if(i&&i(d/n),d<n)for(var _=Date.now();d<n&&(d=d+1,Qm(e,l,u),Qm(t,l,u),!(Date.now()-_>lE)););else{for(d=0;d<64;d++)for(f=0;f<a>>1;f++)ta(s,f<<1,l,u);var g=[];for(d=0;d<a;d++)g.push((s[d]>>24&255)>>>0),g.push((s[d]>>16&255)>>>0),g.push((s[d]>>8&255)>>>0),g.push((s[d]&255)>>>0);if(r){r(null,g);return}else return g}r&&cn(p)}if(typeof r<"u")p();else for(var h;;)if(typeof(h=p())<"u")return h||[]}function xf(e,t,n,r){var i;if(typeof e!="string"||typeof t!="string")if(i=Error("Invalid string / salt: Not a string"),n){cn(n.bind(this,i));return}else throw i;var s,a;if(t.charAt(0)!=="$"||t.charAt(1)!=="2")if(i=Error("Invalid salt version: "+t.substring(0,2)),n){cn(n.bind(this,i));return}else throw i;if(t.charAt(2)==="$")s="\0",a=3;else{if(s=t.charAt(2),s!=="a"&&s!=="b"&&s!=="y"||t.charAt(3)!=="$")if(i=Error("Invalid salt revision: "+t.substring(2,4)),n){cn(n.bind(this,i));return}else throw i;a=4}if(t.charAt(a+2)>"$")if(i=Error("Missing salt rounds"),n){cn(n.bind(this,i));return}else throw i;var c=parseInt(t.substring(a,a+1),10)*10,l=parseInt(t.substring(a+1,a+2),10),u=c+l,d=t.substring(a+3,a+25);e+=s>="a"?"\0":"";var f=aE(e),p=A2(d,ea);function h(_){var g=[];return g.push("$2"),s>="a"&&g.push(s),g.push("$"),u<10&&g.push("0"),g.push(u.toString()),g.push("$"),g.push(hl(p,p.length)),g.push(hl(_,E2.length*4-1)),g.join("")}if(typeof n>"u")return h(eg(f,p,u));eg(f,p,u,function(_,g){_?n(_,null):n(null,h(g))},r)}function dE(e,t){return hl(e,t)}function pE(e,t){return A2(e,t)}const Bo={setRandomFallback:tE,genSaltSync:Lh,genSalt:k2,hashSync:$2,hash:x2,compareSync:nE,compare:rE,getRounds:iE,getSalt:oE,truncates:sE,encodeBase64:dE,decodeBase64:pE},ur={TOO_SHORT:"password_too_short",MISSING_LOWERCASE:"password_missing_lowercase",MISSING_UPPERCASE:"password_missing_uppercase",MISSING_NUMBER:"password_missing_number",MISSING_SPECIAL:"password_missing_special",REUSED:"password_reused",CONTAINS_PERSONAL_INFO:"password_contains_personal_info",CONTAINS_FORBIDDEN_WORD:"password_contains_forbidden_word"};class Sn extends Error{code;params;constructor(t,n,r){super(n),this.code=t,this.params=r,this.name="PasswordPolicyError"}}async function Ea(e,t){const{newPassword:n,userData:r,data:i,tenantId:s,userId:a}=t,c=e.passwordPolicy!==void 0||e.password_complexity_options!==void 0||e.password_history!==void 0||e.password_no_personal_info!==void 0||e.password_dictionary!==void 0,l=c?e.passwordPolicy:"good",u=c?e.password_complexity_options?.min_length:8;if(u&&n.length<u)throw new Sn(ur.TOO_SHORT,`Password must be at least ${u} characters`,{minLength:u});if(l&&l!=="none"&&l==="good"){if(!/[a-z]/.test(n))throw new Sn(ur.MISSING_LOWERCASE,"Password must contain at least one lowercase letter");if(!/[A-Z]/.test(n))throw new Sn(ur.MISSING_UPPERCASE,"Password must contain at least one uppercase letter");if(!/\d/.test(n))throw new Sn(ur.MISSING_NUMBER,"Password must contain at least one number");if(!/[^A-Za-z0-9]/.test(n))throw new Sn(ur.MISSING_SPECIAL,"Password must contain at least one special character")}if(e.password_history?.enable){const d=e.password_history.size||5,f=await i.passwords.list(s,a,d);for(const p of f)if(await Bo.compare(n,p.password))throw new Sn(ur.REUSED,"Password was used recently and cannot be reused",{historySize:d})}if(e.password_no_personal_info?.enable&&r&&[r.email,r.name].filter(Boolean).join(" ").toLowerCase().includes(n.toLowerCase()))throw new Sn(ur.CONTAINS_PERSONAL_INFO,"Password cannot contain personal information like your name or email");if(e.password_dictionary?.enable&&e.password_dictionary.dictionary&&e.password_dictionary.dictionary.some(d=>n.toLowerCase().includes(d.toLowerCase())))throw new Sn(ur.CONTAINS_FORBIDDEN_WORD,"Password contains a forbidden word")}async function Ca(e,t,n){const{connections:r}=await e.connections.list(t,{page:0,per_page:100});return r.find(s=>s.name===n)?.options||{}}async function na(e){return{hash:await Bo.hash(e,10),algorithm:"bcrypt"}}var tg;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(tg||(tg={}));var ng;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(ng||(ng={}));function fE(e){return C2(e,hE,ra.Include)}function Uh(e){return C2(e,_E,ra.None)}function C2(e,t,n){let r="";for(let i=0;i<e.byteLength;i+=3){let s=0,a=0;for(let c=0;c<3&&i+c<e.byteLength;c++)s=s<<8|e[i+c],a+=8;for(let c=0;c<4;c++)a>=6?(r+=t[s>>a-6&63],a-=6):a>0?(r+=t[s<<6-a&63],a=0):n===ra.Include&&(r+="=")}return r}const hE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var ra;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(ra||(ra={}));var rg;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(rg||(rg={}));class mE{uint8(t,n){if(t.byteLength<n+1)throw new TypeError("Insufficient bytes");return t[n]}uint16(t,n){if(t.byteLength<n+2)throw new TypeError("Insufficient bytes");return t[n]<<8|t[n+1]}uint32(t,n){if(t.byteLength<n+4)throw new TypeError("Insufficient bytes");let r=0;for(let i=0;i<4;i++)r|=t[n+i]<<24-i*8;return r}uint64(t,n){if(t.byteLength<n+8)throw new TypeError("Insufficient bytes");let r=0n;for(let i=0;i<8;i++)r|=BigInt(t[n+i])<<BigInt(56-i*8);return r}putUint8(t,n,r){if(t.length<r+1)throw new TypeError("Not enough space");if(n<0||n>255)throw new TypeError("Invalid uint8 value");t[r]=n}putUint16(t,n,r){if(t.length<r+2)throw new TypeError("Not enough space");if(n<0||n>65535)throw new TypeError("Invalid uint16 value");t[r]=n>>8,t[r+1]=n&255}putUint32(t,n,r){if(t.length<r+4)throw new TypeError("Not enough space");if(n<0||n>4294967295)throw new TypeError("Invalid uint32 value");for(let i=0;i<4;i++)t[r+i]=n>>(3-i)*8&255}putUint64(t,n,r){if(t.length<r+8)throw new TypeError("Not enough space");if(n<0||n>18446744073709551615n)throw new TypeError("Invalid uint64 value");for(let i=0;i<8;i++)t[r+i]=Number(n>>BigInt((7-i)*8)&0xffn)}}const ig=new mE;function vn(e,t){return(e<<32-t|e>>>t)>>>0}function gE(e){const t=new yE;return t.update(e),t.digest()}class yE{blockSize=64;size=32;blocks=new Uint8Array(64);currentBlockSize=0;H=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);l=0n;w=new Uint32Array(64);update(t){if(this.l+=BigInt(t.byteLength)*8n,this.currentBlockSize+t.byteLength<64){this.blocks.set(t,this.currentBlockSize),this.currentBlockSize+=t.byteLength;return}let n=0;if(this.currentBlockSize>0){const r=t.slice(0,64-this.currentBlockSize);this.blocks.set(r,this.currentBlockSize),this.process(),n+=r.byteLength,this.currentBlockSize=0}for(;n+64<=t.byteLength;){const r=t.slice(n,n+64);this.blocks.set(r),this.process(),n+=64}if(t.byteLength-n>0){const r=t.slice(n);this.blocks.set(r),this.currentBlockSize=r.byteLength}}digest(){this.blocks[this.currentBlockSize]=128,this.currentBlockSize+=1,64-this.currentBlockSize<8&&(this.blocks.fill(0,this.currentBlockSize),this.process(),this.currentBlockSize=0),this.blocks.fill(0,this.currentBlockSize),ig.putUint64(this.blocks,this.l,this.blockSize-8),this.process();const t=new Uint8Array(32);for(let n=0;n<8;n++)ig.putUint32(t,this.H[n],n*4);return t}process(){for(let u=0;u<16;u++)this.w[u]=(this.blocks[u*4]<<24|this.blocks[u*4+1]<<16|this.blocks[u*4+2]<<8|this.blocks[u*4+3])>>>0;for(let u=16;u<64;u++){const d=(vn(this.w[u-2],17)^vn(this.w[u-2],19)^this.w[u-2]>>>10)>>>0,f=(vn(this.w[u-15],7)^vn(this.w[u-15],18)^this.w[u-15]>>>3)>>>0;this.w[u]=d+this.w[u-7]+f+this.w[u-16]|0}let t=this.H[0],n=this.H[1],r=this.H[2],i=this.H[3],s=this.H[4],a=this.H[5],c=this.H[6],l=this.H[7];for(let u=0;u<64;u++){const d=(vn(s,6)^vn(s,11)^vn(s,25))>>>0,f=(s&a^~s&c)>>>0,p=l+d+f+bE[u]+this.w[u]|0,h=(vn(t,2)^vn(t,13)^vn(t,22))>>>0,_=(t&n^t&r^n&r)>>>0,g=h+_|0;l=c,c=a,a=s,s=i+p|0,i=r,r=n,n=t,t=p+g|0}this.H[0]=t+this.H[0]|0,this.H[1]=n+this.H[1]|0,this.H[2]=r+this.H[2]|0,this.H[3]=i+this.H[3]|0,this.H[4]=s+this.H[4]|0,this.H[5]=a+this.H[5]|0,this.H[6]=c+this.H[6]|0,this.H[7]=l+this.H[7]|0}}const bE=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);new BigUint64Array([0x428a2f98d728ae22n,0x7137449123ef65cdn,0xb5c0fbcfec4d3b2fn,0xe9b5dba58189dbbcn,0x3956c25bf348b538n,0x59f111f1b605d019n,0x923f82a4af194f9bn,0xab1c5ed5da6d8118n,0xd807aa98a3030242n,0x12835b0145706fben,0x243185be4ee4b28cn,0x550c7dc3d5ffb4e2n,0x72be5d74f27b896fn,0x80deb1fe3b1696b1n,0x9bdc06a725c71235n,0xc19bf174cf692694n,0xe49b69c19ef14ad2n,0xefbe4786384f25e3n,0x0fc19dc68b8cd5b5n,0x240ca1cc77ac9c65n,0x2de92c6f592b0275n,0x4a7484aa6ea6e483n,0x5cb0a9dcbd41fbd4n,0x76f988da831153b5n,0x983e5152ee66dfabn,0xa831c66d2db43210n,0xb00327c898fb213fn,0xbf597fc7beef0ee4n,0xc6e00bf33da88fc2n,0xd5a79147930aa725n,0x06ca6351e003826fn,0x142929670a0e6e70n,0x27b70a8546d22ffcn,0x2e1b21385c26c926n,0x4d2c6dfc5ac42aedn,0x53380d139d95b3dfn,0x650a73548baf63den,0x766a0abb3c77b2a8n,0x81c2c92e47edaee6n,0x92722c851482353bn,0xa2bfe8a14cf10364n,0xa81a664bbc423001n,0xc24b8b70d0f89791n,0xc76c51a30654be30n,0xd192e819d6ef5218n,0xd69906245565a910n,0xf40e35855771202an,0x106aa07032bbd1b8n,0x19a4c116b8d2d0c8n,0x1e376c085141ab53n,0x2748774cdf8eeb99n,0x34b0bcb5e19b48a8n,0x391c0cb3c5c95a63n,0x4ed8aa4ae3418acbn,0x5b9cca4f7763e373n,0x682e6ff3d6b2b8a3n,0x748f82ee5defb2fcn,0x78a5636f43172f60n,0x84c87814a1f0ab72n,0x8cc702081a6439ecn,0x90befffa23631e28n,0xa4506cebde82bde9n,0xbef9a3f7b2c67915n,0xc67178f2e372532bn,0xca273eceea26619cn,0xd186b8c721c0c207n,0xeada7dd6cde0eb1en,0xf57d4f7fee6ed178n,0x06f067aa72176fban,0x0a637dc5a2c898a6n,0x113f9804bef90daen,0x1b710b35131c471bn,0x28db77f523047d84n,0x32caab7b40c72493n,0x3c9ebe0a15c9bebcn,0x431d67c49c100d4cn,0x4cc5d4becb3e42b6n,0x597f299cfc657e2an,0x5fcb6fab3ad6faecn,0x6c44198c4a475817n]);class I2{data;constructor(t){this.data=t}tokenType(){if("token_type"in this.data&&typeof this.data.token_type=="string")return this.data.token_type;throw new Error("Missing or invalid 'token_type' field")}accessToken(){if("access_token"in this.data&&typeof this.data.access_token=="string")return this.data.access_token;throw new Error("Missing or invalid 'access_token' field")}accessTokenExpiresInSeconds(){if("expires_in"in this.data&&typeof this.data.expires_in=="number")return this.data.expires_in;throw new Error("Missing or invalid 'expires_in' field")}accessTokenExpiresAt(){return new Date(Date.now()+this.accessTokenExpiresInSeconds()*1e3)}hasRefreshToken(){return"refresh_token"in this.data&&typeof this.data.refresh_token=="string"}refreshToken(){if("refresh_token"in this.data&&typeof this.data.refresh_token=="string")return this.data.refresh_token;throw new Error("Missing or invalid 'refresh_token' field")}hasScopes(){return"scope"in this.data&&typeof this.data.scope=="string"}scopes(){if("scope"in this.data&&typeof this.data.scope=="string")return this.data.scope.split(" ");throw new Error("Missing or invalid 'scope' field")}idToken(){if("id_token"in this.data&&typeof this.data.id_token=="string")return this.data.id_token;throw new Error("Missing or invalid field 'id_token'")}}function j2(e){const t=gE(new TextEncoder().encode(e));return Uh(t)}function Eu(){const e=new Uint8Array(32);return crypto.getRandomValues(e),Uh(e)}function N2(){const e=new Uint8Array(32);return crypto.getRandomValues(e),Uh(e)}function vE(e,t){if(t.length!==1)throw new TypeError("Invalid character string");let n=0;for(;n<e.length&&e[n]===t;)n++;return e.slice(n)}function og(e,t){if(t.length!==1)throw new TypeError("Invalid character string");let n=e.length;for(;n>0&&e[n-1]===t;)n--;return e.slice(0,n)}function sg(e,...t){let n=og(e,"/");for(const r of t)n=og(n,"/")+"/"+vE(r,"/");return n}function Zn(e,t){const n=new TextEncoder().encode(t.toString()),r=new Request(e,{method:"POST",body:n});return r.headers.set("Content-Type","application/x-www-form-urlencoded"),r.headers.set("Accept","application/json"),r.headers.set("User-Agent","arctic"),r.headers.set("Content-Length",n.byteLength.toString()),r}function si(e,t){const n=new TextEncoder().encode(`${e}:${t}`);return fE(n)}async function bo(e){let t;try{t=await fetch(e)}catch(n){throw new Mh(n)}if(t.status===400||t.status===401){let n;try{n=await t.json()}catch{throw new co(t.status)}if(typeof n!="object"||n===null)throw new kr(t.status,n);let r;try{r=Bh(n)}catch{throw new kr(t.status,n)}throw r}if(t.status===200){let n;try{n=await t.json()}catch{throw new co(t.status)}if(typeof n!="object"||n===null)throw new kr(t.status,n);return new I2(n)}throw t.body!==null&&await t.body.cancel(),new co(t.status)}async function wE(e){let t;try{t=await fetch(e)}catch(n){throw new Mh(n)}if(t.status===400||t.status===401){let n;try{n=await t.json()}catch{throw new kr(t.status,null)}if(typeof n!="object"||n===null)throw new kr(t.status,n);let r;try{r=Bh(n)}catch{throw new kr(t.status,n)}throw r}if(t.status===200){t.body!==null&&await t.body.cancel();return}throw t.body!==null&&await t.body.cancel(),new co(t.status)}function Bh(e){let t;if("error"in e&&typeof e.error=="string")t=e.error;else throw new Error("Invalid error response");let n=null,r=null,i=null;if("error_description"in e){if(typeof e.error_description!="string")throw new Error("Invalid data");n=e.error_description}if("error_uri"in e){if(typeof e.error_uri!="string")throw new Error("Invalid data");r=e.error_uri}if("state"in e){if(typeof e.state!="string")throw new Error("Invalid data");i=e.state}return new kE(t,n,r,i)}class Mh extends Error{constructor(t){super("Failed to send request",{cause:t})}}class kE extends Error{code;description;uri;state;constructor(t,n,r,i){super(`OAuth request error: ${t}`),this.code=t,this.description=n,this.uri=r,this.state=i}}class co extends Error{status;constructor(t){super("Unexpected error response"),this.status=t}}class kr extends Error{status;data;constructor(t,n){super("Unexpected error response body"),this.status=t,this.data=n}}class Ni{clientId;clientPassword;redirectURI;constructor(t,n,r){this.clientId=t,this.clientPassword=n,this.redirectURI=r}createAuthorizationURL(t,n,r){const i=new URL(t);return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",this.clientId),this.redirectURI!==null&&i.searchParams.set("redirect_uri",this.redirectURI),i.searchParams.set("state",n),r.length>0&&i.searchParams.set("scope",r.join(" ")),i}createAuthorizationURLWithPKCE(t,n,r,i,s){const a=new URL(t);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",this.clientId),this.redirectURI!==null&&a.searchParams.set("redirect_uri",this.redirectURI),a.searchParams.set("state",n),r===fi.S256){const c=j2(i);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",c)}else r===fi.Plain&&(a.searchParams.set("code_challenge_method","plain"),a.searchParams.set("code_challenge",i));return s.length>0&&a.searchParams.set("scope",s.join(" ")),a}async validateAuthorizationCode(t,n,r){const i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",n),this.redirectURI!==null&&i.set("redirect_uri",this.redirectURI),r!==null&&i.set("code_verifier",r),this.clientPassword===null&&i.set("client_id",this.clientId);const s=Zn(t,i);if(this.clientPassword!==null){const c=si(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await bo(s)}async refreshAccessToken(t,n,r){const i=new URLSearchParams;i.set("grant_type","refresh_token"),i.set("refresh_token",n),this.clientPassword===null&&i.set("client_id",this.clientId),r.length>0&&i.set("scope",r.join(" "));const s=Zn(t,i);if(this.clientPassword!==null){const c=si(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await bo(s)}async revokeToken(t,n){const r=new URLSearchParams;r.set("token",n),this.clientPassword===null&&r.set("client_id",this.clientId);const i=Zn(t,r);if(this.clientPassword!==null){const s=si(this.clientId,this.clientPassword);i.headers.set("Authorization",`Basic ${s}`)}await wE(i)}}var fi;(function(e){e[e.S256=0]="S256",e[e.Plain=1]="Plain"})(fi||(fi={}));var ag;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(ag||(ag={}));var cg;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(cg||(cg={}));function Us(e){return $E(e,xE,_l.None)}function $E(e,t,n){let r="";for(let i=0;i<e.byteLength;i+=3){let s=0,a=0;for(let c=0;c<3&&i+c<e.byteLength;c++)s=s<<8|e[i+c],a+=8;for(let c=0;c<4;c++)a>=6?(r+=t[s>>a-6&63],a-=6):a>0?(r+=t[s<<6-a&63],a=0):n===_l.Include&&(r+="=")}return r}const xE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var _l;(function(e){e[e.Include=0]="Include",e[e.None=1]="None"})(_l||(_l={}));var lg;(function(e){e[e.Required=0]="Required",e[e.Ignore=1]="Ignore"})(lg||(lg={}));function SE(e,t,n){const r=Us(new TextEncoder().encode(e)),i=Us(new TextEncoder().encode(t)),s=Us(n);return r+"."+i+"."+s}function zE(e,t){const n=Us(new TextEncoder().encode(e)),r=Us(new TextEncoder().encode(t)),i=n+"."+r;return new TextEncoder().encode(i)}const AE="https://appleid.apple.com/auth/authorize",EE="https://appleid.apple.com/auth/token";class T2{clientId;teamId;keyId;pkcs8PrivateKey;redirectURI;constructor(t,n,r,i,s){this.clientId=t,this.teamId=n,this.keyId=r,this.pkcs8PrivateKey=i,this.redirectURI=s}createAuthorizationURL(t,n){const r=new URL(AE);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",t),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(t){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId);const r=await this.createClientSecret();n.set("client_secret",r);const i=Zn(EE,n);return await bo(i)}async createClientSecret(){const t=await crypto.subtle.importKey("pkcs8",this.pkcs8PrivateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),n=Math.floor(Date.now()/1e3),r=JSON.stringify({typ:"JWT",alg:"ES256",kid:this.keyId}),i=JSON.stringify({iss:this.teamId,exp:n+300,aud:["https://appleid.apple.com"],sub:this.clientId,iat:n}),s=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},t,zE(r,i)));return SE(r,i,s)}}const CE="https://www.facebook.com/v16.0/dialog/oauth",IE="https://graph.facebook.com/v16.0/oauth/access_token";class P2{clientId;clientSecret;redirectURI;constructor(t,n,r){this.clientId=t,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(t,n){const r=new URL(CE);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",t),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(t){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId),n.set("client_secret",this.clientSecret);const r=Zn(IE,n);return await bo(r)}}const jE="https://github.com/login/oauth/authorize",ug="https://github.com/login/oauth/access_token";class O2{clientId;clientSecret;redirectURI;constructor(t,n,r){this.clientId=t,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(t,n){const r=new URL(jE);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",t),n.length>0&&r.searchParams.set("scope",n.join(" ")),this.redirectURI!==null&&r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(t){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t),this.redirectURI!==null&&n.set("redirect_uri",this.redirectURI);const r=Zn(ug,n),i=si(this.clientId,this.clientSecret);return r.headers.set("Authorization",`Basic ${i}`),await dg(r)}async refreshAccessToken(t){const n=new URLSearchParams;n.set("grant_type","refresh_token"),n.set("refresh_token",t);const r=Zn(ug,n),i=si(this.clientId,this.clientSecret);return r.headers.set("Authorization",`Basic ${i}`),await dg(r)}}async function dg(e){let t;try{t=await fetch(e)}catch(i){throw new Mh(i)}if(t.status!==200)throw t.body!==null&&await t.body.cancel(),new co(t.status);let n;try{n=await t.json()}catch{throw new co(t.status)}if(typeof n!="object"||n===null)throw new kr(t.status,n);if("error"in n&&typeof n.error=="string"){let i;try{i=Bh(n)}catch{throw new kr(t.status,n)}throw i}return new I2(n)}const NE="https://accounts.google.com/o/oauth2/v2/auth",pg="https://oauth2.googleapis.com/token",TE="https://oauth2.googleapis.com/revoke";let R2=class{client;constructor(t,n,r){this.client=new Ni(t,n,r)}createAuthorizationURL(t,n,r){return this.client.createAuthorizationURLWithPKCE(NE,t,fi.S256,n,r)}async validateAuthorizationCode(t,n){return await this.client.validateAuthorizationCode(pg,t,n)}async refreshAccessToken(t){return await this.client.refreshAccessToken(pg,t,[])}async revokeToken(t){await this.client.revokeToken(TE,t)}};class L2{authorizationEndpoint;tokenEndpoint;clientId;clientSecret;redirectURI;constructor(t,n,r,i){this.authorizationEndpoint=sg("https://login.microsoftonline.com",t,"/oauth2/v2.0/authorize"),this.tokenEndpoint=sg("https://login.microsoftonline.com",t,"/oauth2/v2.0/token"),this.clientId=n,this.clientSecret=r,this.redirectURI=i}createAuthorizationURL(t,n,r){const i=new URL(this.authorizationEndpoint);i.searchParams.set("response_type","code"),i.searchParams.set("client_id",this.clientId),i.searchParams.set("redirect_uri",this.redirectURI),i.searchParams.set("state",t);const s=j2(n);return i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("code_challenge",s),r.length>0&&i.searchParams.set("scope",r.join(" ")),i}async validateAuthorizationCode(t,n){const r=new URLSearchParams;r.set("grant_type","authorization_code"),r.set("code",t),r.set("redirect_uri",this.redirectURI),r.set("code_verifier",n),this.clientSecret===null&&r.set("client_id",this.clientId);const i=Zn(this.tokenEndpoint,r);if(this.clientSecret!==null){const a=si(this.clientId,this.clientSecret);i.headers.set("Authorization",`Basic ${a}`)}else i.headers.set("Origin","arctic");return await bo(i)}async refreshAccessToken(t,n){const r=new URLSearchParams;r.set("grant_type","refresh_token"),r.set("refresh_token",t),this.clientSecret===null&&r.set("client_id",this.clientId),n.length>0&&r.set("scope",n.join(" "));const i=Zn(this.tokenEndpoint,r);if(this.clientSecret!==null){const a=si(this.clientId,this.clientSecret);i.headers.set("Authorization",`Basic ${a}`)}else i.headers.set("Origin","arctic");return await bo(i)}}const Mo=o.z.object({iss:o.z.string().url(),sub:o.z.string(),aud:o.z.string(),exp:o.z.number(),email:o.z.string().optional(),given_name:o.z.string().optional(),family_name:o.z.string().optional(),name:o.z.string().optional(),iat:o.z.number(),auth_time:o.z.number().optional(),nonce:o.z.string().optional(),acr:o.z.string().optional(),amr:o.z.array(o.z.string()).optional(),azp:o.z.string().optional(),at_hash:o.z.string().optional(),c_hash:o.z.string().optional()}).passthrough();Mo.omit({iat:!0,auth_time:!0,nonce:!0,acr:!0,amr:!0,azp:!0,at_hash:!0,c_hash:!0});const PE="Apple",OE="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20fill%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M45%200H0V45H45V0Z%22%20fill%3D%22white%22%2F%3E%3Cpath%20d%3D%22M23.5344%2010.3846C25.5313%2010.3846%2028.0344%209.01144%2029.525%207.18055C30.875%205.5213%2031.8594%203.20407%2031.8594%200.886839C31.8594%200.572154%2031.8313%200.25747%2031.775%200C29.5531%200.0858233%2026.8813%201.51621%2025.2781%203.43293C24.0125%204.89193%2022.8594%207.18055%2022.8594%209.52638C22.8594%209.86968%2022.9156%2010.213%2022.9438%2010.3274C23.0844%2010.356%2023.3094%2010.3846%2023.5344%2010.3846ZM16.5031%2045C19.2313%2045%2020.4406%2043.1405%2023.8438%2043.1405C27.3031%2043.1405%2028.0625%2044.9428%2031.1%2044.9428C34.0813%2044.9428%2036.0781%2042.1392%2037.9625%2039.3929C40.0719%2036.246%2040.9438%2033.1564%2041%2033.0134C40.8031%2032.9561%2035.0938%2030.5817%2035.0938%2023.9161C35.0938%2018.1373%2039.5938%2015.534%2039.8469%2015.3338C36.8656%2010.9854%2032.3375%2010.8709%2031.1%2010.8709C27.7531%2010.8709%2025.025%2012.9307%2023.3094%2012.9307C21.4531%2012.9307%2019.0063%2010.9854%2016.1094%2010.9854C10.5969%2010.9854%205%2015.6198%205%2024.3738C5%2029.8093%207.08125%2035.5594%209.64063%2039.2784C11.8344%2042.4253%2013.7469%2045%2016.5031%2045Z%22%20fill%3D%22black%22%2F%3E%3C%2Fsvg%3E";function D2(e){const{options:t}=e;if(!t||!t.client_id||!t.team_id||!t.kid||!t.app_secret)throw new Error("Missing required Apple authentication parameters");const n=Buffer.from(t.app_secret,"utf-8"),r=n.toString().replace(/-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----|\s/g,""),i=Uint8Array.from(Buffer.from(r,"base64"));return n.fill(0),{options:t,keyArray:i}}async function RE(e,t){const{options:n,keyArray:r}=D2(t),i=`${Le(e.env)}callback`,s=new T2(n.client_id,n.team_id,n.kid,r,i),a=Oe(),c=await s.createAuthorizationURL(a,n.scope?.split(" ")||["name","email"]);return(n.scope?.split(" ")||["name","email"]).some(u=>["email","name"].includes(u))&&c.searchParams.set("response_mode","form_post"),{redirectUrl:c.href,code:a}}async function LE(e,t,n){const{options:r,keyArray:i}=D2(t),a=await new T2(r.client_id,r.team_id,r.kid,i,`${Le(e.env)}callback`).validateAuthorizationCode(n),c=za(a.idToken());if(!c)throw new Error("Invalid ID token");const l=Mo.parse(c.payload);return{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture,locale:l.locale}}const DE=Object.freeze(Object.defineProperty({__proto__:null,displayName:PE,getRedirect:RE,logoDataUri:OE,validateAuthorizationCodeAndGetUser:LE},Symbol.toStringTag,{value:"Module"})),UE="Facebook",BE="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M45%2022.5C45%2010.0736%2034.9264%200%2022.5%200C10.0736%200%200%2010.0736%200%2022.5C0%2033.7031%208.23242%2042.9785%2019.0039%2044.6953V28.9746H13.2861V22.5H19.0039V17.5391C19.0039%2011.8945%2022.3828%208.75977%2027.5391%208.75977C29.9658%208.75977%2032.5049%209.19922%2032.5049%209.19922V14.7656H29.7012C26.9414%2014.7656%2026.0156%2016.4824%2026.0156%2018.2432V22.5H32.2412L31.2012%2028.9746H26.0156V44.6953C36.7871%2042.9785%2045%2033.7031%2045%2022.5Z%22%20fill%3D%22%231877F2%22%2F%3E%3Cpath%20d%3D%22M31.2012%2028.9746L32.2412%2022.5H26.0156V18.2432C26.0156%2016.4824%2026.9414%2014.7656%2029.7012%2014.7656H32.5049V9.19922C32.5049%209.19922%2029.9658%208.75977%2027.5391%208.75977C22.3828%208.75977%2019.0039%2011.8945%2019.0039%2017.5391V22.5H13.2861V28.9746H19.0039V44.6953C20.1562%2044.8984%2021.3203%2045%2022.5%2045C23.6797%2045%2024.8438%2044.8984%2026.0156%2044.6953V28.9746H31.2012Z%22%20fill%3D%22white%22%2F%3E%3C%2Fsvg%3E";async function ME(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required authentication parameters");const r=`${Le(e.env)}callback`,i=new P2(n.client_id,n.client_secret,r),s=Oe();return{redirectUrl:i.createAuthorizationURL(s,n.scope?.split(" ")||["email"]).href,code:s}}async function qE(e,t,n){const{options:r}=t;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new P2(r.client_id,r.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode(n),a=await fetch("https://graph.facebook.com/v22.0/me?fields=id,email,name",{headers:{Authorization:`Bearer ${s.accessToken()}`}});if(!a.ok)throw new Error("Failed to fetch user info");const c=await a.json();return e.set("log",`Userinfo: ${JSON.stringify(c)}`),{sub:c.id,email:c.email,name:c.name}}const FE=Object.freeze(Object.defineProperty({__proto__:null,displayName:UE,getRedirect:ME,logoDataUri:BE,validateAuthorizationCodeAndGetUser:qE},Symbol.toStringTag,{value:"Module"})),HE="Google",VE=!0,KE="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M44.1035%2023.0123C44.1054%2021.4791%2043.9758%2019.9486%2043.716%2018.4375H22.498V27.1028H34.6507C34.4021%2028.4868%2033.8757%2029.8061%2033.1034%2030.9812C32.3311%2032.1562%2031.3289%2033.1628%2030.1571%2033.9401V39.5649H37.41C41.6567%2035.6494%2044.1035%2029.859%2044.1035%2023.0123Z%22%20fill%3D%22%234285F4%22%2F%3E%3Cpath%20d%3D%22M22.4982%2044.9997C28.5698%2044.9997%2033.6821%2043.0061%2037.4101%2039.5687L30.1573%2033.9439C28.1386%2035.3126%2025.5387%2036.0938%2022.4982%2036.0938C16.6296%2036.0938%2011.6485%2032.1377%209.86736%2026.8066H2.39575V32.6033C4.26839%2036.3297%207.13989%2039.4622%2010.6896%2041.6512C14.2394%2043.8402%2018.3277%2044.9995%2022.4982%2044.9997Z%22%20fill%3D%22%2334A853%22%2F%3E%3Cpath%20d%3D%22M9.86737%2026.8073C8.92572%2024.0138%208.92572%2020.9886%209.86737%2018.1951V12.3984H2.39576C0.820432%2015.5332%200%2018.9929%200%2022.5012C0%2026.0095%200.820432%2029.4692%202.39576%2032.604L9.86737%2026.8073Z%22%20fill%3D%22%23FBBC04%22%2F%3E%3Cpath%20d%3D%22M22.4982%208.90741C25.7068%208.85499%2028.8071%2010.0673%2031.1291%2012.2823L37.5507%205.86064C33.4788%202.03602%2028.0843%20-0.0637686%2022.4982%200.00147616C18.3277%200.00166623%2014.2394%201.16098%2010.6896%203.34999C7.13989%205.539%204.26839%208.67155%202.39575%2012.3979L9.86736%2018.1946C11.6485%2012.8635%2016.6296%208.90741%2022.4982%208.90741Z%22%20fill%3D%22%23EA4335%22%2F%3E%3C%2Fsvg%3E";async function GE(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required Google authentication parameters");const r=`${Le(e.env)}callback`,i=new R2(n.client_id,n.client_secret,r),s=Oe(),a=Eu();return{redirectUrl:i.createAuthorizationURL(s,a,n.scope?.split(" ")??["email","profile"]).href,code:s,codeVerifier:a}}async function WE(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.client_secret||!r)throw new Error("Missing required authentication parameters");const a=await new R2(i.client_id,i.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode(n,r),c=za(a.idToken());if(!c)throw new Error("Invalid ID token");const l=Mo.parse(c.payload);return{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture,locale:l.locale}}const JE=Object.freeze(Object.defineProperty({__proto__:null,disableEmbeddedBrowsers:VE,displayName:HE,getRedirect:GE,logoDataUri:KE,validateAuthorizationCodeAndGetUser:WE},Symbol.toStringTag,{value:"Module"})),ZE="Vipps",XE="data:image/svg+xml,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2048%2048%22%20width%3D%2245%22%20height%3D%2245%22%3E%3Cpath%20fill%3D%22%23FF5B24%22%20d%3D%22M3.5%2C8h41c1.9%2C0%2C3.5%2C1.6%2C3.5%2C3.5v25c0%2C1.9-1.6%2C3.5-3.5%2C3.5h-41C1.6%2C40%2C0%2C38.4%2C0%2C36.5v-25C0%2C9.6%2C1.6%2C8%2C3.5%2C8z%22%2F%3E%3Cpath%20fill-rule%3D%22evenodd%22%20clip-rule%3D%22evenodd%22%20fill%3D%22%23FFFFFF%22%20d%3D%22M27.9%2C20.3c1.4%2C0%2C2.6-1%2C2.6-2.5h0c0-1.5-1.2-2.5-2.6-2.5c-1.4%2C0-2.6%2C1-2.6%2C2.5C25.3%2C19.2%2C26.5%2C20.3%2C27.9%2C20.3z%20M31.2%2C24.4c-1.7%2C2.2-3.5%2C3.8-6.7%2C3.8h0c-3.2%2C0-5.8-2-7.7-4.8c-0.8-1.2-2-1.4-2.9-0.8c-0.8%2C0.6-1%2C1.8-0.3%2C2.9%20c2.7%2C4.1%2C6.5%2C6.6%2C10.9%2C6.6c4%2C0%2C7.2-2%2C9.6-5.2c0.9-1.2%2C0.9-2.5%2C0-3.1C33.3%2C22.9%2C32.1%2C23.2%2C31.2%2C24.4z%22%2F%3E%3C%2Fsvg%3E";async function YE(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required authentication parameters");const r=new Ni(n.client_id,n.client_secret,`${Le(e.env)}callback`),i=Oe(),s=r.createAuthorizationURL("https://api.vipps.no/access-management-1.0/access/oauth2/auth",i,n.scope?.split(" ")||["openid","email","phoneNumber","name","address","birthDate"]);return s.searchParams.set("response_type","code"),s.searchParams.set("response_mode","query"),{redirectUrl:s.href,code:i}}async function QE(e,t,n){const{options:r}=t;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new Ni(r.client_id,r.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode("https://api.vipps.no/access-management-1.0/access/oauth2/token",n,null),a=za(s.idToken());if(!a)throw new Error("Invalid ID token");const c=Mo.parse(a.payload);if(typeof c.msn!="string")throw new Error("msn not available in id token");const l=await fetch("https://api.vipps.no/vipps-userinfo-api/userinfo",{headers:{Authorization:`Bearer ${s.accessToken()}`,"Merchant-Serial-Number":c.msn}});if(!l.ok)throw new W(400,{message:"Failed to get user from vipps"});return await l.json()}const e7=Object.freeze(Object.defineProperty({__proto__:null,displayName:ZE,getRedirect:YE,logoDataUri:XE,validateAuthorizationCodeAndGetUser:QE},Symbol.toStringTag,{value:"Module"})),t7="GitHub",n7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill-rule%3D%22evenodd%22%20clip-rule%3D%22evenodd%22%20d%3D%22M22.5%200C10.074%200%200%2010.335%200%2023.077C0%2033.266%206.444%2041.895%2015.39%2044.955C16.515%2045.165%2016.935%2044.46%2016.935%2043.857C16.935%2043.32%2016.92%2041.865%2016.905%2039.99C10.65%2041.355%209.33%2036.99%209.33%2036.99C8.31%2034.32%206.825%2033.615%206.825%2033.615C4.77%2032.205%206.975%2032.235%206.975%2032.235C9.24%2032.385%2010.425%2034.59%2010.425%2034.59C12.45%2038.13%2015.75%2037.125%2017.01%2036.555C17.22%2035.07%2017.82%2034.065%2018.48%2033.51C13.455%2032.94%208.19%2030.93%208.19%2022.035C8.19%2019.5%209.075%2017.43%2010.47%2015.81C10.23%2015.24%209.435%2012.87%2010.695%209.66C10.695%209.66%2012.585%209.045%2016.875%2012.06C18.675%2011.565%2020.595%2011.31%2022.5%2011.31C24.405%2011.31%2026.325%2011.565%2028.125%2012.06C32.415%209.045%2034.305%209.66%2034.305%209.66C35.565%2012.87%2034.77%2015.24%2034.53%2015.81C35.925%2017.43%2036.81%2019.5%2036.81%2022.035C36.81%2030.96%2031.53%2032.925%2026.49%2033.48C27.33%2034.2%2028.095%2035.625%2028.095%2037.815C28.095%2040.95%2028.065%2043.47%2028.065%2043.857C28.065%2044.46%2028.485%2045.18%2029.625%2044.955C38.571%2041.88%2045%2033.252%2045%2023.077C45%2010.335%2034.926%200%2022.5%200Z%22%20fill%3D%22%23181717%22%2F%3E%3C%2Fsvg%3E";async function r7(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required GitHub authentication parameters");const r=`${Le(e.env)}callback`,i=new O2(n.client_id,n.client_secret,r),s=Oe();return{redirectUrl:i.createAuthorizationURL(s,n.scope?.split(" ")||["user:email"]).href,code:s}}async function i7(e,t,n){const{options:r}=t;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new O2(r.client_id,r.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode(n),a=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${s.accessToken()}`,"User-Agent":"AuthHero"}});if(!a.ok)throw new Error("Failed to fetch user info");const c=await a.json(),l=await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${s.accessToken()}`,"User-Agent":"AuthHero"}});let u=c.email;if(l.ok){const d=await l.json(),f=d.find(p=>p.primary&&p.verified)||d.find(p=>p.verified);f&&(u=f.email)}return e.set("log",`GitHub user: ${JSON.stringify(c)}`),{sub:c.id.toString(),email:u,name:c.name,given_name:c.name?.split(" ")[0],family_name:c.name?.split(" ").slice(1).join(" "),picture:c.avatar_url}}const o7=Object.freeze(Object.defineProperty({__proto__:null,displayName:t7,getRedirect:r7,logoDataUri:n7,validateAuthorizationCodeAndGetUser:i7},Symbol.toStringTag,{value:"Module"})),s7="Microsoft",a7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill%3D%22%23F25022%22%20d%3D%22M0%200H21.43V21.43H0V0Z%22%2F%3E%3Cpath%20fill%3D%22%237FBA00%22%20d%3D%22M23.57%200H45V21.43H23.57V0Z%22%2F%3E%3Cpath%20fill%3D%22%2300A4EF%22%20d%3D%22M0%2023.57H21.43V45H0V23.57Z%22%2F%3E%3Cpath%20fill%3D%22%23FFB900%22%20d%3D%22M23.57%2023.57H45V45H23.57V23.57Z%22%2F%3E%3C%2Fsvg%3E";async function c7(e,t){const{options:n}=t;if(!n?.client_id||!n.client_secret)throw new Error("Missing required Microsoft authentication parameters");const r=`${Le(e.env)}callback`,i=n.realms||"common",s=new L2(i,n.client_id,n.client_secret,r),a=Oe(),c=Eu();return{redirectUrl:s.createAuthorizationURL(a,c,n.scope?.split(" ")||["openid","profile","email"]).href,code:a,codeVerifier:c}}async function l7(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.client_secret||!r)throw new Error("Missing required authentication parameters");const s=i.realms||"common",c=await new L2(s,i.client_id,i.client_secret,`${Le(e.env)}callback`).validateAuthorizationCode(n,r),l=za(c.idToken());if(!l)throw new Error("Invalid ID token");const u=Mo.parse(l.payload);return e.set("log",`Microsoft user: ${JSON.stringify(u)}`),{sub:u.sub,email:u.email,given_name:u.given_name,family_name:u.family_name,name:u.name,picture:u.picture}}const u7=Object.freeze(Object.defineProperty({__proto__:null,displayName:s7,getRedirect:c7,logoDataUri:a7,validateAuthorizationCodeAndGetUser:l7},Symbol.toStringTag,{value:"Module"})),d7="OpenID Connect",p7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M22.5%200C10.074%200%200%2010.074%200%2022.5S10.074%2045%2022.5%2045%2045%2034.926%2045%2022.5%2034.926%200%2022.5%200zm0%2040.5c-9.941%200-18-8.059-18-18s8.059-18%2018-18%2018%208.059%2018%2018-8.059%2018-18%2018z%22%20fill%3D%22%23F7931E%22%2F%3E%3Cpath%20d%3D%22M22.5%209c-7.456%200-13.5%206.044-13.5%2013.5S15.044%2036%2022.5%2036%2036%2029.956%2036%2022.5%2029.956%209%2022.5%209zm0%2022.5c-4.971%200-9-4.029-9-9s4.029-9%209-9%209%204.029%209%209-4.029%209-9%209z%22%20fill%3D%22%23F7931E%22%2F%3E%3C%2Fsvg%3E";async function f7(e,t){const{options:n}=t;if(!n?.client_id||!n.authorization_endpoint)throw new Error("Missing required OIDC authentication parameters");const r=`${Le(e.env)}callback`,i=new Ni(n.client_id,n.client_secret||null,r),s=N2(),a=Eu(),c=n.scope?.split(" ")??["openid","profile","email"];return{redirectUrl:i.createAuthorizationURLWithPKCE(n.authorization_endpoint,s,fi.S256,a,c).href,code:s,codeVerifier:a}}async function h7(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.token_endpoint)throw new Error("Missing required authentication parameters");const s=`${Le(e.env)}callback`,c=await new Ni(i.client_id,i.client_secret||null,s).validateAuthorizationCode(i.token_endpoint,n,r||null);if(c.data.id_token){const u=za(c.idToken());if(u?.payload){const d=Mo.passthrough().parse(u.payload);return{sub:d.sub,email:d.email,given_name:d.given_name,family_name:d.family_name,name:d.name}}}if(i.userinfo_endpoint){const u=await fetch(i.userinfo_endpoint,{headers:{Authorization:`Bearer ${c.accessToken()}`}});if(!u.ok)throw new Error("Failed to fetch user info");const d=await u.json();if(!d.sub)throw new Error("Unable to get user identifier: userinfo response missing sub");return{sub:d.sub,email:d.email,given_name:d.given_name,family_name:d.family_name,name:d.name}}throw new Error("Unable to get user information: no ID token or userinfo endpoint")}const _7=Object.freeze(Object.defineProperty({__proto__:null,displayName:d7,getRedirect:f7,logoDataUri:p7,validateAuthorizationCodeAndGetUser:h7},Symbol.toStringTag,{value:"Module"})),m7="OAuth 2.0",g7="data:image/svg+xml,%3Csvg%20width%3D%2245%22%20height%3D%2245%22%20viewBox%3D%220%200%2045%2045%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M22.5%200C14.492%200%208%206.492%208%2014.5V18H5v22h35V18h-3v-3.5C37%206.492%2030.508%200%2022.5%200zm0%204c5.799%200%2010.5%204.701%2010.5%2010.5V18h-21v-3.5C12%208.701%2016.701%204%2022.5%204z%22%20fill%3D%22%236B7280%22%2F%3E%3Ccircle%20cx%3D%2222.5%22%20cy%3D%2229%22%20r%3D%223%22%20fill%3D%22%236B7280%22%2F%3E%3C%2Fsvg%3E";async function y7(e,t){const{options:n}=t;if(!n?.client_id||!n.authorization_endpoint)throw new Error("Missing required OAuth2 authentication parameters");const r=`${Le(e.env)}callback`,i=new Ni(n.client_id,n.client_secret||null,r),s=N2(),a=Eu(),c=n.scope?.split(" ")??[];return{redirectUrl:i.createAuthorizationURLWithPKCE(n.authorization_endpoint,s,fi.S256,a,c).href,code:s,codeVerifier:a}}async function b7(e,t,n,r){const{options:i}=t;if(!i?.client_id||!i.token_endpoint)throw new Error("Missing required authentication parameters");const s=`${Le(e.env)}callback`,c=await new Ni(i.client_id,i.client_secret||null,s).validateAuthorizationCode(i.token_endpoint,n,r||null);if(!i.userinfo_endpoint)throw new Error("Missing userinfo_endpoint for OAuth2 provider");const l=await fetch(i.userinfo_endpoint,{headers:{Authorization:`Bearer ${c.accessToken()}`}});if(!l.ok)throw new Error("Failed to fetch user info");const u=await l.json(),d=u.sub||u.id||u.user_id;if(!d)throw new Error("Unable to get user identifier: response missing sub, id, or user_id");return{sub:d,email:u.email,given_name:u.given_name||u.first_name,family_name:u.family_name||u.last_name,name:u.name||`${u.given_name||u.first_name||""} ${u.family_name||u.last_name||""}`.trim()}}const v7=Object.freeze(Object.defineProperty({__proto__:null,displayName:m7,getRedirect:y7,logoDataUri:g7,validateAuthorizationCodeAndGetUser:b7},Symbol.toStringTag,{value:"Module"})),Cu={apple:DE,facebook:FE,"google-oauth2":JE,vipps:e7,github:o7,microsoft:u7,oidc:_7,oauth2:v7};function U2(e,t){const n=e.env.STRATEGIES||{},i={...Cu,...n}[t];if(!i)throw new Error(`Strategy ${t} not found`);return i}const w7=new Set(["oidc","samlp","waad","adfs","oauth2"]);function k7(e){return w7.has(e.strategy)?e.name:e.strategy}function B2(e){return e.options?.icon_url?e.options.icon_url:Cu[e.strategy]?.logoDataUri}const $7=["email","email_verified","phone_number","phone_verified","username"];function fg(e){const t={connection:e.connection,provider:e.provider,user_id:df(e.user_id),isSocial:e.is_social};for(const n of $7)e[n]!==void 0&&e[n]!==null&&(t[n]=e[n]);return t}const hg=It.extend({users:o.z.array(xn)}),x7=It.extend({sessions:o.z.array(du)}),S7=It.extend({organizations:o.z.array(mr)}),z7=new o.OpenAPIHono().openapi(o.createRoute({tags:["users"],method:"get",path:"/",request:{query:rt,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(xn),hg])}},description:"List of users"}}}),async e=>{const{page:t,per_page:n,include_totals:r,sort:i,q:s}=e.req.valid("query");if(s?.includes("identities.profileData.email")){const u=s.split("=")[1],f=(await e.env.data.users.list(e.var.tenant_id,{page:t,per_page:n,include_totals:r,q:`email:${u}`})).users.filter(_=>_.linked_to),[p]=f;if(!p)return e.json([]);const h=await e.env.data.users.get(e.var.tenant_id,p.linked_to);if(!h)throw new I(500,{message:"Primary account not found"});return e.json([xn.parse(h)])}const a=["-_exists_:linked_to"];s&&a.push(s);const c=await e.env.data.users.list(e.var.tenant_id,{page:t,per_page:n,include_totals:r,sort:ft(i),q:a.join(" ")}),l=c.users.filter(u=>!u.linked_to);return r?e.json(hg.parse({users:l,length:c.length,start:c.start,limit:c.limit})):e.json(o.z.array(xn).parse(l))}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:xn}},description:"List of users"}}}),async e=>{const{user_id:t}=e.req.valid("param"),n=await e.env.data.users.get(e.var.tenant_id,t);if(!n)throw new I(404);if(n.linked_to)throw new I(404,{message:"User is linked to another user"});return e.json(n)}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["delete:users","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{user_id:t}=e.req.valid("param");if(!await e.env.data.users.remove(e.var.tenant_id,t))throw new I(404);return await fe(e,e.var.tenant_id,{type:ue.SUCCESS_API_OPERATION,description:"Delete a User",response:{statusCode:204,body:{}}}),e.text("OK")}).openapi(o.createRoute({tags:["users"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({...Wc.shape,password:o.z.string().optional()})}}}},security:[{Bearer:["create:users","auth:write"]}],responses:{201:{content:{"application/json":{schema:xn}},description:"Status"}}}),async e=>{const t=e.req.valid("json");e.set("body",t);const{email:n,phone_number:r,name:i,linked_to:s,email_verified:a,provider:c,connection:l,password:u}=t,d=await e.env.data.connections.get(e.var.tenant_id,l),f=d?k7(d):c||l,p=t.user_id,h=p?df(p):Ii(),_=`${f}|${h}`;try{let g;u&&(g=await na(u));const y={email:n,user_id:_,name:i||n||r,phone_number:r,provider:f,connection:l,linked_to:s??void 0,email_verified:a||!1,last_ip:"",is_social:!1,last_login:new Date().toISOString(),...g&&{password:g}},m=await e.env.data.users.create(e.var.tenant_id,y);e.set("user_id",m.user_id),await fe(e,e.var.tenant_id,{type:ue.SUCCESS_API_OPERATION,description:"User created"});const v=m.identities?m:{...m,identities:[fg(m)]};return e.json(xn.parse(v),{status:201})}catch(g){throw g.message==="User already exists"?new I(409,{message:"User already exists"}):g}}).openapi(o.createRoute({tags:["users"],method:"patch",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({...Wc.shape,verify_email:o.z.boolean(),password:o.z.string()}).partial()}}},params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["update:users","auth:write"]}],responses:{200:{description:"Status"}}}),async e=>{const{data:t}=e.env,n=e.req.valid("json"),{user_id:r}=e.req.valid("param"),{verify_email:i,password:s,connection:a,...c}=n,l=await t.users.get(e.var.tenant_id,r);if(!l)throw new I(404);if(l.linked_to)throw new I(404,{message:"User is linked to another user"});let u=r,d=l;if(a)if(l.connection===a)u=r,d=l;else{const h=(await t.users.list(e.var.tenant_id,{page:0,per_page:100,include_totals:!1,q:`linked_to:${r}`})).users.find(_=>_.connection===a);if(!h)throw new I(404,{message:`No identity found with connection: ${a}`});u=h.user_id,d=h}if(c.email&&c.email!==d.email){const p=await Rh(e.env.data.users,e.var.tenant_id,c.email);if(p.length&&p.some(h=>h.user_id!==u))throw new I(409,{message:"Another user with the same email address already exists."})}if(await e.env.data.users.update(e.var.tenant_id,u,c),s){let p;if(a)if(a==="Username-Password-Authentication")p={provider:d.provider,user_id:df(u)};else throw new I(400,{message:`Cannot set password for connection: ${a}`});else if(p=l.identities?.find(m=>m.connection==="Username-Password-Authentication"),!p)throw new I(400,{message:"User does not have a password identity"});const h=`${p.provider}|${p.user_id}`,_=await t.passwords.get(e.var.tenant_id,h);_&&await t.passwords.update(e.var.tenant_id,{id:_.id,user_id:h,password:_.password,algorithm:_.algorithm,is_current:!1});const{hash:g,algorithm:y}=await na(s);await t.passwords.create(e.var.tenant_id,{user_id:h,password:g,algorithm:y,is_current:!0})}const f=await e.env.data.users.get(e.var.tenant_id,r);if(!f)throw new I(500);return await fe(e,e.var.tenant_id,{type:ue.SUCCESS_API_OPERATION,description:"Update a User",body:n,response:{statusCode:200,body:f}}),e.json(f)}).openapi(o.createRoute({tags:["users"],method:"post",path:"/{user_id}/identities",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.union([o.z.object({link_with:o.z.string()}),o.z.object({user_id:o.z.string(),provider:o.z.string(),connection:o.z.string().optional()})])}}},params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:o.z.array(Gc)}},description:"Status"}}}),async e=>{const t=e.req.valid("json"),{user_id:n}=e.req.valid("param"),r="link_with"in t?t.link_with:t.user_id,i=await e.env.data.users.get(e.var.tenant_id,n);if(!i)throw new I(400,{message:"Linking an inexistent identity is not allowed."});await e.env.data.users.update(e.var.tenant_id,r,{linked_to:n});const s=await e.env.data.users.list(e.var.tenant_id,{page:0,per_page:10,include_totals:!1,q:`linked_to:${n}`}),a=[i,...s.users].map(fg);return e.json(o.z.array(Gc).parse(a),{status:201})}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/identities/{provider}/{linked_user_id}",request:{headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({user_id:o.z.string(),provider:o.z.string(),linked_user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:o.z.array(xn)}},description:"Status"}}}),async e=>{const{user_id:t,provider:n,linked_user_id:r}=e.req.valid("param");await e.env.data.users.unlink(e.var.tenant_id,t,n,r);const i=await e.env.data.users.get(e.var.tenant_id,t);if(!i)throw new I(404);return e.json([xn.parse(i)])}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/sessions",request:{query:rt,headers:o.z.object({"tenant-id":o.z.string().optional()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(du),x7])}},description:"List of sessions"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{include_totals:n,page:r,per_page:i}=e.req.valid("query"),s=await e.env.data.sessions.list(e.var.tenant_id,{page:r,per_page:i,include_totals:n,q:`user_id:${t}`});return n?e.json(s):e.json(s.sessions)}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/permissions",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),query:rt},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:xw}},description:"User permissions"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{page:n,per_page:r,sort:i,q:s}=e.req.valid("query");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});const c=await e.env.data.userPermissions.list(e.var.tenant_id,t,{page:n,per_page:r,include_totals:!1,sort:ft(i),q:s});return e.json(c)}).openapi(o.createRoute({tags:["users"],method:"post",path:"/{user_id}/permissions",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({permissions:o.z.array(o.z.object({permission_name:o.z.string(),resource_server_identifier:o.z.string()}))})}}}},security:[{Bearer:["update:users","auth:write"]}],responses:{201:{description:"Permissions assigned to user"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{permissions:n}=e.req.valid("json");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});for(const i of n)if(!await e.env.data.userPermissions.create(e.var.tenant_id,t,{user_id:t,resource_server_identifier:i.resource_server_identifier,permission_name:i.permission_name}))throw new I(500,{message:"Failed to assign permissions to user"});return e.json({message:"Permissions assigned successfully"},{status:201})}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/permissions",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()}),body:{content:{"application/json":{schema:o.z.object({permissions:o.z.array(o.z.object({permission_name:o.z.string(),resource_server_identifier:o.z.string()}))})}}}},security:[{Bearer:["update:users","auth:write"]}],responses:{200:{description:"Permissions removed from user"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{permissions:n}=e.req.valid("json");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});for(const i of n)if(!await e.env.data.userPermissions.remove(e.var.tenant_id,t,i))throw new I(500,{message:"Failed to remove permissions from user"});return e.json({message:"Permissions removed successfully"})}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/roles",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:rl}},description:"User roles"}}}),async e=>{const{user_id:t}=e.req.valid("param");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});const r=await e.env.data.userRoles.list(e.var.tenant_id,t,void 0,"");return e.json(r)}).openapi(o.createRoute({tags:["users"],method:"post",path:"/{user_id}/roles",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object({roles:o.z.array(o.z.string())})}}}},security:[{Bearer:["update:users","auth:write"]}],responses:{201:{description:"Roles assigned to user"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{roles:n}=e.req.valid("json");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});for(const i of n)if(!await e.env.data.userRoles.create(e.var.tenant_id,t,i,""))throw new I(500,{message:"Failed to assign roles to user"});return e.json({message:"Roles assigned successfully"},{status:201})}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/roles",request:{params:o.z.object({user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object({roles:o.z.array(o.z.string())})}}}},security:[{Bearer:["update:users","auth:write"]}],responses:{200:{description:"Roles removed from user"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{roles:n}=e.req.valid("json");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});for(const i of n)if(!await e.env.data.userRoles.remove(e.var.tenant_id,t,i,""))throw new I(500,{message:"Failed to remove roles from user"});return e.json({message:"Roles removed successfully"})}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/organizations",request:{params:o.z.object({user_id:o.z.string()}),query:rt,headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["read:users","auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([S7,o.z.array(mr)])}},description:"List of user organizations"}}}),async e=>{const{user_id:t}=e.req.valid("param"),{page:n,per_page:r,include_totals:i,sort:s}=e.req.valid("query");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});const c=await e.env.data.userOrganizations.listUserOrganizations(e.var.tenant_id,t,{page:n,per_page:r,sort:ft(s)});return i?e.json({organizations:c.organizations,start:c.start,limit:c.limit,length:c.length}):e.json(c.organizations)}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/organizations/{organization_id}",request:{params:o.z.object({user_id:o.z.string(),organization_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["update:users","auth:write"]}],responses:{200:{description:"User removed from organization successfully"}}}),async e=>{const{user_id:t,organization_id:n}=e.req.valid("param");if(!await e.env.data.users.get(e.var.tenant_id,t))throw new I(404,{message:"User not found"});const s=(await e.env.data.userOrganizations.list(e.var.tenant_id,{q:`user_id:${t}`,per_page:100})).userOrganizations.find(a=>a.organization_id===n);if(!s)throw new I(404,{message:"User is not a member of this organization"});return await e.env.data.userOrganizations.remove(e.var.tenant_id,s.id),e.json({message:"User removed from organization successfully"})});var _g={};var mg;function A7(){if(mg)return _g;mg=1;var e;return(function(t){(function(n){var r=typeof globalThis=="object"?globalThis:typeof zm=="object"?zm:typeof self=="object"?self:typeof this=="object"?this:l(),i=s(t);typeof r.Reflect<"u"&&(i=s(r.Reflect,i)),n(i,r),typeof r.Reflect>"u"&&(r.Reflect=t);function s(u,d){return function(f,p){Object.defineProperty(u,f,{configurable:!0,writable:!0,value:p}),d&&d(f,p)}}function a(){try{return Function("return this;")()}catch{}}function c(){try{return(0,eval)("(function() { return this; })()")}catch{}}function l(){return a()||c()}})(function(n,r){var i=Object.prototype.hasOwnProperty,s=typeof Symbol=="function",a=s&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",c=s&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",l=typeof Object.create=="function",u={__proto__:[]}instanceof Array,d=!l&&!u,f={create:l?function(){return Dd(Object.create(null))}:u?function(){return Dd({__proto__:null})}:function(){return Dd({})},has:d?function(O,U){return i.call(O,U)}:function(O,U){return U in O},get:d?function(O,U){return i.call(O,U)?O[U]:void 0}:function(O,U){return O[U]}},p=Object.getPrototypeOf(Function),h=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:ic(),_=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Ld(),g=typeof WeakMap=="function"?WeakMap:tx(),y=s?Symbol.for("@reflect-metadata:registry"):void 0,m=Rn(),v=Zt(m);function k(O,U,q,X){if(V(q)){if(!Y(O))throw new TypeError;if(!me(U))throw new TypeError;return M(O,U)}else{if(!Y(O))throw new TypeError;if(!ce(U))throw new TypeError;if(!ce(X)&&!V(X)&&!Te(X))throw new TypeError;return Te(X)&&(X=void 0),q=B(q),H(O,U,q,X)}}n("decorate",k);function x(O,U){function q(X,de){if(!ce(X))throw new TypeError;if(!V(de)&&!Xe(de))throw new TypeError;we(O,U,X,de)}return q}n("metadata",x);function b(O,U,q,X){if(!ce(q))throw new TypeError;return V(X)||(X=B(X)),we(O,U,q,X)}n("defineMetadata",b);function S(O,U,q){if(!ce(U))throw new TypeError;return V(q)||(q=B(q)),D(O,U,q)}n("hasMetadata",S);function A(O,U,q){if(!ce(U))throw new TypeError;return V(q)||(q=B(q)),Q(O,U,q)}n("hasOwnMetadata",A);function C(O,U,q){if(!ce(U))throw new TypeError;return V(q)||(q=B(q)),pe(O,U,q)}n("getMetadata",C);function P(O,U,q){if(!ce(U))throw new TypeError;return V(q)||(q=B(q)),se(O,U,q)}n("getOwnMetadata",P);function R(O,U){if(!ce(O))throw new TypeError;return V(U)||(U=B(U)),le(O,U)}n("getMetadataKeys",R);function E(O,U){if(!ce(O))throw new TypeError;return V(U)||(U=B(U)),be(O,U)}n("getOwnMetadataKeys",E);function L(O,U,q){if(!ce(U))throw new TypeError;if(V(q)||(q=B(q)),!ce(U))throw new TypeError;V(q)||(q=B(q));var X=Hr(U,q,!1);return V(X)?!1:X.OrdinaryDeleteMetadata(O,U,q)}n("deleteMetadata",L);function M(O,U){for(var q=O.length-1;q>=0;--q){var X=O[q],de=X(U);if(!V(de)&&!Te(de)){if(!me(de))throw new TypeError;U=de}}return U}function H(O,U,q,X){for(var de=O.length-1;de>=0;--de){var tt=O[de],Qe=tt(U,q,X);if(!V(Qe)&&!Te(Qe)){if(!ce(Qe))throw new TypeError;X=Qe}}return X}function D(O,U,q){var X=Q(O,U,q);if(X)return!0;var de=ze(U);return Te(de)?!1:D(O,de,q)}function Q(O,U,q){var X=Hr(U,q,!1);return V(X)?!1:Li(X.OrdinaryHasOwnMetadata(O,U,q))}function pe(O,U,q){var X=Q(O,U,q);if(X)return se(O,U,q);var de=ze(U);if(!Te(de))return pe(O,de,q)}function se(O,U,q){var X=Hr(U,q,!1);if(!V(X))return X.OrdinaryGetOwnMetadata(O,U,q)}function we(O,U,q,X){var de=Hr(q,X,!0);de.OrdinaryDefineOwnMetadata(O,U,q,X)}function le(O,U){var q=be(O,U),X=ze(O);if(X===null)return q;var de=le(X,U);if(de.length<=0)return q;if(q.length<=0)return de;for(var tt=new _,Qe=[],ke=0,ee=q;ke<ee.length;ke++){var re=ee[ke],oe=tt.has(re);oe||(tt.add(re),Qe.push(re))}for(var ae=0,$e=de;ae<$e.length;ae++){var re=$e[ae],oe=tt.has(re);oe||(tt.add(re),Qe.push(re))}return Qe}function be(O,U){var q=Hr(O,U,!1);return q?q.OrdinaryOwnMetadataKeys(O,U):[]}function Ee(O){if(O===null)return 1;switch(typeof O){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return O===null?1:6;default:return 6}}function V(O){return O===void 0}function Te(O){return O===null}function $t(O){return typeof O=="symbol"}function ce(O){return typeof O=="object"?O!==null:typeof O=="function"}function ut(O,U){switch(Ee(O)){case 0:return O;case 1:return O;case 2:return O;case 3:return O;case 4:return O;case 5:return O}var q="string",X=Od(O,a);if(X!==void 0){var de=X.call(O,q);if(ce(de))throw new TypeError;return de}return is(O)}function is(O,U){var q,X;{var de=O.toString;if(G(de)){var X=de.call(O);if(!ce(X))return X}var q=O.valueOf;if(G(q)){var X=q.call(O);if(!ce(X))return X}}throw new TypeError}function Li(O){return!!O}function Di(O){return""+O}function B(O){var U=ut(O);return $t(U)?U:Di(U)}function Y(O){return Array.isArray?Array.isArray(O):O instanceof Object?O instanceof Array:Object.prototype.toString.call(O)==="[object Array]"}function G(O){return typeof O=="function"}function me(O){return typeof O=="function"}function Xe(O){switch(Ee(O)){case 3:return!0;case 4:return!0;default:return!1}}function Ye(O,U){return O===U||O!==O&&U!==U}function Od(O,U){var q=O[U];if(q!=null){if(!G(q))throw new TypeError;return q}}function Rd(O){var U=Od(O,c);if(!G(U))throw new TypeError;var q=U.call(O);if(!ce(q))throw new TypeError;return q}function Ie(O){return O.value}function Se(O){var U=O.next();return U.done?!1:U}function Ui(O){var U=O.return;U&&U.call(O)}function ze(O){var U=Object.getPrototypeOf(O);if(typeof O!="function"||O===p||U!==p)return U;var q=O.prototype,X=q&&Object.getPrototypeOf(q);if(X==null||X===Object.prototype)return U;var de=X.constructor;return typeof de!="function"||de===O?U:de}function je(){var O;!V(y)&&typeof r.Reflect<"u"&&!(y in r.Reflect)&&typeof r.Reflect.defineMetadata=="function"&&(O=Tt(r.Reflect));var U,q,X,de=new g,tt={registerProvider:Qe,getProvider:ee,setProvider:oe};return tt;function Qe(ae){if(!Object.isExtensible(tt))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case O===ae:break;case V(U):U=ae;break;case U===ae:break;case V(q):q=ae;break;case q===ae:break;default:X===void 0&&(X=new _),X.add(ae);break}}function ke(ae,$e){if(!V(U)){if(U.isProviderFor(ae,$e))return U;if(!V(q)){if(q.isProviderFor(ae,$e))return U;if(!V(X))for(var Re=Rd(X);;){var Ke=Se(Re);if(!Ke)return;var Xt=Ie(Ke);if(Xt.isProviderFor(ae,$e))return Ui(Re),Xt}}}if(!V(O)&&O.isProviderFor(ae,$e))return O}function ee(ae,$e){var Re=de.get(ae),Ke;return V(Re)||(Ke=Re.get($e)),V(Ke)&&(Ke=ke(ae,$e),V(Ke)||(V(Re)&&(Re=new h,de.set(ae,Re)),Re.set($e,Ke))),Ke}function re(ae){if(V(ae))throw new TypeError;return U===ae||q===ae||!V(X)&&X.has(ae)}function oe(ae,$e,Re){if(!re(Re))throw new Error("Metadata provider not registered.");var Ke=ee(ae,$e);if(Ke!==Re){if(!V(Ke))return!1;var Xt=de.get(ae);V(Xt)&&(Xt=new h,de.set(ae,Xt)),Xt.set($e,Re)}return!0}}function Rn(){var O;return!V(y)&&ce(r.Reflect)&&Object.isExtensible(r.Reflect)&&(O=r.Reflect[y]),V(O)&&(O=je()),!V(y)&&ce(r.Reflect)&&Object.isExtensible(r.Reflect)&&Object.defineProperty(r.Reflect,y,{enumerable:!1,configurable:!1,writable:!1,value:O}),O}function Zt(O){var U=new g,q={isProviderFor:function(re,oe){var ae=U.get(re);return V(ae)?!1:ae.has(oe)},OrdinaryDefineOwnMetadata:Qe,OrdinaryHasOwnMetadata:de,OrdinaryGetOwnMetadata:tt,OrdinaryOwnMetadataKeys:ke,OrdinaryDeleteMetadata:ee};return m.registerProvider(q),q;function X(re,oe,ae){var $e=U.get(re),Re=!1;if(V($e)){if(!ae)return;$e=new h,U.set(re,$e),Re=!0}var Ke=$e.get(oe);if(V(Ke)){if(!ae)return;if(Ke=new h,$e.set(oe,Ke),!O.setProvider(re,oe,q))throw $e.delete(oe),Re&&U.delete(re),new Error("Wrong provider for target.")}return Ke}function de(re,oe,ae){var $e=X(oe,ae,!1);return V($e)?!1:Li($e.has(re))}function tt(re,oe,ae){var $e=X(oe,ae,!1);if(!V($e))return $e.get(re)}function Qe(re,oe,ae,$e){var Re=X(ae,$e,!0);Re.set(re,oe)}function ke(re,oe){var ae=[],$e=X(re,oe,!1);if(V($e))return ae;for(var Re=$e.keys(),Ke=Rd(Re),Xt=0;;){var sm=Se(Ke);if(!sm)return ae.length=Xt,ae;var nx=Ie(sm);try{ae[Xt]=nx}catch(rx){try{Ui(Ke)}finally{throw rx}}Xt++}}function ee(re,oe,ae){var $e=X(oe,ae,!1);if(V($e)||!$e.delete(re))return!1;if($e.size===0){var Re=U.get(oe);V(Re)||(Re.delete(ae),Re.size===0&&U.delete(Re))}return!0}}function Tt(O){var U=O.defineMetadata,q=O.hasOwnMetadata,X=O.getOwnMetadata,de=O.getOwnMetadataKeys,tt=O.deleteMetadata,Qe=new g,ke={isProviderFor:function(ee,re){var oe=Qe.get(ee);return!V(oe)&&oe.has(re)?!0:de(ee,re).length?(V(oe)&&(oe=new _,Qe.set(ee,oe)),oe.add(re),!0):!1},OrdinaryDefineOwnMetadata:U,OrdinaryHasOwnMetadata:q,OrdinaryGetOwnMetadata:X,OrdinaryOwnMetadataKeys:de,OrdinaryDeleteMetadata:tt};return ke}function Hr(O,U,q){var X=m.getProvider(O,U);if(!V(X))return X;if(q){if(m.setProvider(O,U,v))return v;throw new Error("Illegal state.")}}function ic(){var O={},U=[],q=(function(){function ke(ee,re,oe){this._index=0,this._keys=ee,this._values=re,this._selector=oe}return ke.prototype["@@iterator"]=function(){return this},ke.prototype[c]=function(){return this},ke.prototype.next=function(){var ee=this._index;if(ee>=0&&ee<this._keys.length){var re=this._selector(this._keys[ee],this._values[ee]);return ee+1>=this._keys.length?(this._index=-1,this._keys=U,this._values=U):this._index++,{value:re,done:!1}}return{value:void 0,done:!0}},ke.prototype.throw=function(ee){throw this._index>=0&&(this._index=-1,this._keys=U,this._values=U),ee},ke.prototype.return=function(ee){return this._index>=0&&(this._index=-1,this._keys=U,this._values=U),{value:ee,done:!0}},ke})(),X=(function(){function ke(){this._keys=[],this._values=[],this._cacheKey=O,this._cacheIndex=-2}return Object.defineProperty(ke.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),ke.prototype.has=function(ee){return this._find(ee,!1)>=0},ke.prototype.get=function(ee){var re=this._find(ee,!1);return re>=0?this._values[re]:void 0},ke.prototype.set=function(ee,re){var oe=this._find(ee,!0);return this._values[oe]=re,this},ke.prototype.delete=function(ee){var re=this._find(ee,!1);if(re>=0){for(var oe=this._keys.length,ae=re+1;ae<oe;ae++)this._keys[ae-1]=this._keys[ae],this._values[ae-1]=this._values[ae];return this._keys.length--,this._values.length--,Ye(ee,this._cacheKey)&&(this._cacheKey=O,this._cacheIndex=-2),!0}return!1},ke.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=O,this._cacheIndex=-2},ke.prototype.keys=function(){return new q(this._keys,this._values,de)},ke.prototype.values=function(){return new q(this._keys,this._values,tt)},ke.prototype.entries=function(){return new q(this._keys,this._values,Qe)},ke.prototype["@@iterator"]=function(){return this.entries()},ke.prototype[c]=function(){return this.entries()},ke.prototype._find=function(ee,re){if(!Ye(this._cacheKey,ee)){this._cacheIndex=-1;for(var oe=0;oe<this._keys.length;oe++)if(Ye(this._keys[oe],ee)){this._cacheIndex=oe;break}}return this._cacheIndex<0&&re&&(this._cacheIndex=this._keys.length,this._keys.push(ee),this._values.push(void 0)),this._cacheIndex},ke})();return X;function de(ke,ee){return ke}function tt(ke,ee){return ee}function Qe(ke,ee){return[ke,ee]}}function Ld(){var O=(function(){function U(){this._map=new h}return Object.defineProperty(U.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),U.prototype.has=function(q){return this._map.has(q)},U.prototype.add=function(q){return this._map.set(q,q),this},U.prototype.delete=function(q){return this._map.delete(q)},U.prototype.clear=function(){this._map.clear()},U.prototype.keys=function(){return this._map.keys()},U.prototype.values=function(){return this._map.keys()},U.prototype.entries=function(){return this._map.entries()},U.prototype["@@iterator"]=function(){return this.keys()},U.prototype[c]=function(){return this.keys()},U})();return O}function tx(){var O=16,U=f.create(),q=X();return(function(){function ee(){this._key=X()}return ee.prototype.has=function(re){var oe=de(re,!1);return oe!==void 0?f.has(oe,this._key):!1},ee.prototype.get=function(re){var oe=de(re,!1);return oe!==void 0?f.get(oe,this._key):void 0},ee.prototype.set=function(re,oe){var ae=de(re,!0);return ae[this._key]=oe,this},ee.prototype.delete=function(re){var oe=de(re,!1);return oe!==void 0?delete oe[this._key]:!1},ee.prototype.clear=function(){this._key=X()},ee})();function X(){var ee;do ee="@@WeakMap@@"+ke();while(f.has(U,ee));return U[ee]=!0,ee}function de(ee,re){if(!i.call(ee,q)){if(!re)return;Object.defineProperty(ee,q,{value:f.create()})}return ee[q]}function tt(ee,re){for(var oe=0;oe<re;++oe)ee[oe]=Math.random()*255|0;return ee}function Qe(ee){if(typeof Uint8Array=="function"){var re=new Uint8Array(ee);return typeof crypto<"u"?crypto.getRandomValues(re):typeof msCrypto<"u"?msCrypto.getRandomValues(re):tt(re,ee),re}return tt(new Array(ee),ee)}function ke(){var ee=Qe(O);ee[6]=ee[6]&79|64,ee[8]=ee[8]&191|128;for(var re="",oe=0;oe<O;++oe){var ae=ee[oe];(oe===4||oe===6||oe===8)&&(re+="-"),ae<16&&(re+="0"),re+=ae.toString(16).toLowerCase()}return re}}function Dd(O){return O.__=void 0,delete O.__,O}})})(e||(e={})),_g}A7();const E7="[object ArrayBuffer]";class Z{static isArrayBuffer(t){return Object.prototype.toString.call(t)===E7}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,n){if(t.constructor===n)return t;if(this.isArrayBuffer(t))return new n(t);if(this.isArrayBufferView(t))return new n(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,n){const r=Z.toUint8Array(t),i=Z.toUint8Array(n);if(r.length!==i.byteLength)return!1;for(let s=0;s<r.length;s++)if(r[s]!==i[s])return!1;return!0}static concat(...t){let n;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?n=t[0]:t[t.length-1]instanceof Function?n=t.slice(0,t.length-1):n=t;let r=0;for(const a of n)r+=a.byteLength;const i=new Uint8Array(r);let s=0;for(const a of n){const c=this.toUint8Array(a);i.set(c,s),s+=c.length}return t[t.length-1]instanceof Function?this.toView(i,t[t.length-1]):i.buffer}}const Vd="string",C7=/^[0-9a-f\s]+$/i,I7=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,j7=/^[a-zA-Z0-9-_]+$/;class gg{static fromString(t){const n=unescape(encodeURIComponent(t)),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r.buffer}static toString(t){const n=Z.toUint8Array(t);let r="";for(let s=0;s<n.length;s++)r+=String.fromCharCode(n[s]);return decodeURIComponent(escape(r))}}class wn{static toString(t,n=!1){const r=Z.toArrayBuffer(t),i=new DataView(r);let s="";for(let a=0;a<r.byteLength;a+=2){const c=i.getUint16(a,n);s+=String.fromCharCode(c)}return s}static fromString(t,n=!1){const r=new ArrayBuffer(t.length*2),i=new DataView(r);for(let s=0;s<t.length;s++)i.setUint16(s*2,t.charCodeAt(s),n);return r}}class ie{static isHex(t){return typeof t===Vd&&C7.test(t)}static isBase64(t){return typeof t===Vd&&I7.test(t)}static isBase64Url(t){return typeof t===Vd&&j7.test(t)}static ToString(t,n="utf8"){const r=Z.toUint8Array(t);switch(n.toLowerCase()){case"utf8":return this.ToUtf8String(r);case"binary":return this.ToBinary(r);case"hex":return this.ToHex(r);case"base64":return this.ToBase64(r);case"base64url":return this.ToBase64Url(r);case"utf16le":return wn.toString(r,!0);case"utf16":case"utf16be":return wn.toString(r);default:throw new Error(`Unknown type of encoding '${n}'`)}}static FromString(t,n="utf8"){if(!t)return new ArrayBuffer(0);switch(n.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return wn.fromString(t,!0);case"utf16":case"utf16be":return wn.fromString(t);default:throw new Error(`Unknown type of encoding '${n}'`)}}static ToBase64(t){const n=Z.toUint8Array(t);if(typeof btoa<"u"){const r=this.ToString(n,"binary");return btoa(r)}else return Buffer.from(n).toString("base64")}static FromBase64(t){const n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!ie.isBase64(n))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(n)):new Uint8Array(Buffer.from(n,"base64")).buffer}static FromBase64Url(t){const n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!ie.isBase64Url(n))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(n.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,n=ie.DEFAULT_UTF8_ENCODING){switch(n){case"ascii":return this.FromBinary(t);case"utf8":return gg.fromString(t);case"utf16":case"utf16be":return wn.fromString(t);case"utf16le":case"usc2":return wn.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${n}'`)}}static ToUtf8String(t,n=ie.DEFAULT_UTF8_ENCODING){switch(n){case"ascii":return this.ToBinary(t);case"utf8":return gg.toString(t);case"utf16":case"utf16be":return wn.toString(t);case"utf16le":case"usc2":return wn.toString(t,!0);default:throw new Error(`Unknown type of encoding '${n}'`)}}static FromBinary(t){const n=t.length,r=new Uint8Array(n);for(let i=0;i<n;i++)r[i]=t.charCodeAt(i);return r.buffer}static ToBinary(t){const n=Z.toUint8Array(t);let r="";for(let i=0;i<n.length;i++)r+=String.fromCharCode(n[i]);return r}static ToHex(t){const n=Z.toUint8Array(t);let r="";const i=n.length;for(let s=0;s<i;s++){const a=n[s];a<16&&(r+="0"),r+=a.toString(16)}return r}static FromHex(t){let n=this.formatString(t);if(!n)return new ArrayBuffer(0);if(!ie.isHex(n))throw new TypeError("Argument 'hexString' is not HEX encoded");n.length%2&&(n=`0${n}`);const r=new Uint8Array(n.length/2);for(let i=0;i<n.length;i=i+2){const s=n.slice(i,i+2);r[i/2]=parseInt(s,16)}return r.buffer}static ToUtf16String(t,n=!1){return wn.toString(t,n)}static FromUtf16String(t,n=!1){return wn.fromString(t,n)}static Base64Padding(t){const n=4-t.length%4;if(n<4)for(let r=0;r<n;r++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}}ie.DEFAULT_UTF8_ENCODING="utf8";function N7(...e){const t=e.map(i=>i.byteLength).reduce((i,s)=>i+s),n=new Uint8Array(t);let r=0;return e.map(i=>new Uint8Array(i)).forEach(i=>{for(const s of i)n[r++]=s}),n.buffer}function M2(e,t){if(!(e&&t)||e.byteLength!==t.byteLength)return!1;const n=new Uint8Array(e),r=new Uint8Array(t);for(let i=0;i<e.byteLength;i++)if(n[i]!==r[i])return!1;return!0}function vo(e,t){let n=0;if(e.length===1)return e[0];for(let r=e.length-1;r>=0;r--)n+=e[e.length-1-r]*Math.pow(2,t*r);return n}function hi(e,t,n=-1){const r=n;let i=e,s=0,a=Math.pow(2,t);for(let c=1;c<8;c++){if(e<a){let l;if(r<0)l=new ArrayBuffer(c),s=c;else{if(r<c)return new ArrayBuffer(0);l=new ArrayBuffer(r),s=r}const u=new Uint8Array(l);for(let d=c-1;d>=0;d--){const f=Math.pow(2,d*t);u[s-d-1]=Math.floor(i/f),i-=u[s-d-1]*f}return l}a*=Math.pow(2,t)}return new ArrayBuffer(0)}function Sf(...e){let t=0,n=0;for(const s of e)t+=s.length;const r=new ArrayBuffer(t),i=new Uint8Array(r);for(const s of e)i.set(s,n),n+=s.length;return i}function q2(){const e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const c=e[0]===255&&e[1]&128,l=e[0]===0&&(e[1]&128)===0;(c||l)&&this.warnings.push("Needlessly long format")}const t=new ArrayBuffer(this.valueHex.byteLength),n=new Uint8Array(t);for(let c=0;c<this.valueHex.byteLength;c++)n[c]=0;n[0]=e[0]&128;const r=vo(n,8),i=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(i);for(let c=0;c<this.valueHex.byteLength;c++)s[c]=e[c];return s[0]&=127,vo(s,8)-r}function T7(e){const t=e<0?e*-1:e;let n=128;for(let r=1;r<8;r++){if(t<=n){if(e<0){const a=n-t,c=hi(a,8,r),l=new Uint8Array(c);return l[0]|=128,c}let i=hi(t,8,r),s=new Uint8Array(i);if(s[0]&128){const a=i.slice(0),c=new Uint8Array(a);i=new ArrayBuffer(i.byteLength+1),s=new Uint8Array(i);for(let l=0;l<a.byteLength;l++)s[l+1]=c[l];s[0]=0}return i}n*=Math.pow(2,8)}return new ArrayBuffer(0)}function P7(e,t){if(e.byteLength!==t.byteLength)return!1;const n=new Uint8Array(e),r=new Uint8Array(t);for(let i=0;i<n.length;i++)if(n[i]!==r[i])return!1;return!0}function Pt(e,t){const n=e.toString(10);if(t<n.length)return"";const r=t-n.length,i=new Array(r);for(let a=0;a<r;a++)i[a]="0";return i.join("").concat(n)}function ml(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function qh(e){let t=0,n=0;for(let i=0;i<e.length;i++){const s=e[i];t+=s.byteLength}const r=new Uint8Array(t);for(let i=0;i<e.length;i++){const s=e[i];r.set(new Uint8Array(s),n),n+=s.byteLength}return r.buffer}function or(e,t,n,r){return t instanceof Uint8Array?t.byteLength?n<0?(e.error="Wrong parameter: inputOffset less than zero",!1):r<0?(e.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-n-r<0?(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class Iu{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return qh(this.items)}}const as=[new Uint8Array([1])],yg="0123456789",Kd="name",bg="valueHexView",O7="isHexOnly",R7="idBlock",L7="tagClass",D7="tagNumber",U7="isConstructed",B7="fromBER",M7="toBER",q7="local",Et="",Nn=new ArrayBuffer(0),ju=new Uint8Array(0),ia="EndOfContent",F2="OCTET STRING",H2="BIT STRING";function Tn(e){var t;return t=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(r){this.valueHexView=new Uint8Array(r)}constructor(...r){var i;super(...r);const s=r[0]||{};this.isHexOnly=(i=s.isHexOnly)!==null&&i!==void 0?i:!1,this.valueHexView=s.valueHex?Z.toUint8Array(s.valueHex):ju}fromBER(r,i,s){const a=r instanceof ArrayBuffer?new Uint8Array(r):r;if(!or(this,a,i,s))return-1;const c=i+s;return this.valueHexView=a.subarray(i,c),this.valueHexView.length?(this.blockLength=s,c):(this.warnings.push("Zero buffer length"),i)}toBER(r=!1){return this.isHexOnly?r?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Nn)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:ie.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}class Ti{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}constructor({blockLength:t=0,error:n=Et,warnings:r=[],valueBeforeDecode:i=ju}={}){this.blockLength=t,this.error=n,this.warnings=r,this.valueBeforeDecodeView=Z.toUint8Array(i)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:ie.ToHex(this.valueBeforeDecodeView)}}}Ti.NAME="baseBlock";class kt extends Ti{fromBER(t,n,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}kt.NAME="valueBlock";class V2 extends Tn(Ti){constructor({idBlock:t={}}={}){var n,r,i,s;super(),t?(this.isHexOnly=(n=t.isHexOnly)!==null&&n!==void 0?n:!1,this.valueHexView=t.valueHex?Z.toUint8Array(t.valueHex):ju,this.tagClass=(r=t.tagClass)!==null&&r!==void 0?r:-1,this.tagNumber=(i=t.tagNumber)!==null&&i!==void 0?i:-1,this.isConstructed=(s=t.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let n=0;switch(this.tagClass){case 1:n|=0;break;case 2:n|=64;break;case 3:n|=128;break;case 4:n|=192;break;default:return this.error="Unknown tag class",Nn}if(this.isConstructed&&(n|=32),this.tagNumber<31&&!this.isHexOnly){const i=new Uint8Array(1);if(!t){let s=this.tagNumber;s&=31,n|=s,i[0]=n}return i.buffer}if(!this.isHexOnly){const i=hi(this.tagNumber,7),s=new Uint8Array(i),a=i.byteLength,c=new Uint8Array(a+1);if(c[0]=n|31,!t){for(let l=0;l<a-1;l++)c[l+1]=s[l]|128;c[a]=s[a-1]}return c.buffer}const r=new Uint8Array(this.valueHexView.byteLength+1);if(r[0]=n|31,!t){const i=this.valueHexView;for(let s=0;s<i.length-1;s++)r[s+1]=i[s]|128;r[this.valueHexView.byteLength]=i[i.length-1]}return r.buffer}fromBER(t,n,r){const i=Z.toUint8Array(t);if(!or(this,i,n,r))return-1;const s=i.subarray(n,n+r);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;const c=s[0]&31;if(c!==31)this.tagNumber=c,this.blockLength=1;else{let l=1,u=this.valueHexView=new Uint8Array(255),d=255;for(;s[l]&128;){if(u[l-1]=s[l]&127,l++,l>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(l===d){d+=255;const p=new Uint8Array(d);for(let h=0;h<u.length;h++)p[h]=u[h];u=this.valueHexView=new Uint8Array(d)}}this.blockLength=l+1,u[l-1]=s[l]&127;const f=new Uint8Array(l);for(let p=0;p<l;p++)f[p]=u[p];u=this.valueHexView=new Uint8Array(l),u.set(f),this.blockLength<=9?this.tagNumber=vo(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return n+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}V2.NAME="identificationBlock";class K2 extends Ti{constructor({lenBlock:t={}}={}){var n,r,i;super(),this.isIndefiniteForm=(n=t.isIndefiniteForm)!==null&&n!==void 0?n:!1,this.longFormUsed=(r=t.longFormUsed)!==null&&r!==void 0?r:!1,this.length=(i=t.length)!==null&&i!==void 0?i:0}fromBER(t,n,r){const i=Z.toUint8Array(t);if(!or(this,i,n,r))return-1;const s=i.subarray(n,n+r);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,n+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,n+this.blockLength;const a=s[0]&127;if(a>8)return this.error="Too big integer",-1;if(a+1>s.length)return this.error="End of input reached before message was fully decoded",-1;const c=n+1,l=i.subarray(c,c+a);return l[a-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=vo(l,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=a+1,n+this.blockLength}toBER(t=!1){let n,r;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return n=new ArrayBuffer(1),t===!1&&(r=new Uint8Array(n),r[0]=128),n;if(this.longFormUsed){const i=hi(this.length,8);if(i.byteLength>127)return this.error="Too big length",Nn;if(n=new ArrayBuffer(i.byteLength+1),t)return n;const s=new Uint8Array(i);r=new Uint8Array(n),r[0]=i.byteLength|128;for(let a=0;a<i.byteLength;a++)r[a+1]=s[a];return n}return n=new ArrayBuffer(1),t===!1&&(r=new Uint8Array(n),r[0]=this.length),n}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}K2.NAME="lengthBlock";const ne={};class at extends Ti{constructor({name:t=Et,optional:n=!1,primitiveSchema:r,...i}={},s){super(i),this.name=t,this.optional=n,r&&(this.primitiveSchema=r),this.idBlock=new V2(i),this.lenBlock=new K2(i),this.valueBlock=s?new s(i):new kt(i)}fromBER(t,n,r){const i=this.valueBlock.fromBER(t,n,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}toBER(t,n){const r=n||new Iu;n||G2(this);const i=this.idBlock.toBER(t);if(r.write(i),this.lenBlock.isIndefiniteForm)r.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,r),r.write(new ArrayBuffer(2));else{const s=this.valueBlock.toBER(t);this.lenBlock.length=s.byteLength;const a=this.lenBlock.toBER(t);r.write(a),r.write(s)}return n?Nn:r.final()}toJSON(){const t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():ie.ToHex(this.toBER())}onAsciiEncoding(){const t=this.constructor.NAME,n=ie.ToHex(this.valueBlock.valueBeforeDecodeView);return`${t} : ${n}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;const n=this.toBER(),r=t.toBER();return P7(n,r)}}at.NAME="BaseBlock";function G2(e){var t;if(e instanceof ne.Constructed)for(const n of e.valueBlock.value)G2(n)&&(e.lenBlock.isIndefiniteForm=!0);return!!(!((t=e.lenBlock)===null||t===void 0)&&t.isIndefiniteForm)}class Fh extends at{getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}constructor({value:t=Et,...n}={},r){super(n,r),t&&this.fromString(t)}fromBER(t,n,r){const i=this.valueBlock.fromBER(t,n,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return i===-1?(this.error=this.valueBlock.error,i):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}Fh.NAME="BaseStringBlock";class W2 extends Tn(kt){constructor({isHexOnly:t=!0,...n}={}){super(n),this.isHexOnly=t}}W2.NAME="PrimitiveValueBlock";var J2;class Ia extends at{constructor(t={}){super(t,W2),this.idBlock.isConstructed=!1}}J2=Ia;ne.Primitive=J2;Ia.NAME="PRIMITIVE";function F7(e,t){if(e instanceof t)return e;const n=new t;return n.idBlock=e.idBlock,n.lenBlock=e.lenBlock,n.warnings=e.warnings,n.valueBeforeDecodeView=e.valueBeforeDecodeView,n}function qo(e,t=0,n=e.length){const r=t;let i=new at({},kt);const s=new Ti;if(!or(s,e,t,n))return i.error=s.error,{offset:-1,result:i};if(!e.subarray(t,t+n).length)return i.error="Zero buffer length",{offset:-1,result:i};let c=i.idBlock.fromBER(e,t,n);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),c===-1)return i.error=i.idBlock.error,{offset:-1,result:i};if(t=c,n-=i.idBlock.blockLength,c=i.lenBlock.fromBER(e,t,n),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),c===-1)return i.error=i.lenBlock.error,{offset:-1,result:i};if(t=c,n-=i.lenBlock.blockLength,!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};let l=at;switch(i.idBlock.tagClass){case 1:if(i.idBlock.tagNumber>=37&&i.idBlock.isHexOnly===!1)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};l=ne.EndOfContent;break;case 1:l=ne.Boolean;break;case 2:l=ne.Integer;break;case 3:l=ne.BitString;break;case 4:l=ne.OctetString;break;case 5:l=ne.Null;break;case 6:l=ne.ObjectIdentifier;break;case 10:l=ne.Enumerated;break;case 12:l=ne.Utf8String;break;case 13:l=ne.RelativeObjectIdentifier;break;case 14:l=ne.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:l=ne.Sequence;break;case 17:l=ne.Set;break;case 18:l=ne.NumericString;break;case 19:l=ne.PrintableString;break;case 20:l=ne.TeletexString;break;case 21:l=ne.VideotexString;break;case 22:l=ne.IA5String;break;case 23:l=ne.UTCTime;break;case 24:l=ne.GeneralizedTime;break;case 25:l=ne.GraphicString;break;case 26:l=ne.VisibleString;break;case 27:l=ne.GeneralString;break;case 28:l=ne.UniversalString;break;case 29:l=ne.CharacterString;break;case 30:l=ne.BmpString;break;case 31:l=ne.DATE;break;case 32:l=ne.TimeOfDay;break;case 33:l=ne.DateTime;break;case 34:l=ne.Duration;break;default:{const u=i.idBlock.isConstructed?new ne.Constructed:new ne.Primitive;u.idBlock=i.idBlock,u.lenBlock=i.lenBlock,u.warnings=i.warnings,i=u}}break;default:l=i.idBlock.isConstructed?ne.Constructed:ne.Primitive}return i=F7(i,l),c=i.fromBER(e,t,i.lenBlock.isIndefiniteForm?n:i.lenBlock.length),i.valueBeforeDecodeView=e.subarray(r,r+i.blockLength),{offset:c,result:i}}function lo(e){if(!e.byteLength){const t=new at({},kt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return qo(Z.toUint8Array(e).slice(),0,e.byteLength)}function H7(e,t){return e?1:t}class $r extends kt{constructor({value:t=[],isIndefiniteForm:n=!1,...r}={}){super(r),this.value=t,this.isIndefiniteForm=n}fromBER(t,n,r){const i=Z.toUint8Array(t);if(!or(this,i,n,r))return-1;if(this.valueBeforeDecodeView=i.subarray(n,n+r),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),n;let s=n;for(;H7(this.isIndefiniteForm,r)>0;){const a=qo(i,s,r);if(a.offset===-1)return this.error=a.result.error,this.warnings.concat(a.result.warnings),-1;if(s=a.offset,this.blockLength+=a.result.blockLength,r-=a.result.blockLength,this.value.push(a.result),this.isIndefiniteForm&&a.result.constructor.NAME===ia)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===ia?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,n){const r=n||new Iu;for(let i=0;i<this.value.length;i++)this.value[i].toBER(t,r);return n?Nn:r.final()}toJSON(){const t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const n of this.value)t.value.push(n.toJSON());return t}}$r.NAME="ConstructedValueBlock";var Z2;class wt extends at{constructor(t={}){super(t,$r),this.idBlock.isConstructed=!0}fromBER(t,n,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const i=this.valueBlock.fromBER(t,n,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}onAsciiEncoding(){const t=[];for(const r of this.valueBlock.value)t.push(r.toString("ascii").split(`
|
|
68
68
|
`).map(i=>` ${i}`).join(`
|
|
69
69
|
`));const n=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return t.length?`${n} :
|
|
70
70
|
${t.join(`
|
|
@@ -83,7 +83,7 @@ ${t}`):e.set("log",t)}const fN=o.z.object({grant_type:o.z.literal("refresh_token
|
|
|
83
83
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function NN(e,t){if(e){if(typeof e=="string")return ib(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ib(e,t):void 0}}function ib(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}var TN=["MOBILE","PREMIUM_RATE","TOLL_FREE","SHARED_COST","VOIP","PERSONAL_NUMBER","PAGER","UAN","VOICEMAIL"];function O_(e,t,n){if(t=t||{},!(!e.country&&!e.countryCallingCode)){n=new bt(n),n.selectNumberingPlan(e.country,e.countryCallingCode);var r=t.v2?e.nationalNumber:e.phone;if(ir(r,n.nationalNumberPattern())){if(up(r,"FIXED_LINE",n))return n.type("MOBILE")&&n.type("MOBILE").pattern()===""||!n.type("MOBILE")||up(r,"MOBILE",n)?"FIXED_LINE_OR_MOBILE":"FIXED_LINE";for(var i=jN(TN),s;!(s=i()).done;){var a=s.value;if(up(r,a,n))return a}}}}function up(e,t,n){var r=n.type(t);return!r||!r.pattern()||r.possibleLengths()&&r.possibleLengths().indexOf(e.length)<0?!1:ir(e,r.pattern())}function PN(e,t,n){if(t=t||{},n=new bt(n),n.selectNumberingPlan(e.country,e.countryCallingCode),n.hasTypes())return O_(e,t,n.metadata)!==void 0;var r=t.v2?e.nationalNumber:e.phone;return ir(r,n.nationalNumberPattern())}function ON(e,t,n){var r=new bt(n),i=r.getCountryCodesForCallingCode(e);return i?i.filter(function(s){return RN(t,s,n)}):[]}function RN(e,t,n){var r=new bt(n);return r.selectNumberingPlan(t),r.numberingPlan.possibleLengths().indexOf(e.length)>=0}var R_=2,LN=17,DN=3,mn="0-90-9٠-٩۰-۹",UN="-‐-―−ー-",BN="//",MN="..",qN=" ",FN="()()[]\\[\\]",HN="~⁓∼~",Ql="".concat(UN).concat(BN).concat(MN).concat(qN).concat(FN).concat(HN),L_="++",VN=new RegExp("(["+mn+"])");function KN(e,t,n,r){if(t){var i=new bt(r);i.selectNumberingPlan(t,n);var s=new RegExp(i.IDDPrefix());if(e.search(s)===0){e=e.slice(e.match(s)[0].length);var a=e.match(VN);if(!(a&&a[1]!=null&&a[1].length>0&&a[1]==="0"))return e}}}function GN(e,t){if(e&&t.numberingPlan.nationalPrefixForParsing()){var n=new RegExp("^(?:"+t.numberingPlan.nationalPrefixForParsing()+")"),r=n.exec(e);if(r){var i,s,a=r.length-1,c=a>0&&r[a];if(t.nationalPrefixTransformRule()&&c)i=e.replace(n,t.nationalPrefixTransformRule()),a>1&&(s=r[1]);else{var l=r[0];i=e.slice(l.length),c&&(s=r[1])}var u;if(c){var d=e.indexOf(r[1]),f=e.slice(0,d);f===t.numberingPlan.nationalPrefix()&&(u=t.numberingPlan.nationalPrefix())}else u=r[0];return{nationalNumber:i,nationalPrefix:u,carrierCode:s}}}return{nationalNumber:e}}function WN(e,t){var n=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=JN(e))||t){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
84
84
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function JN(e,t){if(e){if(typeof e=="string")return ob(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ob(e,t):void 0}}function ob(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function ZN(e,t){var n=t.countries,r=t.metadata;r=new bt(r);for(var i=WN(n),s;!(s=i()).done;){var a=s.value;if(r.selectNumberingPlan(a),r.leadingDigits()){if(e&&e.search(r.leadingDigits())===0)return a}else if(O_({phone:e,country:a},void 0,r.metadata))return a}}function Mk(e,t){var n=t.nationalNumber,r=t.metadata,i=r.getCountryCodesForCallingCode(e);if(i)return i.length===1?i[0]:ZN(n,{countries:i,metadata:r.metadata})}function H0(e,t,n){var r=GN(e,n),i=r.carrierCode,s=r.nationalNumber;if(s!==e){if(!XN(e,s,n))return{nationalNumber:e};if(n.numberingPlan.possibleLengths()&&(t||(t=Mk(n.numberingPlan.callingCode(),{nationalNumber:s,metadata:n})),!YN(s,t,n)))return{nationalNumber:e}}return{nationalNumber:s,carrierCode:i}}function XN(e,t,n){return!(ir(e,n.nationalNumberPattern())&&!ir(t,n.nationalNumberPattern()))}function YN(e,t,n){switch(P_(e,t,n)){case"TOO_SHORT":case"INVALID_LENGTH":return!1;default:return!0}}function QN(e,t,n,r,i){var s=n?T_(n,i):r;if(e.indexOf(s)===0){i=new bt(i),i.selectNumberingPlan(n,s);var a=e.slice(s.length),c=H0(a,t,i),l=c.nationalNumber,u=H0(e,t,i),d=u.nationalNumber;if(!ir(d,i.nationalNumberPattern())&&ir(l,i.nationalNumberPattern())||P_(d,t,i)==="TOO_LONG")return{countryCallingCode:s,number:a}}return{number:e}}function qk(e,t,n,r,i){if(!e)return{};var s;if(e[0]!=="+"){var a=KN(e,n,r,i);if(a&&a!==e)s=!0,e="+"+a;else{if(n||r){var c=QN(e,t,n,r,i),l=c.countryCallingCode,u=c.number;if(l)return{countryCallingCodeSource:"FROM_NUMBER_WITHOUT_PLUS_SIGN",countryCallingCode:l,number:u}}return{number:e}}}if(e[1]==="0")return{};i=new bt(i);for(var d=2;d-1<=DN&&d<=e.length;){var f=e.slice(1,d);if(i.hasCallingCode(f))return i.selectNumberingPlan(f),{countryCallingCodeSource:s?"FROM_NUMBER_WITH_IDD":"FROM_NUMBER_WITH_PLUS_SIGN",countryCallingCode:f,number:e.slice(d)};d++}return{}}function eT(e){return e.replace(new RegExp("[".concat(Ql,"]+"),"g")," ").trim()}var tT=/(\$\d)/;function nT(e,t,n){var r=n.useInternationalFormat,i=n.withNationalPrefix,s=e.replace(new RegExp(t.pattern()),r?t.internationalFormat():i&&t.nationalPrefixFormattingRule()?t.format().replace(tT,t.nationalPrefixFormattingRule()):t.format());return r?eT(s):s}var rT=/^[\d]+(?:[~\u2053\u223C\uFF5E][\d]+)?$/;function iT(e,t,n){var r=new bt(n);if(r.selectNumberingPlan(e,t),r.defaultIDDPrefix())return r.defaultIDDPrefix();if(rT.test(r.IDDPrefix()))return r.IDDPrefix()}var oT=";ext=",Fi=function(t){return"([".concat(mn,"]{1,").concat(t,"})")};function Fk(e){var t="20",n="15",r="9",i="6",s="[ \\t,]*",a="[:\\..]?[ \\t,-]*",c="#?",l="(?:e?xt(?:ensi(?:ó?|ó))?n?|e?xtn?|доб|anexo)",u="(?:[xx##~~]|int|int)",d="[- ]+",f="[ \\t]*",p="(?:,{2}|;)",h=oT+Fi(t),_=s+l+a+Fi(t)+c,g=s+u+a+Fi(r)+c,y=d+Fi(i)+"#",m=f+p+a+Fi(n)+c,v=f+"(?:,)+"+a+Fi(r)+c;return h+"|"+_+"|"+g+"|"+y+"|"+m+"|"+v}var sT="["+mn+"]{"+R_+"}",aT="["+L_+"]{0,1}(?:["+Ql+"]*["+mn+"]){3,}["+Ql+mn+"]*",cT=new RegExp("^["+L_+"]{0,1}(?:["+Ql+"]*["+mn+"]){1,2}$","i"),lT=aT+"(?:"+Fk()+")?",uT=new RegExp("^"+sT+"$|^"+lT+"$","i");function dT(e){return e.length>=R_&&uT.test(e)}function pT(e){return cT.test(e)}function fT(e){var t=e.number,n=e.ext;if(!t)return"";if(t[0]!=="+")throw new Error('"formatRFC3966()" expects "number" to be in E.164 format.');return"tel:".concat(t).concat(n?";ext="+n:"")}var sb={formatExtension:function(t,n,r){return"".concat(t).concat(r.ext()).concat(n)}};function hT(e,t,n,r){if(n?n=gT({},sb,n):n=sb,r=new bt(r),e.country&&e.country!=="001"){if(!r.hasCountry(e.country))throw new Error("Unknown country: ".concat(e.country));r.selectNumberingPlan(e.country)}else if(e.countryCallingCode)r.selectNumberingPlan(e.countryCallingCode);else return e.phone||"";var i=r.countryCallingCode(),s=n.v2?e.nationalNumber:e.phone,a;switch(t){case"NATIONAL":return s?(a=eu(s,e.carrierCode,"NATIONAL",r,n),dp(a,e.ext,r,n.formatExtension)):"";case"INTERNATIONAL":return s?(a=eu(s,null,"INTERNATIONAL",r,n),a="+".concat(i," ").concat(a),dp(a,e.ext,r,n.formatExtension)):"+".concat(i);case"E.164":return"+".concat(i).concat(s);case"RFC3966":return fT({number:"+".concat(i).concat(s),ext:e.ext});case"IDD":if(!n.fromCountry)return;var c=mT(s,e.carrierCode,i,n.fromCountry,r);return c?dp(c,e.ext,r,n.formatExtension):void 0;default:throw new Error('Unknown "format" argument passed to "formatNumber()": "'.concat(t,'"'))}}function eu(e,t,n,r,i){var s=_T(r.formats(),e);return s?nT(e,s,{useInternationalFormat:n==="INTERNATIONAL",withNationalPrefix:!(s.nationalPrefixIsOptionalWhenFormattingInNationalFormat()&&i&&i.nationalPrefix===!1)}):e}function _T(e,t){return yT(e,function(n){if(n.leadingDigitsPatterns().length>0){var r=n.leadingDigitsPatterns()[n.leadingDigitsPatterns().length-1];if(t.search(r)!==0)return!1}return ir(t,n.pattern())})}function dp(e,t,n,r){return t?r(e,t,n):e}function mT(e,t,n,r,i){var s=T_(r,i.metadata);if(s===n){var a=eu(e,t,"NATIONAL",i);return n==="1"?n+" "+a:a}var c=iT(r,void 0,i.metadata);if(c)return"".concat(c," ").concat(n," ").concat(eu(e,null,"INTERNATIONAL",i))}function gT(){for(var e=1,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];for(;e<n.length;){if(n[e])for(var i in n[e])n[0][i]=n[e][i];e++}return n[0]}function yT(e,t){for(var n=0;n<e.length;){if(t(e[n]))return e[n];n++}}function _a(e){"@babel/helpers - typeof";return _a=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_a(e)}function ab(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function cb(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?ab(Object(n),!0).forEach(function(r){bT(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ab(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function bT(e,t,n){return(t=Hk(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function vT(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function wT(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,Hk(r.key),r)}}function kT(e,t,n){return t&&wT(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Hk(e){var t=$T(e,"string");return _a(t)=="symbol"?t:t+""}function $T(e,t){if(_a(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(_a(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var xT=(function(){function e(t,n,r){if(vT(this,e),!t)throw new TypeError("First argument is required");if(typeof t!="string")throw new TypeError("First argument must be a string");if(t[0]==="+"&&!n)throw new TypeError("`metadata` argument not passed");if(fo(n)&&fo(n.countries)){r=n;var i=t;if(!AT.test(i))throw new Error('Invalid `number` argument passed: must consist of a "+" followed by digits');var s=qk(i,void 0,void 0,void 0,r),a=s.countryCallingCode,c=s.number;if(n=c,t=a,!n)throw new Error("Invalid `number` argument passed: too short")}if(!n)throw new TypeError("`nationalNumber` argument is required");if(typeof n!="string")throw new TypeError("`nationalNumber` argument must be a string");Dk(r);var l=zT(t,r),u=l.country,d=l.countryCallingCode;this.country=u,this.countryCallingCode=d,this.nationalNumber=n,this.number="+"+this.countryCallingCode+this.nationalNumber,this.getMetadata=function(){return r}}return kT(e,[{key:"setExt",value:function(n){this.ext=n}},{key:"getPossibleCountries",value:function(){return this.country?[this.country]:ON(this.countryCallingCode,this.nationalNumber,this.getMetadata())}},{key:"isPossible",value:function(){return IN(this,{v2:!0},this.getMetadata())}},{key:"isValid",value:function(){return PN(this,{v2:!0},this.getMetadata())}},{key:"isNonGeographic",value:function(){var n=new bt(this.getMetadata());return n.isNonGeographicCallingCode(this.countryCallingCode)}},{key:"isEqual",value:function(n){return this.number===n.number&&this.ext===n.ext}},{key:"getType",value:function(){return O_(this,{v2:!0},this.getMetadata())}},{key:"format",value:function(n,r){return hT(this,n,r?cb(cb({},r),{},{v2:!0}):{v2:!0},this.getMetadata())}},{key:"formatNational",value:function(n){return this.format("NATIONAL",n)}},{key:"formatInternational",value:function(n){return this.format("INTERNATIONAL",n)}},{key:"getURI",value:function(n){return this.format("RFC3966",n)}}])})(),ST=function(t){return/^[A-Z]{2}$/.test(t)};function zT(e,t){var n,r,i=new bt(t);return ST(e)?(n=e,i.selectNumberingPlan(n),r=i.countryCallingCode()):r=e,{country:n,countryCallingCode:r}}var AT=/^\+\d+$/;function V0(e){"@babel/helpers - typeof";return V0=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},V0(e)}function ET(e,t,n){return Object.defineProperty(e,"prototype",{writable:!1}),e}function CT(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function IT(e,t,n){return t=ga(t),jT(e,D_()?Reflect.construct(t,n||[],ga(e).constructor):t.apply(e,n))}function jT(e,t){if(t&&(V0(t)=="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return NT(e)}function NT(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function TT(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&ma(e,t)}function K0(e){var t=typeof Map=="function"?new Map:void 0;return K0=function(r){if(r===null||!OT(r))return r;if(typeof r!="function")throw new TypeError("Super expression must either be null or a function");if(t!==void 0){if(t.has(r))return t.get(r);t.set(r,i)}function i(){return PT(r,arguments,ga(this).constructor)}return i.prototype=Object.create(r.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),ma(i,r)},K0(e)}function PT(e,t,n){if(D_())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&ma(i,n.prototype),i}function D_(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(D_=function(){return!!e})()}function OT(e){try{return Function.toString.call(e).indexOf("[native code]")!==-1}catch{return typeof e=="function"}}function ma(e,t){return ma=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},ma(e,t)}function ga(e){return ga=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},ga(e)}var Gn=(function(e){function t(n){var r;return CT(this,t),r=IT(this,t,[n]),Object.setPrototypeOf(r,t.prototype),r.name=r.constructor.name,r}return TT(t,e),ET(t)})(K0(Error)),lb=new RegExp("(?:"+Fk()+")$","i");function RT(e){var t=e.search(lb);if(t<0)return{};for(var n=e.slice(0,t),r=e.match(lb),i=1;i<r.length;){if(r[i])return{number:n,ext:r[i]};i++}}var LT={0:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9","0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9","٠":"0","١":"1","٢":"2","٣":"3","٤":"4","٥":"5","٦":"6","٧":"7","٨":"8","٩":"9","۰":"0","۱":"1","۲":"2","۳":"3","۴":"4","۵":"5","۶":"6","۷":"7","۸":"8","۹":"9"};function DT(e){return LT[e]}function UT(e,t){var n=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=BT(e))||t){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
85
85
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function BT(e,t){if(e){if(typeof e=="string")return ub(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ub(e,t):void 0}}function ub(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function db(e){for(var t="",n=UT(e.split("")),r;!(r=n()).done;){var i=r.value;t+=MT(i,t)||""}return t}function MT(e,t,n){return e==="+"?t?void 0:"+":DT(e)}var Vk="+",qT="[\\-\\.\\(\\)]?",pb="(["+mn+"]|"+qT+")",FT="^\\"+Vk+pb+"*["+mn+"]"+pb+"*$",HT=new RegExp(FT,"g"),G0=mn,VT="["+G0+"]+((\\-)*["+G0+"])*",KT="a-zA-Z",GT="["+KT+"]+((\\-)*["+G0+"])*",WT="^("+VT+"\\.)*"+GT+"\\.?$",JT=new RegExp(WT,"g"),fb="tel:",W0=";phone-context=",ZT=";isub=";function XT(e){var t=e.indexOf(W0);if(t<0)return null;var n=t+W0.length;if(n>=e.length)return"";var r=e.indexOf(";",n);return r>=0?e.substring(n,r):e.substring(n)}function YT(e){return e===null?!0:e.length===0?!1:HT.test(e)||JT.test(e)}function QT(e,t){var n=t.extractFormattedPhoneNumber,r=XT(e);if(!YT(r))throw new Gn("NOT_A_NUMBER");var i;if(r===null)i=n(e)||"";else{i="",r.charAt(0)===Vk&&(i+=r);var s=e.indexOf(fb),a;s>=0?a=s+fb.length:a=0;var c=e.indexOf(W0);i+=e.substring(a,c)}var l=i.indexOf(ZT);if(l>0&&(i=i.substring(0,l)),i!=="")return i}var eP=250,tP=new RegExp("["+L_+mn+"]"),nP=new RegExp("[^"+mn+"#]+$");function rP(e,t,n){if(t=t||{},n=new bt(n),t.defaultCountry&&!n.hasCountry(t.defaultCountry))throw t.v2?new Gn("INVALID_COUNTRY"):new Error("Unknown country: ".concat(t.defaultCountry));var r=oP(e,t.v2,t.extract),i=r.number,s=r.ext,a=r.error;if(!i){if(t.v2)throw a==="TOO_SHORT"?new Gn("TOO_SHORT"):new Gn("NOT_A_NUMBER");return{}}var c=aP(i,t.defaultCountry,t.defaultCallingCode,n),l=c.country,u=c.nationalNumber,d=c.countryCallingCode,f=c.countryCallingCodeSource,p=c.carrierCode;if(!n.hasSelectedNumberingPlan()){if(t.v2)throw new Gn("INVALID_COUNTRY");return{}}if(!u||u.length<R_){if(t.v2)throw new Gn("TOO_SHORT");return{}}if(u.length>LN){if(t.v2)throw new Gn("TOO_LONG");return{}}if(t.v2){var h=new xT(d,u,n.metadata);return l&&(h.country=l),p&&(h.carrierCode=p),s&&(h.ext=s),h.__countryCallingCodeSource=f,h}var _=(t.extended?n.hasSelectedNumberingPlan():l)?ir(u,n.nationalNumberPattern()):!1;return t.extended?{country:l,countryCallingCode:d,carrierCode:p,valid:_,possible:_?!0:!!(t.extended===!0&&n.possibleLengths()&&Bk(u,l,n)),phone:u,ext:s}:_?sP(l,u,s):{}}function iP(e,t,n){if(e){if(e.length>eP){if(n)throw new Gn("TOO_LONG");return}if(t===!1)return e;var r=e.search(tP);if(!(r<0))return e.slice(r).replace(nP,"")}}function oP(e,t,n){var r=QT(e,{extractFormattedPhoneNumber:function(a){return iP(a,n,t)}});if(!r)return{};if(!dT(r))return pT(r)?{error:"TOO_SHORT"}:{};var i=RT(r);return i.ext?i:{number:r}}function sP(e,t,n){var r={country:e,phone:t};return n&&(r.ext=n),r}function aP(e,t,n,r){var i=qk(db(e),void 0,t,n,r.metadata),s=i.countryCallingCodeSource,a=i.countryCallingCode,c=i.number,l;if(a)r.selectNumberingPlan(a);else if(c&&(t||n))r.selectNumberingPlan(t,n),t&&(l=t),a=n||T_(t,r.metadata);else return{};if(!c)return{countryCallingCodeSource:s,countryCallingCode:a};var u=H0(db(c),l,r),d=u.nationalNumber,f=u.carrierCode,p=Mk(a,{nationalNumber:d,metadata:r});return p&&(l=p,p==="001"||r.selectNumberingPlan(l)),{country:l,countryCallingCode:a,countryCallingCodeSource:s,nationalNumber:d,carrierCode:f}}function ya(e){"@babel/helpers - typeof";return ya=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ya(e)}function hb(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function _b(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?hb(Object(n),!0).forEach(function(r){cP(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):hb(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function cP(e,t,n){return(t=lP(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function lP(e){var t=uP(e,"string");return ya(t)=="symbol"?t:t+""}function uP(e,t){if(ya(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(ya(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function dP(e,t,n){return rP(e,_b(_b({},t),{},{v2:!0}),n)}function ba(e){"@babel/helpers - typeof";return ba=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ba(e)}function mb(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function pP(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?mb(Object(n),!0).forEach(function(r){fP(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):mb(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function fP(e,t,n){return(t=hP(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function hP(e){var t=_P(e,"string");return ba(t)=="symbol"?t:t+""}function _P(e,t){if(ba(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(ba(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function mP(e,t){return vP(e)||bP(e,t)||yP(e,t)||gP()}function gP(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
86
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function yP(e,t){if(e){if(typeof e=="string")return gb(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?gb(e,t):void 0}}function gb(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function bP(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,s,a,c=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(l=(r=s.call(n)).done)&&(c.push(r.value),c.length!==t);l=!0);}catch(d){u=!0,i=d}finally{try{if(!l&&n.return!=null&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw i}}return c}}function vP(e){if(Array.isArray(e))return e}function wP(e){var t=Array.prototype.slice.call(e),n=mP(t,4),r=n[0],i=n[1],s=n[2],a=n[3],c,l,u;if(typeof r=="string")c=r;else throw new TypeError("A text for parsing must be a string.");if(!i||typeof i=="string")a?(l=s,u=a):(l=void 0,u=s),i&&(l=pP({defaultCountry:i},l));else if(fo(i))s?(l=i,u=s):u=i;else throw new Error("Invalid second argument: ".concat(i));return{text:c,options:l,metadata:u}}function va(e){"@babel/helpers - typeof";return va=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},va(e)}function yb(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function bb(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?yb(Object(n),!0).forEach(function(r){kP(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):yb(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function kP(e,t,n){return(t=$P(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function $P(e){var t=xP(e,"string");return va(t)=="symbol"?t:t+""}function xP(e,t){if(va(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(va(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function SP(e,t,n){t&&t.defaultCountry&&!EN(t.defaultCountry,n)&&(t=bb(bb({},t),{},{defaultCountry:void 0}));try{return dP(e,t,n)}catch(r){if(!(r instanceof Gn))throw r}}function zP(){var e=wP(arguments),t=e.text,n=e.options,r=e.metadata;return SP(t,n,r)}function AP(){return mN(zP,arguments)}function ns(e,t="US"){const n=e.trim();if(n.includes("@")){const r=n.toLowerCase(),i=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r);return{connectionType:"email",normalized:i?r:null,isValid:i,provider:"email"}}else if(/^\+?\d[\d\s\-().]*$/.test(n)){const r=AP(n,{defaultCountry:t});return r&&r.isValid()?{connectionType:"sms",normalized:r.number,isValid:!0,provider:"sms"}:{connectionType:"sms",normalized:null,isValid:!1,provider:"sms"}}else return{connectionType:"username",normalized:n,isValid:!0,provider:Pe}}function U_(e){let t=e.trim();t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1));const n=t.indexOf("%");return n!==-1&&(t=t.slice(0,n)),t}function EP(e){const n=U_(e).split(".");return n.length!==4?!1:n.every(r=>/^\d+$/.test(r)&&Number(r)>=0&&Number(r)<=255)}function CP(e){const t=U_(e);if(t.length<2||t.indexOf(":")===-1||!/^[0-9a-fA-F:.]+$/.test(t))return!1;const n=t.split(":");return t.includes("::")?n.length<=8:n.length===8}function IP(e){let t=e.trim();const n=/^\[([^\]]+)\](?::\d+)?$/,r=t.match(n);if(r&&r[1])return r[1];const i=t.lastIndexOf(":");if(i!==-1){const s=t.slice(0,i),a=t.slice(i+1);/^[0-9.]+$/.test(s)&&/^\d+$/.test(a)&&(t=s)}return t}function vb(e){if(!e)return null;const t=U_(IP(e));return EP(t)?{family:4,normalized:t}:CP(t)?{family:6,normalized:t.toLowerCase()}:null}function wb(e){if(e.includes("::")){let[t,n]=e.split("::"),r=t?t.split(":").filter(Boolean):[],i=n?n.split(":").filter(Boolean):[],s=8-(r.length+i.length);return[...r.map(a=>a.toLowerCase()||"0"),...Array(s).fill("0"),...i.map(a=>a.toLowerCase()||"0")]}else return e.split(":").map(t=>t.toLowerCase()||"0")}function jP(e,t,n=!0){const r=vb(e),i=vb(t);if(!r||!i||r.family!==i.family)return!1;if(r.family===4)return r.normalized===i.normalized;const s=wb(r.normalized),a=wb(i.normalized);return n?s.length===8&&a.length===8&&s.join(":")===a.join(":"):s.slice(0,4).join(":")===a.slice(0,4).join(":")}class qt extends Error{location;status;constructor(t,n=302){super(`Redirect to ${t}`),this.name=qt.name,this.location=t,this.status=n}}const NP=o.z.object({client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),otp:o.z.string(),authParams:Js.optional(),enforceIpCheck:o.z.boolean().optional().default(!1)});async function Kk(e,{client_id:t,username:n,otp:r,authParams:i,enforceIpCheck:s=!1}){const a=e.get("ip"),c=e.get("countryCode"),{connectionType:l,normalized:u}=ns(n,c);if(!u)throw new W(400,{message:"Invalid username format"});const d=await He(e.env,t,e.var.tenant_id),{env:f}=e,p=await f.data.codes.get(d.tenant.id,r,"otp");if(!p)throw new W(400,{message:he("code_invalid")});if(p.expires_at<new Date().toISOString())throw new W(400,{message:he("code_expired")});if(p.used_at)throw new W(400,{message:he("code_used")});const h=await f.data.loginSessions.get(d.tenant.id,p.login_id);if(!h||h.authParams.username!==n)throw new W(400,{message:"Code not found or expired"});if(s&&h.ip&&a&&!jP(h.ip,a))throw new qt(`${_t(e.env)}invalid-session?state=${h.id}`);const _=await Au(e,{client:d,username:u,provider:l,connection:l,isSocial:!1,ip:e.var.ip});return await f.data.codes.used(d.tenant.id,r),{user:_,client:d,loginSession:h,session_id:h.session_id,authParams:{...h.authParams,...i||{}}}}async function xd(e,t){const n=await Kk(e,t);return gt(e,{authParams:n.authParams,client:n.client,user:n.user,loginSession:n.loginSession,authStrategy:{strategy:"email",strategy_type:"passwordless"}})}const kb=o.z.object({client_id:o.z.string().optional(),client_secret:o.z.string().optional()}),$b=o.z.union([Lk.extend(kb.shape),o.z.object({grant_type:o.z.literal("authorization_code"),client_id:o.z.string(),code:o.z.string(),redirect_uri:o.z.string(),code_verifier:o.z.string().min(43).max(128),organization:o.z.string().optional()}),o.z.object({grant_type:o.z.literal("authorization_code"),code:o.z.string(),redirect_uri:o.z.string().optional(),organization:o.z.string().optional(),...kb.shape}),o.z.object({grant_type:o.z.literal("refresh_token"),client_id:o.z.string().optional(),refresh_token:o.z.string(),redirect_uri:o.z.string().optional(),client_secret:o.z.string().optional()}),o.z.object({grant_type:o.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),client_id:o.z.string(),username:o.z.string(),otp:o.z.string(),realm:o.z.enum(["email","sms"])})]);function TP(e){if(!e)return{};const[t,n]=e.split(" ");if(t?.toLowerCase()==="basic"&&n){const[r,i]=atob(n).split(":");return{client_id:r,client_secret:i}}return{}}const PP=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:$b},"application/json":{schema:$b}}}},responses:{200:{content:{"application/json":{schema:vh}},description:"Tokens"},302:{description:"Redirect for further user interaction (e.g., MFA, consent).",headers:o.z.object({Location:o.z.string().url()}).openapi({})},400:{description:"Bad Request - The request was malformed or invalid.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},401:{description:"Unauthorized - Client authentication failed.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},403:{description:"Forbidden - User is not a member of the required organization.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}}}}),async e=>{const n=(e.req.header("Content-Type")||"").includes("application/json")?e.req.valid("json"):e.req.valid("form"),r=TP(e.req.header("Authorization")),i={...n,...r};if(!i.client_id)throw new I(400,{message:"client_id is required"});e.set("client_id",i.client_id);let s;switch(n.grant_type){case an.AuthorizationCode:s=await pN(e,dN.parse(i));break;case an.ClientCredential:s=await uN(e,Lk.parse(i));break;case an.RefreshToken:s=await hN(e,fN.parse(i));break;case an.OTP:s=await Kk(e,NP.parse(i));break;default:return e.json({error:"unsupported_grant_type",error_description:"Grant type not implemented"},400)}Vt(e,s.client.tenant.id);const a=new Headers;s.session_id&&sl(s.client.tenant.id,s.session_id,e.var.host||"").forEach(d=>{a.append("Set-Cookie",d)});let c=[];if(s.authParams.audience)try{let u;if(n.grant_type===an.ClientCredential)u=await Ys(e,{grantType:an.ClientCredential,tenantId:s.client.tenant.id,clientId:s.client.client_id,audience:s.authParams.audience,requestedScopes:s.authParams.scope?.split(" ")||[],organizationId:s.organization?.id});else{if(!s.user?.user_id)throw new W(400,{error:"invalid_request",error_description:"User ID is required for user-based grants"});u=await Ys(e,{grantType:n.grant_type,tenantId:s.client.tenant.id,userId:s.user.user_id,clientId:s.client.client_id,audience:s.authParams.audience,requestedScopes:s.authParams.scope?.split(" ")||[],organizationId:s.organization?.id})}s.authParams.scope=u.scopes.join(" "),c=u.permissions}catch(u){if(u instanceof I)throw u;console.error("Error calculating scopes and permissions:",u)}const l=await gu(e,{...s,grantType:n.grant_type,permissions:c.length>0?c:void 0});return e.json(l,{headers:a})});async function Za(e,t){const n=await e.env.data.emailProviders.get(e.var.tenant_id);if(!n)throw new I(500,{message:"Email provider not found"});const r=e.env.emailProviders?.[n.name];if(!r)throw new I(500,{message:"Email provider not found"});await r({emailProvider:n,...t,from:n.default_from_address||`login@${e.env.ISSUER}`})}async function Gk(e,t){if(!e.var.client_id)throw new I(500,{message:"Client not found"});const n=await He(e.env,e.var.client_id),r=n.connections.find(a=>a.strategy==="sms");if(!r)throw new I(500,{message:"SMS provider not found"});const i=r.options?.provider||"twilio",s=e.env.smsProviders?.[i];if(!s)throw new I(500,{message:"SMS provider not found"});await s({options:r.options,to:t.to,from:t.from,text:t.text,template:"auth-code",data:{code:t.code,tenantName:n.tenant.friendly_name,tenantId:n.tenant.id}})}async function Wk(e,t,n,r,i){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});const a=`${_t(e.env)}reset-password?state=${r}&code=${n}`,c=await e.env.data.branding.get(e.var.tenant_id),l=c?.logo_url||"",u=c?.colors?.primary||"#7d68f4",d={vendorName:s.friendly_name,lng:"en"};await Za(e,{to:t,subject:he("reset_password_title",d),html:`Click here to reset your password: ${_t(e.env)}reset-password?state=${r}&code=${n}`,template:"auth-password-reset",data:{vendorName:s.friendly_name,logo:l,passwordResetUrl:a,supportUrl:s.support_url||"https://support.sesamy.com",buttonColor:u,passwordResetTitle:he("password_reset_title",d),resetPasswordEmailClickToReset:he("reset_password_email_click_to_reset",d),resetPasswordEmailReset:he("reset_password_email_reset",d),supportInfo:he("support_info",d),contactUs:he("contact_us",d),copyright:he("copyright",d),tenantName:s.friendly_name,tenantId:s.id}}),fe(e,s.id,{type:ue.SUCCESS_CHANGE_PASSWORD_REQUEST,description:t})}async function Sd(e,{to:t,code:n,language:r}){const i=await e.env.data.tenants.get(e.var.tenant_id);if(!i)throw new I(500,{message:"Tenant not found"});const{connectionType:s}=ns(t),a=await e.env.data.branding.get(e.var.tenant_id),c=a?.logo_url||"",l=a?.colors?.primary||"#7d68f4",u=new URL(_t(e.env)),d={vendorName:i.friendly_name,vendorId:i.id,loginDomain:u.hostname,code:n,lng:r||"en"};s==="email"?await Za(e,{to:t,subject:he("code_email_subject",d),html:`Click here to validate your email: ${_t(e.env)}validate-email`,template:"auth-code",data:{code:n,vendorName:i.friendly_name,logo:c,supportUrl:i.support_url||"",buttonColor:l,welcomeToYourAccount:he("welcome_to_your_account",d),linkEmailClickToLogin:he("link_email_click_to_login",d),linkEmailLogin:he("link_email_login",d),linkEmailOrEnterCode:he("link_email_or_enter_code",d),codeValid30Mins:he("code_valid_30_minutes",d),supportInfo:he("support_info",d),contactUs:he("contact_us",d),copyright:he("copyright",d)}}):s==="sms"&&await Gk(e,{to:t,text:he("sms_code_text",d),code:n,from:i.friendly_name}),fe(e,i.id,{type:ue.CODE_LINK_SENT,description:t})}async function zd(e,{to:t,code:n,authParams:r,language:i}){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});if(!r.redirect_uri)throw new I(400,{message:"redirect_uri is required"});const{connectionType:a}=ns(t),c=await e.env.data.branding.get(e.var.tenant_id),l=c?.logo_url||"",u=c?.colors?.primary||"",d=new URL(Le(e.env));d.pathname="passwordless/verify_redirect",d.searchParams.set("verification_code",n),d.searchParams.set("connection",a),d.searchParams.set("client_id",r.client_id),d.searchParams.set("redirect_uri",r.redirect_uri),d.searchParams.set("email",t),r.response_type&&d.searchParams.set("response_type",r.response_type),r.scope&&d.searchParams.set("scope",r.scope),r.state&&d.searchParams.set("state",r.state),r.nonce&&d.searchParams.set("nonce",r.nonce),r.code_challenge&&d.searchParams.set("code_challenge",r.code_challenge),r.code_challenge_method&&d.searchParams.set("code_challenge_method",r.code_challenge_method),r.audience&&d.searchParams.set("audience",r.audience);const f={vendorName:s.friendly_name,code:n,lng:i||"en"};if(a==="email")await Za(e,{to:t,subject:he("code_email_subject",f),html:`Click here to validate your email: ${_t(e.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:s.friendly_name,logo:l,supportUrl:s.support_url||"",magicLink:d.toString(),buttonColor:u,welcomeToYourAccount:he("welcome_to_your_account",f),linkEmailClickToLogin:he("link_email_click_to_login",f),linkEmailLogin:he("link_email_login",f),linkEmailOrEnterCode:he("link_email_or_enter_code",f),codeValid30Mins:he("code_valid_30_minutes",f),supportInfo:he("support_info",f),contactUs:he("contact_us",f),copyright:he("copyright",f)}});else if(a==="sms")await Gk(e,{to:t,text:`${he("link_sms_login",f)}: ${d.toString()}`,code:n,from:s.friendly_name});else throw new I(400,{message:"Only email and SMS connections are supported for magic links"});fe(e,s.id,{type:ue.CODE_LINK_SENT,description:t})}async function Ad(e,t,n){const r=await e.env.data.tenants.get(e.var.tenant_id);if(!r)throw new I(500,{message:"Tenant not found"});if(!t.email)throw new I(400,{message:"User has no email"});const i=await e.env.data.branding.get(e.var.tenant_id),s=i?.logo_url||"",a=i?.colors?.primary||"#7d68f4",c={vendorName:r.friendly_name,lng:n||"en"};await Za(e,{to:t.email,subject:he("welcome_to_your_account",c),html:`Click here to validate your email: ${_t(e.env)}validate-email`,template:"auth-verify-email",data:{vendorName:r.friendly_name,logo:s,emailValidationUrl:`${_t(e.env)}validate-email`,supportUrl:r.support_url||"https://support.sesamy.com",buttonColor:a,welcomeToYourAccount:he("welcome_to_your_account",c),verifyEmailVerify:he("verify_email_verify",c),supportInfo:he("support_info",c),contactUs:he("contact_us",c),copyright:he("copyright",c)}})}async function OP(e,t,n,r,i){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});const a=await e.env.data.branding.get(e.var.tenant_id),c=a?.logo_url||"",l=a?.colors?.primary||"#7d68f4",u={vendorName:s.friendly_name,lng:"en"},d=`${_t(e.env)}signup?state=${r}&code=${n}`;await Za(e,{to:t,subject:he("register_password_account",u),html:`Click here to register: ${d}`,template:"auth-pre-signup-verification",data:{vendorName:s.friendly_name,logo:c,signupUrl:d,setPassword:he("set_password",u),registerPasswordAccount:he("register_password_account",u),clickToSignUpDescription:he("click_to_sign_up_description",u),supportUrl:s.support_url||"https://support.sesamy.com",buttonColor:l,welcomeToYourAccount:he("welcome_to_your_account",u),verifyEmailVerify:he("verify_email_verify",u),supportInfo:he("support_info",u),contactUs:he("contact_us",u),copyright:he("copyright",u)}})}const RP=new o.OpenAPIHono().openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/signup",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(e=>e.toLowerCase()),password:o.z.string()})}}}},responses:{200:{content:{"application/json":{schema:o.z.object({_id:o.z.string(),email:o.z.string().optional(),email_verified:o.z.boolean(),app_metadata:o.z.object({}),user_metadata:o.z.object({})})}},description:"Created user"}}}),async e=>{const{email:t,password:n,client_id:r}=e.req.valid("json"),i=await He(e.env,r);e.set("client_id",i.client_id),Vt(e,i.tenant.id);const a=i.connections.find(p=>p.strategy==="Username-Password-Authentication")?.name||"Username-Password-Authentication",c=await Ca(e.env.data,i.tenant.id,a);try{await Ea(c,{tenantId:i.tenant.id,userId:"",newPassword:n,data:e.env.data})}catch(p){throw new I(400,{message:p?.message||"Password does not meet the requirements"})}if(await Xn({userAdapter:e.env.data.users,tenant_id:i.tenant.id,username:t,provider:Pe}))throw new I(400,{message:"Invalid sign up"});const{hash:u,algorithm:d}=await na(n),f=await e.env.data.users.create(i.tenant.id,{user_id:`${Pe}|${Ii()}`,email:t,email_verified:!1,provider:Pe,connection:"Username-Password-Authentication",is_social:!1,password:{hash:u,algorithm:d}});e.set("user_id",f.user_id),e.set("username",f.email),e.set("connection",f.connection);try{await Ad(e,f)}catch(p){console.error("Failed to send verification email:",p)}return fe(e,i.tenant.id,{type:ue.SUCCESS_SIGNUP,description:"Successful signup"}),e.json({_id:f.user_id,email:f.email,email_verified:!1,app_metadata:{},user_metadata:{}})}).openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/change_password",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(e=>e.toLowerCase())})}}}},responses:{200:{description:"Redirect to the client's redirect uri"}}}),async e=>{const{email:t,client_id:n}=e.req.valid("json"),r=await He(e.env,n);if(e.set("client_id",r.client_id),Vt(e,r.tenant.id),!await Or({userAdapter:e.env.data.users,tenant_id:r.tenant.id,username:t,provider:Pe}))return e.html("If an account with that email exists, we've sent instructions to reset your password.");const s={client_id:n,username:t},a=await e.env.data.loginSessions.create(r.tenant.id,{expires_at:new Date(Date.now()+li*1e3).toISOString(),authParams:s,csrf_token:Oe(),ip:e.get("ip"),useragent:e.get("useragent"),auth0Client:rr(e.get("auth0_client"))});return await Wk(e,t,a.id,a.authParams.state),e.html("If an account with that email exists, we've sent instructions to reset your password.")});function In(){const e="1234567890";let t="";for(let n=0;n<6;n+=1)t+=e[Math.floor(Math.random()*10)];return t.toString()}const LP=new o.OpenAPIHono().openapi(o.createRoute({tags:["passwordless"],method:"post",path:"/start",request:{body:{content:{"application/json":{schema:o.z.union([o.z.object({connection:o.z.literal("email"),client_id:o.z.string(),email:o.z.string().transform(e=>e.toLowerCase()),send:o.z.enum(["link","code"]),authParams:Js.omit({client_id:!0})}),o.z.object({client_id:o.z.string(),connection:o.z.literal("sms"),phone_number:o.z.string(),send:o.z.enum(["link","code"]),authParams:Js.omit({client_id:!0})})])}}}},responses:{200:{description:"Status"}}}),async e=>{const t=e.req.valid("json"),{env:n}=e,{client_id:r,send:i,authParams:s,connection:a}=t,c=await He(e.env,r);e.set("client_id",c.client_id),Vt(e,c.tenant.id);const l=a==="email"?t.email:t.phone_number,u=e.get("ip"),d=e.get("useragent"),f=e.get("auth0_client"),p=rr(f),h=await n.data.loginSessions.create(c.tenant.id,{authParams:{...s,client_id:r,username:l},expires_at:new Date(Date.now()+Ds).toISOString(),csrf_token:Oe(),ip:u,useragent:d,auth0Client:p}),_=await n.data.codes.create(c.tenant.id,{code_id:In(),code_type:"otp",login_id:h.id,expires_at:new Date(Date.now()+Ds).toISOString(),redirect_uri:s.redirect_uri}),g=s?.ui_locales?.split(" ")?.map(y=>y.split("-")[0])[0];return i==="link"?await zd(e,{to:l,code:_.code_id,authParams:{...s,client_id:r},language:g}):await Sd(e,{to:l,code:_.code_id,language:g}),e.html("OK")}).openapi(o.createRoute({tags:["passwordless"],method:"get",path:"/verify_redirect",request:{query:o.z.object({scope:o.z.string(),response_type:o.z.nativeEnum(ot),redirect_uri:o.z.string(),state:o.z.string(),nonce:o.z.string().optional(),verification_code:o.z.string(),connection:o.z.string(),client_id:o.z.string(),email:o.z.string().transform(e=>e.toLowerCase()),audience:o.z.string().optional()})},responses:{302:{description:"Successful verification, redirecting to continue flow.",headers:o.z.object({Location:o.z.string().url()}).openapi({})},400:{description:"Bad Request (e.g., invalid client, invalid code, missing parameters).",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},500:{description:"Internal Server Error.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}}}}),async e=>{const{env:t}=e,{client_id:n,email:r,verification_code:i,redirect_uri:s,state:a,scope:c,audience:l,response_type:u,nonce:d}=e.req.valid("query"),f=await He(t,n);e.set("client_id",f.client_id),Vt(e,f.tenant.id),e.set("connection","email");const p={client_id:n,redirect_uri:s,state:a,nonce:d,scope:c,audience:l,response_type:u};let h="Something went wrong. Please try again later.";try{const k=await xd(e,{client_id:n,username:r,otp:i,authParams:p,enforceIpCheck:!0});if(k instanceof Response)return k;if(k&&typeof k=="object"&&"access_token"in k)return e.json(k)}catch(k){const x=k;"message"in x&&typeof x.message=="string"&&(h=x.message)}const _=e.get("ip"),g=e.get("useragent"),y=e.get("auth0_client"),m=rr(y),v=await t.data.loginSessions.create(f.tenant.id,{authParams:{...p,username:r},expires_at:new Date(Date.now()+Ds).toISOString(),csrf_token:Oe(),ip:_,useragent:g,auth0Client:m});return e.redirect(`${_t(e.env)}invalid-session?state=${v.id}&error=${encodeURIComponent(h)}`,302)});class Zi extends I{_code;constructor(t,n){super(t,n),this._code=n?.code}get code(){return this._code}}async function DP(e,t,n){const r=n.app_metadata||{},i=r.failed_logins||[],s=Date.now(),a=[...i.filter(c=>s-c<1e3*60*5),s];r.failed_logins=a,await e.users.update(t,n.user_id,{app_metadata:r})}function UP(e){const n=(e.app_metadata||{}).failed_logins||[],r=Date.now();return n.filter(i=>r-i<1e3*60*5)}async function Jk(e,t,n,r){const{data:i}=e.env,{username:s}=n;if(e.set("username",s),!s)throw new W(400,{message:"Username is required"});const a=await Or({userAdapter:e.env.data.users,tenant_id:t.tenant.id,username:s,provider:Pe});if(!a)throw fe(e,t.tenant.id,{type:ue.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"}),new Zi(403,{message:"User not found",code:"USER_NOT_FOUND"});const c=a.linked_to?await i.users.get(t.tenant.id,a.linked_to):a;if(!c)throw new Zi(403,{message:"User not found",code:"USER_NOT_FOUND"});if(e.set("connection",a.connection),e.set("user_id",c.user_id),UP(c).length>=3)throw fe(e,t.tenant.id,{type:ue.FAILED_LOGIN,description:"Too many failed login attempts"}),new Zi(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"});const u=await i.passwords.get(t.tenant.id,a.user_id);if(!(u&&await Bo.compare(n.password,u.password)))throw fe(e,t.tenant.id,{type:ue.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"}),DP(i,t.tenant.id,c),new Zi(403,{message:"Invalid password",code:"INVALID_PASSWORD"});if(!a.email_verified&&t.client_metadata?.email_validation==="enforced"){const p=r?.authParams?.ui_locales?.split(" ")?.map(h=>h.split("-")[0])[0];throw await Ad(e,a,p),fe(e,t.tenant.id,{type:ue.FAILED_LOGIN,description:"Email not verified"}),r&&await TA(e,t.tenant.id,r,"Email not verified"),new Zi(403,{message:"Email not verified",code:"EMAIL_NOT_VERIFIED"})}const f=c.app_metadata||{};return f.failed_logins&&f.failed_logins.length>0&&(f.failed_logins=[],i.users.update(t.tenant.id,c.user_id,{app_metadata:f})),{client:t,authParams:n,user:c,loginSession:r}}async function Xa(e,t,n,r,i){const s=await Jk(e,t,n,r);return gt(e,{...s,ticketAuth:i,authStrategy:{strategy:"Username-Password-Authentication",strategy_type:"database"}})}async function BP(e,t,n,r){await Au(e,{client:t,username:n,provider:Pe,connection:"Username-Password-Authentication",isSocial:!1,ip:e.var.ip});let i=In(),s=await e.env.data.codes.get(t.tenant.id,i,"password_reset");for(;s;)i=In(),s=await e.env.data.codes.get(t.tenant.id,i,"password_reset");const a=e.get("ip"),c=e.get("useragent"),l=e.get("auth0_client"),u=rr(l),d=await e.env.data.loginSessions.create(t.tenant.id,{expires_at:new Date(Date.now()+Sz).toISOString(),authParams:{client_id:t.client_id,username:n},csrf_token:Oe(),ip:a,useragent:c,auth0Client:u}),f=await e.env.data.codes.create(t.tenant.id,{code_id:i,code_type:"password_reset",login_id:d.id,expires_at:new Date(Date.now()+xz).toISOString()});await Wk(e,n,f.code_id,r)}const MP=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.union([o.z.object({credential_type:o.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),otp:o.z.string(),client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),realm:o.z.enum(["email"]),scope:o.z.string().optional()}),o.z.object({credential_type:o.z.literal("http://auth0.com/oauth/grant-type/password-realm"),client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),password:o.z.string(),realm:o.z.enum(["Username-Password-Authentication"]),scope:o.z.string().optional()})])}}}},responses:{200:{description:"List of tenants"}}}),async e=>{const t=e.req.valid("json"),{client_id:n,username:r}=t;e.set("username",r);const i=await He(e.env,n);e.set("client_id",n),Vt(e,i.tenant.id);const s=r.toLocaleLowerCase(),a=e.get("ip"),c=e.get("useragent"),l=e.get("auth0_client");let u;if("otp"in t)u=await xd(e,{client_id:n,username:s,otp:t.otp});else if("password"in t){const d=await e.env.data.loginSessions.create(i.tenant.id,{expires_at:new Date(Date.now()+li*1e3).toISOString(),authParams:{client_id:n,username:s},csrf_token:Oe(),ip:a,useragent:c,auth0Client:rr(l)});u=await Xa(e,i,{username:s,password:t.password,client_id:n},d,!0)}else throw new I(400,{message:"Code or password required"});return u});function Zk(e,t){if(!e||t.length===0)return!1;const n=pp(e)?.host??null;if(!n)return!1;for(const r of t){let i;if(r.startsWith("http://")||r.startsWith("https://")?i=pp(r)?.host??null:i=pp("https://"+r)?.host??null,n===i)return!0}return!1}function pp(e){try{return new URL(e)}catch{return null}}function qP(e,t){if(!e||t===void 0)return!1;const n=new Date(e.authenticated_at).getTime(),r=t*1e3;return Date.now()-n>r}async function FP({ctx:e,session:t,client:n,authParams:r,connection:i,login_hint:s}){const a=new URL(e.req.url);e.var.custom_domain&&(a.hostname=e.var.custom_domain);const{ip:c,auth0_client:l,useragent:u}=e.var,d=rr(l);qP(t,r.max_age)&&(t=void 0);const f=await e.env.data.loginSessions.create(n.tenant.id,{expires_at:new Date(Date.now()+li*1e3).toISOString(),authParams:r,csrf_token:Oe(),authorization_url:a.toString(),ip:c,useragent:u,auth0Client:d}),p=n.client_metadata?.universal_login_version==="2"?"/u2":"/u";if(t&&s){const h=await e.env.data.users.get(n.tenant.id,t.user_id);if(h?.email===s)return gt(e,{client:n,loginSession:f,authParams:r,user:h,existingSessionIdToLink:t.id})}if(i==="email"&&s){const h=In();return await e.env.data.codes.create(n.tenant.id,{code_id:h,code_type:"otp",login_id:f.id,expires_at:new Date(Date.now()+li*1e3).toISOString(),redirect_uri:r.redirect_uri}),await zd(e,{code:h,to:s,authParams:r}),e.redirect(`${p}/enter-code?state=${f.id}`)}if(t)return e.redirect(`${p}/check-account?state=${f.id}`);if(p==="/u2"){const h=await e.env.data.promptSettings.get(n.tenant.id),_=Rs.parse(h||{}),g=n.connections.some(y=>y.strategy==="Username-Password-Authentication");if(_.identifier_first===!1&&g)return e.redirect(`${p}/login?state=${f.id}`)}return e.redirect(`${p}/login/identifier?state=${f.id}`)}function HP(e){if(e==="Username-Password-Authentication")return Pe;if(e==="email")return"email";throw new W(403,{message:"Invalid realm"})}async function VP(e,t,n,r,i){const{env:s}=e;e.set("connection",i);const a=await s.data.codes.get(t,n,"ticket");if(!a||a.used_at)throw new W(403,{message:"Ticket not found"});const c=await s.data.loginSessions.get(t,a.login_id);if(!c||!c.authParams.username)throw new W(403,{message:"Session not found"});const l=await He(s,c.authParams.client_id,t);e.set("client_id",c.authParams.client_id),await s.data.codes.used(t,n);const u=HP(i),f=l.connections.find(_=>_.name===i)?.strategy||(u===Pe?"Username-Password-Authentication":"email"),p=f==="Username-Password-Authentication"?"database":"passwordless";let h=await Au(e,{username:c.authParams.username,provider:u,client:l,connection:i,isSocial:!1,ip:e.var.ip});return e.set("username",h.email||h.phone_number),e.set("user_id",h.user_id),gt(e,{authParams:{scope:c.authParams?.scope,...r},loginSession:c,user:h,client:l,authStrategy:{strategy:f,strategy_type:p}})}async function KP({ctx:e,client:t,session:n,redirect_uri:r,state:i,nonce:s,code_challenge_method:a,code_challenge:c,audience:l,scope:u,response_type:d,response_mode:f,organization:p,max_age:h}){const{env:_}=e,g=new URL(r),y=`${g.protocol}//${g.host}`,m=f===pn.WEB_MESSAGE;async function v(le="Login required"){const be=new Headers;if(n&&(fe(e,t.tenant.id,{type:ue.FAILED_SILENT_AUTH,description:le}),qw(t.tenant.id,e.req.header("host")).forEach(ut=>{be.append("set-cookie",ut)})),m)return _f(e,y,JSON.stringify({error:"login_required",error_description:le,state:i}),be);const Ee=new URL(r);if(d===ot.TOKEN||d===ot.TOKEN_ID_TOKEN){const ce=new URLSearchParams;ce.set("error","login_required"),ce.set("error_description",le),i&&ce.set("state",i),Ee.hash=ce.toString()}else Ee.searchParams.set("error","login_required"),Ee.searchParams.set("error_description",le),i&&Ee.searchParams.set("state",i);const Te={Location:Ee.toString()},$t=be.get("set-cookie");return $t&&(Te["set-cookie"]=$t),new Response(null,{status:302,headers:Te})}const k=!n||n?.expires_at&&new Date(n.expires_at)<new Date||n?.idle_expires_at&&new Date(n.idle_expires_at)<new Date,x=n&&h!==void 0&&Date.now()-new Date(n.authenticated_at).getTime()>h*1e3;if(k||x)return v();e.set("user_id",n.user_id);const b=await _.data.users.get(t.tenant.id,n.user_id);if(!b)return console.error("User not found",n.user_id),v("User not found");e.set("username",b.email),e.set("connection",b.connection);let S;if(p&&(S=await _.data.organizations.get(t.tenant.id,p),!S))return v("Organization not found");const A=l||t.tenant.audience;let C=u||"",P=[];if(A)try{const le=await Ys(e,{tenantId:t.tenant.id,clientId:t.client_id,audience:A,requestedScopes:u?.split(" ")||[],organizationId:S?.id,userId:b.user_id});C=le.scopes.join(" "),P=le.permissions}catch(le){if(le?.statusCode===403||le?.status===403){const be=le?.body?.error_description||le?.message||"Access denied";return v(be)}throw le}else if(S&&!(await _.data.userOrganizations.list(t.tenant.id,{q:`user_id:${b.user_id}`,per_page:1e3})).userOrganizations.some(Ee=>Ee.organization_id===S.id))return v("User is not a member of the specified organization");const R=await _.data.loginSessions.create(t.tenant.id,{csrf_token:Oe(),authParams:{client_id:t.client_id,audience:l,scope:u,state:i,nonce:s,response_type:d,redirect_uri:r,organization:p,max_age:h},expires_at:new Date(Date.now()+300*1e3).toISOString(),session_id:n.id,ip:e.var.ip,useragent:e.var.useragent}),E=h!==void 0?Math.floor(new Date(n.authenticated_at).getTime()/1e3):void 0,L={client:t,authParams:{client_id:t.client_id,audience:l,code_challenge_method:a,code_challenge:c,scope:C,state:i,nonce:s,response_type:d,redirect_uri:r,max_age:h},user:b,session_id:n.id,auth_time:E,permissions:P,organization:S},M=d===ot.CODE?await y2(e,{user:b,client:t,authParams:L.authParams,login_id:R.id}):await gu(e,L);await _.data.sessions.update(t.tenant.id,n.id,{used_at:new Date().toISOString(),last_interaction_at:new Date().toISOString(),login_session_id:R.id,device:{...n.device,last_ip:e.var.ip||"",last_user_agent:e.var.useragent||""},idle_expires_at:n.idle_expires_at?new Date(Date.now()+pu*1e3).toISOString():void 0}),fe(e,t.tenant.id,{type:ue.SUCCESS_SILENT_AUTH,description:"Successful silent authentication"});const H=new Headers;if(sl(t.tenant.id,n.id,e.req.header("host")).forEach(le=>{H.append("set-cookie",le)}),m)return _f(e,y,JSON.stringify({...M,state:i}),H);const Q=new URL(r);if(d===ot.TOKEN||d===ot.TOKEN_ID_TOKEN){const le=new URLSearchParams;Object.entries(M).forEach(([be,Ee])=>{Ee!==void 0&&le.set(be,String(Ee))}),i&&le.set("state",i),Q.hash=le.toString()}else Object.entries(M).forEach(([le,be])=>{be!==void 0&&Q.searchParams.set(le,String(be))}),i&&Q.searchParams.set("state",i);const se={Location:Q.toString()},we=H.get("set-cookie");return we&&(se["set-cookie"]=we),new Response(null,{status:302,headers:se})}const GP=["email","sms","Username-Password-Authentication"],xb=o.z.object({client_id:o.z.string().optional(),vendor_id:o.z.string().optional(),redirect_uri:o.z.string().optional(),scope:o.z.string().optional(),state:o.z.string().optional(),prompt:o.z.string().optional(),response_mode:o.z.nativeEnum(pn).optional(),response_type:o.z.nativeEnum(ot).optional(),audience:o.z.string().optional(),connection:o.z.string().optional(),nonce:o.z.string().optional(),max_age:o.z.string().optional(),acr_values:o.z.string().optional(),login_ticket:o.z.string().optional(),code_challenge_method:o.z.nativeEnum(uu).optional(),code_challenge:o.z.string().optional(),realm:o.z.string().optional(),auth0Client:o.z.string().optional(),organization:o.z.string().optional(),login_hint:o.z.string().optional(),screen_hint:o.z.string().optional(),ui_locales:o.z.string().optional()});function WP(e){try{const t=e.split(".");if(t.length<2||!t[1])return null;const n=new TextDecoder().decode(wr.decode(t[1],{strict:!1})),r=JSON.parse(n);return typeof r!="object"||r===null?null:r}catch{return null}}const JP=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:xb.extend({client_id:o.z.string(),screen_hint:o.z.string().openapi({example:"signup",description:'Optional hint for the screen to show, like "signup" or "login".'}).optional(),request:o.z.string().openapi({description:"JWT containing authorization request parameters (OpenID Connect Core Section 6.1)"}).optional()}).passthrough()},responses:{200:{description:"Successful authorization response. This can be an HTML page (e.g., for silent authentication iframe or universal login page) or a JSON object containing tokens (e.g., for response_mode=web_message).",content:{"text/html":{schema:o.z.string().openapi({example:"<html>...</html>"})},"application/json":{schema:vh}}},302:{description:"Redirect to the client's redirect URI, an authentication page, or an external identity provider.",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request. Invalid parameters or other client-side errors.",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}},403:{description:"Forbidden. The request is not allowed (e.g., invalid origin).",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async e=>{const{env:t}=e,n=e.req.valid("query");let r={};if(n.request){const D=WP(n.request);if(D){const Q=xb.safeParse(D);Q.success&&(r=Q.data)}}const{client_id:i,vendor_id:s,redirect_uri:a,scope:c,state:l,audience:u,nonce:d,connection:f,response_type:p,response_mode:h,code_challenge:_,code_challenge_method:g,prompt:y,max_age:m,acr_values:v,login_ticket:k,realm:x,login_hint:b,ui_locales:S,organization:A}={...r,...n};e.set("log","authorize");const C=await He(t,i);e.set("client_id",C.client_id),Vt(e,C.tenant.id);let P=a;typeof a=="string"&&(P=a.split("#")[0]);const R=e.req.header("origin");if(R&&!Zk(R,C.web_origins||[]))throw new I(403,{message:`Origin ${R} not allowed`});if(!p){if(P){const D=new URL(P);return D.searchParams.set("error","invalid_request"),D.searchParams.set("error_description","Missing required parameter: response_type"),l&&D.searchParams.set("state",l),e.redirect(D.toString())}throw new I(400,{message:"Missing required parameter: response_type"})}const E={redirect_uri:P,scope:c,state:l,client_id:i,vendor_id:s,audience:u,nonce:d,prompt:y,response_type:p,response_mode:h,code_challenge:_,code_challenge_method:g,username:b,ui_locales:S,organization:A,max_age:m?parseInt(m,10):void 0,acr_values:v};if(E.redirect_uri){const D=C.callbacks||[];if(e.var.host&&(D.push(`${wu(e.env)}/*`),D.push(`${_t(e.env)}/*`)),!N_(E.redirect_uri,D,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new I(400,{message:`Invalid redirect URI - ${E.redirect_uri}`})}let L;const M=Ez(C.tenant.id,e.req.header("cookie"));for(const D of M){const Q=await t.data.sessions.get(C.tenant.id,D);if(Q&&!Q.revoked_at){L=Q;break}}if(y=="none"){if(!P||!l||!p)throw new I(400,{message:"Missing required parameters for silent auth: redirect_uri, state, and response_type"});return KP({ctx:e,session:L||void 0,redirect_uri:P,state:l,response_type:p,response_mode:h,client:C,nonce:d,code_challenge_method:g,code_challenge:_,audience:u,scope:c,organization:A,max_age:m?parseInt(m,10):void 0})}if(C.connections.length===1&&C.connections[0]&&!GP.includes(C.connections[0].strategy||""))return Jy(e,C,C.connections[0].name,E);if(f&&f!=="email")return Jy(e,C,f,E);if(k){const D=await VP(e,C.tenant.id,k,E,x);return D instanceof Response?D:e.json(D)}const H=await FP({ctx:e,client:C,authParams:E,session:L||void 0,connection:f,login_hint:b});return H instanceof Response?H:e.json(H)}),ZP=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:o.z.object({client_id:o.z.string(),redirect_url:o.z.string().optional(),login_hint:o.z.string().toLowerCase().optional(),screen_hint:o.z.enum(["account","change-email","change-phone","change-password"]).optional().default("account")})},responses:{302:{description:"Redirect to the account page with login session state or login page",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request. Invalid parameters or other client-side errors.",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async e=>{const{env:t}=e,{client_id:n,redirect_url:r,login_hint:i,screen_hint:s}=e.req.valid("query");e.set("log","account");const a=await He(t,n);e.set("client_id",a.client_id),Vt(e,a.tenant.id);const c={redirect_uri:r||e.req.url,client_id:n,username:i},l=e.req.header("origin");if(l&&!Zk(l,a.web_origins||[]))throw new I(403,{message:`Origin ${l} not allowed`});if(c.redirect_uri){const v=a.callbacks||[];if(e.var.host&&(v.push(`${wu(e.env)}/*`),v.push(`${_t(e.env)}/*`)),!N_(c.redirect_uri,v,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new I(400,{message:`Invalid redirect URI - ${c.redirect_uri}`})}const u=ui(a.tenant.id,e.req.header("cookie")),d=u?await t.data.sessions.get(a.tenant.id,u):void 0,f=d&&!d.revoked_at?d:void 0,p=new URL(e.req.url);e.var.custom_domain&&(p.hostname=e.var.custom_domain);const{ip:h,auth0_client:_,useragent:g}=e.var,y=rr(_),m=await t.data.loginSessions.create(a.tenant.id,{expires_at:new Date(Date.now()+li*1e3).toISOString(),authParams:c,csrf_token:Oe(),authorization_url:p.toString(),ip:h,useragent:g,auth0Client:y});if(f){if(i&&(await t.data.users.get(a.tenant.id,f.user_id))?.email!==i)return e.redirect(`${_t(e.env)}login/identifier?state=${encodeURIComponent(m.id)}`);if(await t.data.loginSessions.update(a.tenant.id,m.id,{session_id:f.id}),s==="change-email"){const k=new URL("/u/account/change-email",e.req.url);return k.searchParams.set("state",m.id),e.redirect(k.toString())}const v=new URL("/u/account",e.req.url);return v.searchParams.set("state",m.id),e.redirect(v.toString())}return e.redirect(`${_t(e.env)}login/identifier?state=${encodeURIComponent(m.id)}`)});function XP(e){const t=new o.OpenAPIHono;t.use(async(r,i)=>{const s=Do(r,e.dataAdapter),a=e.dataAdapter.cache||ts({defaultTtlSeconds:0,maxEntries:100,cleanupIntervalMs:0}),c=e.dataAdapter.cache?300:0,l=Ja(s,{defaultTtl:c,cacheEntities:["tenants","connections","clientConnections","customDomains","clients","branding","themes","promptSettings","forms","resourceServers","roles","organizations","userRoles","userPermissions"],cache:a});return r.env.data=Wa(r,l),i()}),t.use("/oauth/token",Rk({origin:r=>r||"",allowHeaders:["Tenant-Id","Content-Type","Auth0-Client","Upgrade-Insecure-Requests"],allowMethods:["POST"],maxAge:600})),t.use(es).use(Qo).use(wd(t));const n=t.route("/v2/logout",oN).route("/userinfo",cN).route("/.well-known",lN).route("/oauth/token",PP).route("/dbconnections",RP).route("/passwordless",LP).route("/co/authenticate",MP).route("/authorize",JP).route("/account",ZP).route("/callback",rN);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Oauth API"},security:[{oauth2:["openid","email","profile"]}]}),I_(n),n}var B_=Symbol("RENDERER"),J0=Symbol("ERROR_HANDLER"),qe=Symbol("STASH"),Xk=Symbol("INTERNAL"),YP=Symbol("MEMO"),tu=Symbol("PERMALINK"),Sb=e=>(e[Xk]=!0,e),Yk=e=>({value:t,children:n})=>{if(!n)return;const r={children:[{tag:Sb(()=>{e.push(t)}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:Sb(()=>{e.pop()}),props:{}});const i={tag:"",props:r,type:""};return i[J0]=s=>{throw e.pop(),s},i},Qk=e=>{const t=[e],n=Yk(t);return n.values=t,n.Provider=n,No.push(n),n},No=[],e4=e=>{const t=[e],n=(r=>{t.push(r.value);let i;try{i=r.children?(Array.isArray(r.children)?new i4("",{},r.children):r.children).toString():""}catch(s){throw t.pop(),s}return i instanceof Promise?i.finally(()=>t.pop()).then(s=>Cr(s,s.callbacks)):(t.pop(),Cr(i))});return n.values=t,n.Provider=n,n[B_]=Yk(t),No.push(n),n},rs=e=>e.values.at(-1),Oc={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},Z0={},Rc="data-precedence",Ya=e=>Array.isArray(e)?e:[e],zb=new WeakMap,Ab=(e,t,n,r)=>({buffer:i,context:s})=>{if(!i)return;const a=zb.get(s)||{};zb.set(s,a);const c=a[e]||=[];let l=!1;const u=Oc[e];if(u.length>0){e:for(const[,d]of c)for(const f of u)if((d?.[f]??null)===n?.[f]){l=!0;break e}}if(l?i[0]=i[0].replaceAll(t,""):u.length>0?c.push([t,n,r]):c.unshift([t,n,r]),i[0].indexOf("</head>")!==-1){let d;if(r===void 0)d=c.map(([f])=>f);else{const f=[];d=c.map(([p,,h])=>{let _=f.indexOf(h);return _===-1&&(f.push(h),_=f.length-1),[p,_]}).sort((p,h)=>p[1]-h[1]).map(([p])=>p)}d.forEach(f=>{i[0]=i[0].replaceAll(f,"")}),i[0]=i[0].replace(/(?=<\/head>)/,d.join(""))}},Qa=(e,t,n)=>Cr(new _n(e,n,Ya(t??[])).toString()),ec=(e,t,n,r)=>{if("itemProp"in n)return Qa(e,t,n);let{precedence:i,blocking:s,...a}=n;i=r?i??"":void 0,r&&(a[Rc]=i);const c=new _n(e,a,Ya(t||[])).toString();return c instanceof Promise?c.then(l=>Cr(c,[...l.callbacks||[],Ab(e,l,a,i)])):Cr(c,[Ab(e,c,a,i)])},QP=({children:e,...t})=>{const n=M_();if(n){const r=rs(n);if(r==="svg"||r==="head")return new _n("title",t,Ya(e??[]))}return ec("title",e,t,!1)},eO=({children:e,...t})=>{const n=M_();return["src","async"].some(r=>!t[r])||n&&rs(n)==="head"?Qa("script",e,t):ec("script",e,t,!1)},tO=({children:e,...t})=>["href","precedence"].every(n=>n in t)?(t["data-href"]=t.href,delete t.href,ec("style",e,t,!0)):Qa("style",e,t),nO=({children:e,...t})=>["onLoad","onError"].some(n=>n in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?Qa("link",e,t):ec("link",e,t,"precedence"in t),rO=({children:e,...t})=>{const n=M_();return n&&rs(n)==="head"?Qa("meta",e,t):ec("meta",e,t,!1)},t4=(e,{children:t,...n})=>new _n(e,n,Ya(t??[])),iO=e=>(typeof e.action=="function"&&(e.action=tu in e.action?e.action[tu]:void 0),t4("form",e)),n4=(e,t)=>(typeof t.formAction=="function"&&(t.formAction=tu in t.formAction?t.formAction[tu]:void 0),t4(e,t)),oO=e=>n4("input",e),sO=e=>n4("button",e);const fp=Object.freeze(Object.defineProperty({__proto__:null,button:sO,form:iO,input:oO,link:nO,meta:rO,script:eO,style:tO,title:QP},Symbol.toStringTag,{value:"Module"}));var aO=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),nu=e=>aO.get(e)||e,r4=(e,t)=>{for(const[n,r]of Object.entries(e)){const i=n[0]==="-"||!/[A-Z]/.test(n)?n:n.replace(/[A-Z]/g,s=>`-${s.toLowerCase()}`);t(i,r==null?null:typeof r=="number"?i.match(/^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/)?`${r}`:`${r}px`:r)}},wa=void 0,M_=()=>wa,cO=e=>/[A-Z]/.test(e)&&e.match(/^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/)?e.replace(/([A-Z])/g,"-$1").toLowerCase():e,lO=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],uO=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","download","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"],q_=(e,t)=>{for(let n=0,r=e.length;n<r;n++){const i=e[n];if(typeof i=="string")po(i,t);else{if(typeof i=="boolean"||i===null||i===void 0)continue;i instanceof _n?i.toStringToBuffer(t):typeof i=="number"||i.isEscaped?t[0]+=i:i instanceof Promise?t.unshift("",i):q_(i,t)}}},_n=class{tag;props;key;children;isEscaped=!0;localContexts;constructor(e,t,n){this.tag=e,this.props=t,this.children=n}get type(){return this.tag}get ref(){return this.props.ref||null}toString(){const e=[""];this.localContexts?.forEach(([t,n])=>{t.values.push(n)});try{this.toStringToBuffer(e)}finally{this.localContexts?.forEach(([t])=>{t.values.pop()})}return e.length===1?"callbacks"in e?hj(Cr(e[0],e.callbacks)).toString():e[0]:fj(e,e.callbacks)}toStringToBuffer(e){const t=this.tag,n=this.props;let{children:r}=this;e[0]+=`<${t}`;const i=wa&&rs(wa)==="svg"?s=>cO(nu(s)):s=>nu(s);for(let[s,a]of Object.entries(n))if(s=i(s),s!=="children"){if(s==="style"&&typeof a=="object"){let c="";r4(a,(l,u)=>{u!=null&&(c+=`${c?";":""}${l}:${u}`)}),e[0]+=' style="',po(c,e),e[0]+='"'}else if(typeof a=="string")e[0]+=` ${s}="`,po(a,e),e[0]+='"';else if(a!=null)if(typeof a=="number"||a.isEscaped)e[0]+=` ${s}="${a}"`;else if(typeof a=="boolean"&&uO.includes(s))a&&(e[0]+=` ${s}=""`);else if(s==="dangerouslySetInnerHTML"){if(r.length>0)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");r=[Cr(a.__html)]}else if(a instanceof Promise)e[0]+=` ${s}="`,e.unshift('"',a);else if(typeof a=="function"){if(!s.startsWith("on")&&s!=="ref")throw new Error(`Invalid prop '${s}' of type 'function' supplied to '${t}'.`)}else e[0]+=` ${s}="`,po(a.toString(),e),e[0]+='"'}if(lO.includes(t)&&r.length===0){e[0]+="/>";return}e[0]+=">",q_(r,e),e[0]+=`</${t}>`}},hp=class extends _n{toStringToBuffer(e){const{children:t}=this,n={...this.props};t.length&&(n.children=t.length===1?t[0]:t);const r=this.tag.call(null,n);if(!(typeof r=="boolean"||r==null))if(r instanceof Promise)if(No.length===0)e.unshift("",r);else{const i=No.map(s=>[s,s.values.at(-1)]);e.unshift("",r.then(s=>(s instanceof _n&&(s.localContexts=i),s)))}else r instanceof _n?r.toStringToBuffer(e):typeof r=="number"||r.isEscaped?(e[0]+=r,r.callbacks&&(e.callbacks||=[],e.callbacks.push(...r.callbacks))):po(r,e)}},i4=class extends _n{toStringToBuffer(e){q_(this.children,e)}},dO=(e,t,...n)=>{t??={},n.length&&(t.children=n.length===1?n[0]:n);const r=t.key;delete t.key;const i=Lc(e,t,n);return i.key=r,i},Eb=!1,Lc=(e,t,n)=>{if(!Eb){for(const r in Z0)fp[r][B_]=Z0[r];Eb=!0}return typeof e=="function"?new hp(e,t,n):fp[e]?new hp(fp[e],t,n):e==="svg"||e==="head"?(wa||=e4(""),new _n(e,t,[new hp(wa,{value:e},n)])):new _n(e,t,n)},To=({children:e})=>new i4("",{children:e},Array.isArray(e)?e:e?[e]:[]),pO=(e,t,...n)=>{let r;if(n.length>0)r=n;else{const i=e.props.children;r=Array.isArray(i)?i:[i]}return dO(e.tag,{...e.props,...t},...r)};function w(e,t,n){let r;if(!t||!("children"in t))r=Lc(e,t,[]);else{const i=t.children;r=Array.isArray(i)?Lc(e,t,i):Lc(e,t,[i])}return r.key=n,r}async function Ae(e,t,n=!1){const{env:r}=e,i=await r.data.loginSessions.get(e.var.tenant_id||"",t);if(!i)throw new W(400,{message:"Login session not found"});e.set("loginSession",i);const s=await He(r,i.authParams.client_id);e.set("client_id",s.client_id),Vt(e,s.tenant.id);const a=s.tenant;if(i.session_id&&!n){if(!i.authParams.redirect_uri)throw new W(400,{message:"Login session closed and no redirect URI available"});const p=new URL(i.authParams.redirect_uri);throw p.searchParams.set("error","access_denied"),p.searchParams.set("error_description","Login session closed"),i.authParams.state&&p.searchParams.set("state",i.authParams.state),new qt(p.toString(),302)}const[c,l]=await Promise.all([r.data.themes.get(a.id,"default"),r.data.branding.get(a.id)]),u=c??uf,d=l?{...l,favicon_url:e.var.custom_domain?l.favicon_url:void 0}:null,f=i.authParams?.ui_locales?.split(" ")?.map(p=>p.split("-")[0])?.find(p=>{if(Array.isArray(T.options.supportedLngs))return T.options.supportedLngs.includes(p)});return await T.changeLanguage(f||"en"),{theme:u,branding:d,client:s,tenant:a,loginSession:i}}async function Ai(e,t,n){const{theme:r,branding:i,client:s,tenant:a,loginSession:c}=await Ae(e,t,!0),l=ui(s.tenant.id,e.req.header("cookie")),u=l?await e.env.data.sessions.get(s.tenant.id,l):null;if(n?.continuationScope&&RA(c,n.continuationScope)){if(!c.user_id)throw new qt(`/u/login/identifier?state=${encodeURIComponent(t)}`);const h=await e.env.data.users.get(s.tenant.id,c.user_id);if(!h)throw new qt(`/u/login/identifier?state=${encodeURIComponent(t)}`);const _=c.session_id?await e.env.data.sessions.get(s.tenant.id,c.session_id):null;return{theme:r,branding:i,client:s,user:h,tenant:a,loginSession:c,session:_,isContinuation:!0}}if(!u||u.revoked_at||!c.session_id)throw new qt(`/u/login/identifier?state=${encodeURIComponent(t)}`);const f=await e.env.data.sessions.get(s.tenant.id,c.session_id),p=await e.env.data.users.get(s.tenant.id,u.user_id);if(!p||f?.user_id!==u.user_id)throw new qt(`/u/login/identifier?state=${encodeURIComponent(t)}`);return{theme:r,branding:i,client:s,user:p,tenant:a,loginSession:c,session:f,isContinuation:!1}}const _p={"Username-Password-Authentication":"password",email:"email",sms:"sms"};async function o4(e,t,n,r,i){if(r==="username"||i==="password")return"password";if(i==="code")return r==="sms"?"sms":"email";const a=(r==="email"?await Uo({userAdapter:e.env.data.users,tenant_id:t.tenant.id,email:n}):await Xn({userAdapter:e.env.data.users,tenant_id:t.tenant.id,username:n,provider:r==="sms"?"sms":Pe}))?.app_metadata?.strategy;if(a&&_p[a])return _p[a];const c=t.connections.map(u=>_p[u.strategy]).filter(u=>u!==void 0);return c.length===1&&c[0]?c[0]:(await e.env.data.promptSettings.get(t.tenant.id)).password_first&&c.includes("password")?"password":r==="sms"?"sms":"email"}const F_=({theme:e,branding:t})=>{const n=e?.widget?.logo_url||t?.logo_url;return n?w("div",{className:"inline-flex h-9 items-center",children:w("img",{src:n,className:"h-full w-auto",alt:"Logo"})}):w(To,{})},s4=e=>w("div",{className:"mt-8",children:e.client?.client_metadata?.termsAndConditionsUrl&&w("div",{className:"text-xs text-gray-300",children:[T.t("agree_to")," ",w("a",{href:e.client.client_metadata.termsAndConditionsUrl,className:"text-primary hover:underline",target:"_blank",rel:"noreferrer",children:T.t("terms")})]})});var mp={exports:{}};var Cb;function fO(){return Cb||(Cb=1,(function(e){(function(){var t={}.hasOwnProperty;function n(){for(var s="",a=0;a<arguments.length;a++){var c=arguments[a];c&&(s=i(s,r(c)))}return s}function r(s){if(typeof s=="string"||typeof s=="number")return s;if(typeof s!="object")return"";if(Array.isArray(s))return n.apply(null,s);if(s.toString!==Object.prototype.toString&&!s.toString.toString().includes("[native code]"))return s.toString();var a="";for(var c in s)t.call(s,c)&&s[c]&&(a=i(a,c));return a}function i(s,a){return a?s?s+" "+a:s+a:s}e.exports?(n.default=n,e.exports=n):window.classNames=n})()})(mp)),mp.exports}var hO=fO();const Be=Bw(hO),_O=e=>e==="small"?"text-base":e==="medium"?"text-2xl":e==="large"?"text-3xl":"",Ze=({name:e,size:t,className:n=""})=>{const r=_O(t);return w("span",{className:Be(`uicon-${e}`,n,r)})},mO=(e,t)=>{const n=e.replace("#",""),r=parseInt(n,16),i=r>>16&255,s=r>>8&255,a=r&255,c=Math.min(255,Math.round(i+(255-i)*t)),l=Math.min(255,Math.round(s+(255-s)*t)),u=Math.min(255,Math.round(a+(255-a)*t));return`#${(c<<16|l<<8|u).toString(16).padStart(6,"0")}`},Po="mm9ctyyf",gO=(e,t)=>{const n=e?.colors?.primary_button||t?.colors?.primary||"#000000",r=e?.colors?.base_hover_color||mO(n,.2),i=e?.colors?.primary_button_label||"#ffffff";return`
|
|
86
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function yP(e,t){if(e){if(typeof e=="string")return gb(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?gb(e,t):void 0}}function gb(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function bP(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,s,a,c=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,t!==0)for(;!(l=(r=s.call(n)).done)&&(c.push(r.value),c.length!==t);l=!0);}catch(d){u=!0,i=d}finally{try{if(!l&&n.return!=null&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw i}}return c}}function vP(e){if(Array.isArray(e))return e}function wP(e){var t=Array.prototype.slice.call(e),n=mP(t,4),r=n[0],i=n[1],s=n[2],a=n[3],c,l,u;if(typeof r=="string")c=r;else throw new TypeError("A text for parsing must be a string.");if(!i||typeof i=="string")a?(l=s,u=a):(l=void 0,u=s),i&&(l=pP({defaultCountry:i},l));else if(fo(i))s?(l=i,u=s):u=i;else throw new Error("Invalid second argument: ".concat(i));return{text:c,options:l,metadata:u}}function va(e){"@babel/helpers - typeof";return va=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},va(e)}function yb(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function bb(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?yb(Object(n),!0).forEach(function(r){kP(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):yb(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function kP(e,t,n){return(t=$P(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function $P(e){var t=xP(e,"string");return va(t)=="symbol"?t:t+""}function xP(e,t){if(va(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(va(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function SP(e,t,n){t&&t.defaultCountry&&!EN(t.defaultCountry,n)&&(t=bb(bb({},t),{},{defaultCountry:void 0}));try{return dP(e,t,n)}catch(r){if(!(r instanceof Gn))throw r}}function zP(){var e=wP(arguments),t=e.text,n=e.options,r=e.metadata;return SP(t,n,r)}function AP(){return mN(zP,arguments)}function ns(e,t="US"){const n=e.trim();if(n.includes("@")){const r=n.toLowerCase(),i=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r);return{connectionType:"email",normalized:i?r:null,isValid:i,provider:"email"}}else if(/^\+?\d[\d\s\-().]*$/.test(n)){const r=AP(n,{defaultCountry:t});return r&&r.isValid()?{connectionType:"sms",normalized:r.number,isValid:!0,provider:"sms"}:{connectionType:"sms",normalized:null,isValid:!1,provider:"sms"}}else return{connectionType:"username",normalized:n,isValid:!0,provider:Pe}}function U_(e){let t=e.trim();t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1));const n=t.indexOf("%");return n!==-1&&(t=t.slice(0,n)),t}function EP(e){const n=U_(e).split(".");return n.length!==4?!1:n.every(r=>/^\d+$/.test(r)&&Number(r)>=0&&Number(r)<=255)}function CP(e){const t=U_(e);if(t.length<2||t.indexOf(":")===-1||!/^[0-9a-fA-F:.]+$/.test(t))return!1;const n=t.split(":");return t.includes("::")?n.length<=8:n.length===8}function IP(e){let t=e.trim();const n=/^\[([^\]]+)\](?::\d+)?$/,r=t.match(n);if(r&&r[1])return r[1];const i=t.lastIndexOf(":");if(i!==-1){const s=t.slice(0,i),a=t.slice(i+1);/^[0-9.]+$/.test(s)&&/^\d+$/.test(a)&&(t=s)}return t}function vb(e){if(!e)return null;const t=U_(IP(e));return EP(t)?{family:4,normalized:t}:CP(t)?{family:6,normalized:t.toLowerCase()}:null}function wb(e){if(e.includes("::")){let[t,n]=e.split("::"),r=t?t.split(":").filter(Boolean):[],i=n?n.split(":").filter(Boolean):[],s=8-(r.length+i.length);return[...r.map(a=>a.toLowerCase()||"0"),...Array(s).fill("0"),...i.map(a=>a.toLowerCase()||"0")]}else return e.split(":").map(t=>t.toLowerCase()||"0")}function jP(e,t,n=!0){const r=vb(e),i=vb(t);if(!r||!i||r.family!==i.family)return!1;if(r.family===4)return r.normalized===i.normalized;const s=wb(r.normalized),a=wb(i.normalized);return n?s.length===8&&a.length===8&&s.join(":")===a.join(":"):s.slice(0,4).join(":")===a.slice(0,4).join(":")}class qt extends Error{location;status;constructor(t,n=302){super(`Redirect to ${t}`),this.name=qt.name,this.location=t,this.status=n}}const NP=o.z.object({client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),otp:o.z.string(),authParams:Js.optional(),enforceIpCheck:o.z.boolean().optional().default(!1)});async function Kk(e,{client_id:t,username:n,otp:r,authParams:i,enforceIpCheck:s=!1}){const a=e.get("ip"),c=e.get("countryCode"),{connectionType:l,normalized:u}=ns(n,c);if(!u)throw new W(400,{message:"Invalid username format"});const d=await He(e.env,t,e.var.tenant_id),{env:f}=e,p=await f.data.codes.get(d.tenant.id,r,"otp");if(!p)throw new W(400,{message:he("code_invalid")});if(p.expires_at<new Date().toISOString())throw new W(400,{message:he("code_expired")});if(p.used_at)throw new W(400,{message:he("code_used")});const h=await f.data.loginSessions.get(d.tenant.id,p.login_id);if(!h||h.authParams.username!==n)throw new W(400,{message:"Code not found or expired"});if(s&&h.ip&&a&&!jP(h.ip,a))throw new qt(`${_t(e.env)}invalid-session?state=${h.id}`);const _=await Au(e,{client:d,username:u,provider:l,connection:l,isSocial:!1,ip:e.var.ip});return await f.data.codes.used(d.tenant.id,r),{user:_,client:d,loginSession:h,session_id:h.session_id,authParams:{...h.authParams,...i||{}}}}async function xd(e,t){const n=await Kk(e,t);return gt(e,{authParams:n.authParams,client:n.client,user:n.user,loginSession:n.loginSession,authStrategy:{strategy:"email",strategy_type:"passwordless"}})}const kb=o.z.object({client_id:o.z.string().optional(),client_secret:o.z.string().optional()}),$b=o.z.union([Lk.extend(kb.shape),o.z.object({grant_type:o.z.literal("authorization_code"),client_id:o.z.string(),code:o.z.string(),redirect_uri:o.z.string(),code_verifier:o.z.string().min(43).max(128),organization:o.z.string().optional()}),o.z.object({grant_type:o.z.literal("authorization_code"),code:o.z.string(),redirect_uri:o.z.string().optional(),organization:o.z.string().optional(),...kb.shape}),o.z.object({grant_type:o.z.literal("refresh_token"),client_id:o.z.string().optional(),refresh_token:o.z.string(),redirect_uri:o.z.string().optional(),client_secret:o.z.string().optional()}),o.z.object({grant_type:o.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),client_id:o.z.string(),username:o.z.string(),otp:o.z.string(),realm:o.z.enum(["email","sms"])})]);function TP(e){if(!e)return{};const[t,n]=e.split(" ");if(t?.toLowerCase()==="basic"&&n){const[r,i]=atob(n).split(":");return{client_id:r,client_secret:i}}return{}}const PP=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:$b},"application/json":{schema:$b}}}},responses:{200:{content:{"application/json":{schema:vh}},description:"Tokens"},302:{description:"Redirect for further user interaction (e.g., MFA, consent).",headers:o.z.object({Location:o.z.string().url()}).openapi({})},400:{description:"Bad Request - The request was malformed or invalid.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},401:{description:"Unauthorized - Client authentication failed.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},403:{description:"Forbidden - User is not a member of the required organization.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}}}}),async e=>{const n=(e.req.header("Content-Type")||"").includes("application/json")?e.req.valid("json"):e.req.valid("form"),r=TP(e.req.header("Authorization")),i={...n,...r};if(!i.client_id)throw new I(400,{message:"client_id is required"});e.set("client_id",i.client_id);let s;switch(n.grant_type){case an.AuthorizationCode:s=await pN(e,dN.parse(i));break;case an.ClientCredential:s=await uN(e,Lk.parse(i));break;case an.RefreshToken:s=await hN(e,fN.parse(i));break;case an.OTP:s=await Kk(e,NP.parse(i));break;default:return e.json({error:"unsupported_grant_type",error_description:"Grant type not implemented"},400)}Vt(e,s.client.tenant.id);const a=new Headers;s.session_id&&sl(s.client.tenant.id,s.session_id,e.var.host||"").forEach(d=>{a.append("Set-Cookie",d)});let c=[];if(s.authParams.audience)try{let u;if(n.grant_type===an.ClientCredential)u=await Ys(e,{grantType:an.ClientCredential,tenantId:s.client.tenant.id,clientId:s.client.client_id,audience:s.authParams.audience,requestedScopes:s.authParams.scope?.split(" ")||[],organizationId:s.organization?.id});else{if(!s.user?.user_id)throw new W(400,{error:"invalid_request",error_description:"User ID is required for user-based grants"});u=await Ys(e,{grantType:n.grant_type,tenantId:s.client.tenant.id,userId:s.user.user_id,clientId:s.client.client_id,audience:s.authParams.audience,requestedScopes:s.authParams.scope?.split(" ")||[],organizationId:s.organization?.id})}s.authParams.scope=u.scopes.join(" "),c=u.permissions}catch(u){if(u instanceof I)throw u;console.error("Error calculating scopes and permissions:",u)}const l=await gu(e,{...s,grantType:n.grant_type,permissions:c.length>0?c:void 0});return e.json(l,{headers:a})});async function Za(e,t){const n=await e.env.data.emailProviders.get(e.var.tenant_id);if(!n)throw new I(500,{message:"Email provider not found"});const r=e.env.emailProviders?.[n.name];if(!r)throw new I(500,{message:"Email provider not found"});await r({emailProvider:n,...t,from:n.default_from_address||`login@${e.env.ISSUER}`})}async function Gk(e,t){if(!e.var.client_id)throw new I(500,{message:"Client not found"});const n=await He(e.env,e.var.client_id),r=n.connections.find(a=>a.strategy==="sms");if(!r)throw new I(500,{message:"SMS provider not found"});const i=r.options?.provider||"twilio",s=e.env.smsProviders?.[i];if(!s)throw new I(500,{message:"SMS provider not found"});await s({options:r.options,to:t.to,from:t.from,text:t.text,template:"auth-code",data:{code:t.code,tenantName:n.tenant.friendly_name,tenantId:n.tenant.id}})}async function Wk(e,t,n,r,i){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});const a=`${_t(e.env)}reset-password?state=${r}&code=${n}`,c=await e.env.data.branding.get(e.var.tenant_id),l=c?.logo_url||"",u=c?.colors?.primary||"#7d68f4",d={vendorName:s.friendly_name,lng:"en"};await Za(e,{to:t,subject:he("reset_password_title",d),html:`Click here to reset your password: ${_t(e.env)}reset-password?state=${r}&code=${n}`,template:"auth-password-reset",data:{vendorName:s.friendly_name,logo:l,passwordResetUrl:a,supportUrl:s.support_url||"https://support.sesamy.com",buttonColor:u,passwordResetTitle:he("password_reset_title",d),resetPasswordEmailClickToReset:he("reset_password_email_click_to_reset",d),resetPasswordEmailReset:he("reset_password_email_reset",d),supportInfo:he("support_info",d),contactUs:he("contact_us",d),copyright:he("copyright",d),tenantName:s.friendly_name,tenantId:s.id}}),fe(e,s.id,{type:ue.SUCCESS_CHANGE_PASSWORD_REQUEST,description:t})}async function Sd(e,{to:t,code:n,language:r}){const i=await e.env.data.tenants.get(e.var.tenant_id);if(!i)throw new I(500,{message:"Tenant not found"});const{connectionType:s}=ns(t),a=await e.env.data.branding.get(e.var.tenant_id),c=a?.logo_url||"",l=a?.colors?.primary||"#7d68f4",u=new URL(_t(e.env)),d={vendorName:i.friendly_name,vendorId:i.id,loginDomain:u.hostname,code:n,lng:r||"en"};s==="email"?await Za(e,{to:t,subject:he("code_email_subject",d),html:`Click here to validate your email: ${_t(e.env)}validate-email`,template:"auth-code",data:{code:n,vendorName:i.friendly_name,logo:c,supportUrl:i.support_url||"",buttonColor:l,welcomeToYourAccount:he("welcome_to_your_account",d),linkEmailClickToLogin:he("link_email_click_to_login",d),linkEmailLogin:he("link_email_login",d),linkEmailOrEnterCode:he("link_email_or_enter_code",d),codeValid30Mins:he("code_valid_30_minutes",d),supportInfo:he("support_info",d),contactUs:he("contact_us",d),copyright:he("copyright",d)}}):s==="sms"&&await Gk(e,{to:t,text:he("sms_code_text",d),code:n,from:i.friendly_name}),fe(e,i.id,{type:ue.CODE_LINK_SENT,description:t})}async function zd(e,{to:t,code:n,authParams:r,language:i}){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});if(!r.redirect_uri)throw new I(400,{message:"redirect_uri is required"});const{connectionType:a}=ns(t),c=await e.env.data.branding.get(e.var.tenant_id),l=c?.logo_url||"",u=c?.colors?.primary||"",d=new URL(Le(e.env));d.pathname="passwordless/verify_redirect",d.searchParams.set("verification_code",n),d.searchParams.set("connection",a),d.searchParams.set("client_id",r.client_id),d.searchParams.set("redirect_uri",r.redirect_uri),d.searchParams.set("email",t),r.response_type&&d.searchParams.set("response_type",r.response_type),r.scope&&d.searchParams.set("scope",r.scope),r.state&&d.searchParams.set("state",r.state),r.nonce&&d.searchParams.set("nonce",r.nonce),r.code_challenge&&d.searchParams.set("code_challenge",r.code_challenge),r.code_challenge_method&&d.searchParams.set("code_challenge_method",r.code_challenge_method),r.audience&&d.searchParams.set("audience",r.audience);const f={vendorName:s.friendly_name,code:n,lng:i||"en"};if(a==="email")await Za(e,{to:t,subject:he("code_email_subject",f),html:`Click here to validate your email: ${_t(e.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:s.friendly_name,logo:l,supportUrl:s.support_url||"",magicLink:d.toString(),buttonColor:u,welcomeToYourAccount:he("welcome_to_your_account",f),linkEmailClickToLogin:he("link_email_click_to_login",f),linkEmailLogin:he("link_email_login",f),linkEmailOrEnterCode:he("link_email_or_enter_code",f),codeValid30Mins:he("code_valid_30_minutes",f),supportInfo:he("support_info",f),contactUs:he("contact_us",f),copyright:he("copyright",f)}});else if(a==="sms")await Gk(e,{to:t,text:`${he("link_sms_login",f)}: ${d.toString()}`,code:n,from:s.friendly_name});else throw new I(400,{message:"Only email and SMS connections are supported for magic links"});fe(e,s.id,{type:ue.CODE_LINK_SENT,description:t})}async function Ad(e,t,n){const r=await e.env.data.tenants.get(e.var.tenant_id);if(!r)throw new I(500,{message:"Tenant not found"});if(!t.email)throw new I(400,{message:"User has no email"});const i=await e.env.data.branding.get(e.var.tenant_id),s=i?.logo_url||"",a=i?.colors?.primary||"#7d68f4",c={vendorName:r.friendly_name,lng:n||"en"};await Za(e,{to:t.email,subject:he("welcome_to_your_account",c),html:`Click here to validate your email: ${_t(e.env)}validate-email`,template:"auth-verify-email",data:{vendorName:r.friendly_name,logo:s,emailValidationUrl:`${_t(e.env)}validate-email`,supportUrl:r.support_url||"https://support.sesamy.com",buttonColor:a,welcomeToYourAccount:he("welcome_to_your_account",c),verifyEmailVerify:he("verify_email_verify",c),supportInfo:he("support_info",c),contactUs:he("contact_us",c),copyright:he("copyright",c)}})}async function OP(e,t,n,r,i){const s=await e.env.data.tenants.get(e.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});const a=await e.env.data.branding.get(e.var.tenant_id),c=a?.logo_url||"",l=a?.colors?.primary||"#7d68f4",u={vendorName:s.friendly_name,lng:"en"},d=`${_t(e.env)}signup?state=${r}&code=${n}`;await Za(e,{to:t,subject:he("register_password_account",u),html:`Click here to register: ${d}`,template:"auth-pre-signup-verification",data:{vendorName:s.friendly_name,logo:c,signupUrl:d,setPassword:he("set_password",u),registerPasswordAccount:he("register_password_account",u),clickToSignUpDescription:he("click_to_sign_up_description",u),supportUrl:s.support_url||"https://support.sesamy.com",buttonColor:l,welcomeToYourAccount:he("welcome_to_your_account",u),verifyEmailVerify:he("verify_email_verify",u),supportInfo:he("support_info",u),contactUs:he("contact_us",u),copyright:he("copyright",u)}})}const RP=new o.OpenAPIHono().openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/signup",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(e=>e.toLowerCase()),password:o.z.string()})}}}},responses:{200:{content:{"application/json":{schema:o.z.object({_id:o.z.string(),email:o.z.string().optional(),email_verified:o.z.boolean(),app_metadata:o.z.object({}),user_metadata:o.z.object({})})}},description:"Created user"}}}),async e=>{const{email:t,password:n,client_id:r}=e.req.valid("json"),i=await He(e.env,r);e.set("client_id",i.client_id),Vt(e,i.tenant.id);const a=i.connections.find(p=>p.strategy==="Username-Password-Authentication")?.name||"Username-Password-Authentication",c=await Ca(e.env.data,i.tenant.id,a);try{await Ea(c,{tenantId:i.tenant.id,userId:"",newPassword:n,data:e.env.data})}catch(p){throw new I(400,{message:p?.message||"Password does not meet the requirements"})}if(await Xn({userAdapter:e.env.data.users,tenant_id:i.tenant.id,username:t,provider:Pe}))throw new I(400,{message:"Invalid sign up"});const{hash:u,algorithm:d}=await na(n),f=await e.env.data.users.create(i.tenant.id,{user_id:`${Pe}|${Ii()}`,email:t,email_verified:!1,provider:Pe,connection:"Username-Password-Authentication",is_social:!1,password:{hash:u,algorithm:d}});e.set("user_id",f.user_id),e.set("username",f.email),e.set("connection",f.connection);try{await Ad(e,f)}catch(p){console.error("Failed to send verification email:",p)}return fe(e,i.tenant.id,{type:ue.SUCCESS_SIGNUP,description:"Successful signup"}),e.json({_id:f.user_id,email:f.email,email_verified:!1,app_metadata:{},user_metadata:{}})}).openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/change_password",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(e=>e.toLowerCase())})}}}},responses:{200:{description:"Redirect to the client's redirect uri"}}}),async e=>{const{email:t,client_id:n}=e.req.valid("json"),r=await He(e.env,n);if(e.set("client_id",r.client_id),Vt(e,r.tenant.id),!await Or({userAdapter:e.env.data.users,tenant_id:r.tenant.id,username:t,provider:Pe}))return e.html("If an account with that email exists, we've sent instructions to reset your password.");const s={client_id:n,username:t},a=await e.env.data.loginSessions.create(r.tenant.id,{expires_at:new Date(Date.now()+li*1e3).toISOString(),authParams:s,csrf_token:Oe(),ip:e.get("ip"),useragent:e.get("useragent"),auth0Client:rr(e.get("auth0_client"))});return await Wk(e,t,a.id,a.authParams.state),e.html("If an account with that email exists, we've sent instructions to reset your password.")});function In(){const e="1234567890";let t="";for(let n=0;n<6;n+=1)t+=e[Math.floor(Math.random()*10)];return t.toString()}const LP=new o.OpenAPIHono().openapi(o.createRoute({tags:["passwordless"],method:"post",path:"/start",request:{body:{content:{"application/json":{schema:o.z.union([o.z.object({connection:o.z.literal("email"),client_id:o.z.string(),email:o.z.string().transform(e=>e.toLowerCase()),send:o.z.enum(["link","code"]),authParams:Js.omit({client_id:!0})}),o.z.object({client_id:o.z.string(),connection:o.z.literal("sms"),phone_number:o.z.string(),send:o.z.enum(["link","code"]),authParams:Js.omit({client_id:!0})})])}}}},responses:{200:{description:"Status"}}}),async e=>{const t=e.req.valid("json"),{env:n}=e,{client_id:r,send:i,authParams:s,connection:a}=t,c=await He(e.env,r);e.set("client_id",c.client_id),Vt(e,c.tenant.id);const l=a==="email"?t.email:t.phone_number,u=e.get("ip"),d=e.get("useragent"),f=e.get("auth0_client"),p=rr(f),h=await n.data.loginSessions.create(c.tenant.id,{authParams:{...s,client_id:r,username:l},expires_at:new Date(Date.now()+Ds).toISOString(),csrf_token:Oe(),ip:u,useragent:d,auth0Client:p}),_=await n.data.codes.create(c.tenant.id,{code_id:In(),code_type:"otp",login_id:h.id,expires_at:new Date(Date.now()+Ds).toISOString(),redirect_uri:s.redirect_uri}),g=s?.ui_locales?.split(" ")?.map(y=>y.split("-")[0])[0];return i==="link"?await zd(e,{to:l,code:_.code_id,authParams:{...s,client_id:r},language:g}):await Sd(e,{to:l,code:_.code_id,language:g}),e.html("OK")}).openapi(o.createRoute({tags:["passwordless"],method:"get",path:"/verify_redirect",request:{query:o.z.object({scope:o.z.string(),response_type:o.z.nativeEnum(ot),redirect_uri:o.z.string(),state:o.z.string(),nonce:o.z.string().optional(),verification_code:o.z.string(),connection:o.z.string(),client_id:o.z.string(),email:o.z.string().transform(e=>e.toLowerCase()),audience:o.z.string().optional()})},responses:{302:{description:"Successful verification, redirecting to continue flow.",headers:o.z.object({Location:o.z.string().url()}).openapi({})},400:{description:"Bad Request (e.g., invalid client, invalid code, missing parameters).",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}},500:{description:"Internal Server Error.",content:{"application/json":{schema:o.z.object({error:o.z.string(),error_description:o.z.string().optional()})}}}}}),async e=>{const{env:t}=e,{client_id:n,email:r,verification_code:i,redirect_uri:s,state:a,scope:c,audience:l,response_type:u,nonce:d}=e.req.valid("query"),f=await He(t,n);e.set("client_id",f.client_id),Vt(e,f.tenant.id),e.set("connection","email");const p={client_id:n,redirect_uri:s,state:a,nonce:d,scope:c,audience:l,response_type:u};let h="Something went wrong. Please try again later.";try{const k=await xd(e,{client_id:n,username:r,otp:i,authParams:p,enforceIpCheck:!0});if(k instanceof Response)return k;if(k&&typeof k=="object"&&"access_token"in k)return e.json(k)}catch(k){const x=k;"message"in x&&typeof x.message=="string"&&(h=x.message)}const _=e.get("ip"),g=e.get("useragent"),y=e.get("auth0_client"),m=rr(y),v=await t.data.loginSessions.create(f.tenant.id,{authParams:{...p,username:r},expires_at:new Date(Date.now()+Ds).toISOString(),csrf_token:Oe(),ip:_,useragent:g,auth0Client:m});return e.redirect(`${_t(e.env)}invalid-session?state=${v.id}&error=${encodeURIComponent(h)}`,302)});class Zi extends I{_code;constructor(t,n){super(t,n),this._code=n?.code}get code(){return this._code}}async function DP(e,t,n){const r=n.app_metadata||{},i=r.failed_logins||[],s=Date.now(),a=[...i.filter(c=>s-c<1e3*60*5),s];r.failed_logins=a,await e.users.update(t,n.user_id,{app_metadata:r})}function UP(e){const n=(e.app_metadata||{}).failed_logins||[],r=Date.now();return n.filter(i=>r-i<1e3*60*5)}async function Jk(e,t,n,r){const{data:i}=e.env,{username:s}=n;if(e.set("username",s),!s)throw new W(400,{message:"Username is required"});const a=await Or({userAdapter:e.env.data.users,tenant_id:t.tenant.id,username:s,provider:Pe});if(!a)throw fe(e,t.tenant.id,{type:ue.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"}),new Zi(403,{message:"User not found",code:"USER_NOT_FOUND"});const c=a.linked_to?await i.users.get(t.tenant.id,a.linked_to):a;if(!c)throw new Zi(403,{message:"User not found",code:"USER_NOT_FOUND"});if(e.set("connection",a.connection),e.set("user_id",c.user_id),UP(c).length>=3)throw fe(e,t.tenant.id,{type:ue.FAILED_LOGIN,description:"Too many failed login attempts"}),new Zi(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"});const u=await i.passwords.get(t.tenant.id,a.user_id);if(!(u&&await Bo.compare(n.password,u.password)))throw fe(e,t.tenant.id,{type:ue.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"}),DP(i,t.tenant.id,c),new Zi(403,{message:"Invalid password",code:"INVALID_PASSWORD"});if(!a.email_verified&&t.client_metadata?.email_validation==="enforced"){const p=r?.authParams?.ui_locales?.split(" ")?.map(h=>h.split("-")[0])[0];throw await Ad(e,a,p),fe(e,t.tenant.id,{type:ue.FAILED_LOGIN,description:"Email not verified"}),r&&await TA(e,t.tenant.id,r,"Email not verified"),new Zi(403,{message:"Email not verified",code:"EMAIL_NOT_VERIFIED"})}const f=c.app_metadata||{};return f.failed_logins&&f.failed_logins.length>0&&(f.failed_logins=[],i.users.update(t.tenant.id,c.user_id,{app_metadata:f})),{client:t,authParams:n,user:c,loginSession:r}}async function Xa(e,t,n,r,i){const s=await Jk(e,t,n,r);return gt(e,{...s,ticketAuth:i,authStrategy:{strategy:"Username-Password-Authentication",strategy_type:"database"}})}async function BP(e,t,n,r){await Au(e,{client:t,username:n,provider:Pe,connection:"Username-Password-Authentication",isSocial:!1,ip:e.var.ip});let i=In(),s=await e.env.data.codes.get(t.tenant.id,i,"password_reset");for(;s;)i=In(),s=await e.env.data.codes.get(t.tenant.id,i,"password_reset");const a=e.get("ip"),c=e.get("useragent"),l=e.get("auth0_client"),u=rr(l),d=await e.env.data.loginSessions.create(t.tenant.id,{expires_at:new Date(Date.now()+Sz).toISOString(),authParams:{client_id:t.client_id,username:n},csrf_token:Oe(),ip:a,useragent:c,auth0Client:u}),f=await e.env.data.codes.create(t.tenant.id,{code_id:i,code_type:"password_reset",login_id:d.id,expires_at:new Date(Date.now()+xz).toISOString()});await Wk(e,n,f.code_id,r)}const MP=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.union([o.z.object({credential_type:o.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),otp:o.z.string(),client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),realm:o.z.enum(["email"]),scope:o.z.string().optional()}),o.z.object({credential_type:o.z.literal("http://auth0.com/oauth/grant-type/password-realm"),client_id:o.z.string(),username:o.z.string().transform(e=>e.toLowerCase()),password:o.z.string(),realm:o.z.enum(["Username-Password-Authentication"]),scope:o.z.string().optional()})])}}}},responses:{200:{description:"List of tenants"}}}),async e=>{const t=e.req.valid("json"),{client_id:n,username:r}=t;e.set("username",r);const i=await He(e.env,n);e.set("client_id",n),Vt(e,i.tenant.id);const s=r.toLocaleLowerCase(),a=e.get("ip"),c=e.get("useragent"),l=e.get("auth0_client");let u;if("otp"in t)u=await xd(e,{client_id:n,username:s,otp:t.otp});else if("password"in t){const d=await e.env.data.loginSessions.create(i.tenant.id,{expires_at:new Date(Date.now()+li*1e3).toISOString(),authParams:{client_id:n,username:s},csrf_token:Oe(),ip:a,useragent:c,auth0Client:rr(l)});u=await Xa(e,i,{username:s,password:t.password,client_id:n},d,!0)}else throw new I(400,{message:"Code or password required"});return u});function Zk(e,t){if(!e||t.length===0)return!1;const n=pp(e)?.host??null;if(!n)return!1;for(const r of t){let i;if(r.startsWith("http://")||r.startsWith("https://")?i=pp(r)?.host??null:i=pp("https://"+r)?.host??null,n===i)return!0}return!1}function pp(e){try{return new URL(e)}catch{return null}}function qP(e,t){if(!e||t===void 0)return!1;const n=new Date(e.authenticated_at).getTime(),r=t*1e3;return Date.now()-n>r}async function FP({ctx:e,session:t,client:n,authParams:r,connection:i,login_hint:s}){const a=new URL(e.req.url);e.var.custom_domain&&(a.hostname=e.var.custom_domain);const{ip:c,auth0_client:l,useragent:u}=e.var,d=rr(l);qP(t,r.max_age)&&(t=void 0);const f=await e.env.data.loginSessions.create(n.tenant.id,{expires_at:new Date(Date.now()+li*1e3).toISOString(),authParams:r,csrf_token:Oe(),authorization_url:a.toString(),ip:c,useragent:u,auth0Client:d}),p=n.client_metadata?.universal_login_version==="2"?"/u2":"/u";if(t&&s){const h=await e.env.data.users.get(n.tenant.id,t.user_id);if(h?.email===s)return gt(e,{client:n,loginSession:f,authParams:r,user:h,existingSessionIdToLink:t.id})}if(i==="email"&&s){const h=In();return await e.env.data.codes.create(n.tenant.id,{code_id:h,code_type:"otp",login_id:f.id,expires_at:new Date(Date.now()+li*1e3).toISOString(),redirect_uri:r.redirect_uri}),await zd(e,{code:h,to:s,authParams:r}),e.redirect(`${p}/enter-code?state=${f.id}`)}if(t)return e.redirect(`${p}/check-account?state=${f.id}`);if(p==="/u2"){const h=await e.env.data.promptSettings.get(n.tenant.id),_=Rs.parse(h||{}),g=n.connections.some(y=>y.strategy==="Username-Password-Authentication");if(_.identifier_first===!1&&g)return e.redirect(`${p}/login?state=${f.id}`)}return e.redirect(`${p}/login/identifier?state=${f.id}`)}function HP(e){if(e==="Username-Password-Authentication")return Pe;if(e==="email")return"email";throw new W(403,{message:"Invalid realm"})}async function VP(e,t,n,r,i){const{env:s}=e;e.set("connection",i);const a=await s.data.codes.get(t,n,"ticket");if(!a||a.used_at)throw new W(403,{message:"Ticket not found"});const c=await s.data.loginSessions.get(t,a.login_id);if(!c||!c.authParams.username)throw new W(403,{message:"Session not found"});const l=await He(s,c.authParams.client_id,t);e.set("client_id",c.authParams.client_id),await s.data.codes.used(t,n);const u=HP(i),f=l.connections.find(_=>_.name===i)?.strategy||(u===Pe?"Username-Password-Authentication":"email"),p=f==="Username-Password-Authentication"?"database":"passwordless";let h=await Au(e,{username:c.authParams.username,provider:u,client:l,connection:i,isSocial:!1,ip:e.var.ip});return e.set("username",h.email||h.phone_number),e.set("user_id",h.user_id),gt(e,{authParams:{scope:c.authParams?.scope,...r},loginSession:c,user:h,client:l,authStrategy:{strategy:f,strategy_type:p}})}async function KP({ctx:e,client:t,session:n,redirect_uri:r,state:i,nonce:s,code_challenge_method:a,code_challenge:c,audience:l,scope:u,response_type:d,response_mode:f,organization:p,max_age:h}){const{env:_}=e,g=new URL(r),y=`${g.protocol}//${g.host}`,m=f===pn.WEB_MESSAGE;async function v(le="Login required"){const be=new Headers;if(n&&(fe(e,t.tenant.id,{type:ue.FAILED_SILENT_AUTH,description:le}),qw(t.tenant.id,e.req.header("host")).forEach(ut=>{be.append("set-cookie",ut)})),m)return _f(e,y,JSON.stringify({error:"login_required",error_description:le,state:i}),be);const Ee=new URL(r);if(d===ot.TOKEN||d===ot.TOKEN_ID_TOKEN){const ce=new URLSearchParams;ce.set("error","login_required"),ce.set("error_description",le),i&&ce.set("state",i),Ee.hash=ce.toString()}else Ee.searchParams.set("error","login_required"),Ee.searchParams.set("error_description",le),i&&Ee.searchParams.set("state",i);const Te={Location:Ee.toString()},$t=be.get("set-cookie");return $t&&(Te["set-cookie"]=$t),new Response(null,{status:302,headers:Te})}const k=!n||n?.expires_at&&new Date(n.expires_at)<new Date||n?.idle_expires_at&&new Date(n.idle_expires_at)<new Date,x=n&&h!==void 0&&Date.now()-new Date(n.authenticated_at).getTime()>h*1e3;if(k||x)return v();e.set("user_id",n.user_id);const b=await _.data.users.get(t.tenant.id,n.user_id);if(!b)return console.error("User not found",n.user_id),v("User not found");e.set("username",b.email),e.set("connection",b.connection);let S;if(p&&(S=await _.data.organizations.get(t.tenant.id,p),!S))return v("Organization not found");const A=l||t.tenant.audience;let C=u||"",P=[];if(A)try{const le=await Ys(e,{tenantId:t.tenant.id,clientId:t.client_id,audience:A,requestedScopes:u?.split(" ")||[],organizationId:S?.id,userId:b.user_id});C=le.scopes.join(" "),P=le.permissions}catch(le){if(le?.statusCode===403||le?.status===403){const be=le?.body?.error_description||le?.message||"Access denied";return v(be)}throw le}else if(S&&!(await _.data.userOrganizations.list(t.tenant.id,{q:`user_id:${b.user_id}`,per_page:1e3})).userOrganizations.some(Ee=>Ee.organization_id===S.id))return v("User is not a member of the specified organization");const R=await _.data.loginSessions.create(t.tenant.id,{csrf_token:Oe(),authParams:{client_id:t.client_id,audience:l,scope:u,state:i,nonce:s,response_type:d,redirect_uri:r,organization:p,max_age:h},expires_at:new Date(Date.now()+300*1e3).toISOString(),session_id:n.id,ip:e.var.ip,useragent:e.var.useragent}),E=h!==void 0?Math.floor(new Date(n.authenticated_at).getTime()/1e3):void 0,L={client:t,authParams:{client_id:t.client_id,audience:l,code_challenge_method:a,code_challenge:c,scope:C,state:i,nonce:s,response_type:d,redirect_uri:r,max_age:h},user:b,session_id:n.id,auth_time:E,permissions:P,organization:S},M=d===ot.CODE?await y2(e,{user:b,client:t,authParams:L.authParams,login_id:R.id}):await gu(e,L);await _.data.sessions.update(t.tenant.id,n.id,{used_at:new Date().toISOString(),last_interaction_at:new Date().toISOString(),login_session_id:R.id,device:{...n.device,last_ip:e.var.ip||"",last_user_agent:e.var.useragent||""},idle_expires_at:n.idle_expires_at?new Date(Date.now()+pu*1e3).toISOString():void 0}),fe(e,t.tenant.id,{type:ue.SUCCESS_SILENT_AUTH,description:"Successful silent authentication"});const H=new Headers;if(sl(t.tenant.id,n.id,e.req.header("host")).forEach(le=>{H.append("set-cookie",le)}),m)return _f(e,y,JSON.stringify({...M,state:i}),H);const Q=new URL(r);if(d===ot.TOKEN||d===ot.TOKEN_ID_TOKEN){const le=new URLSearchParams;Object.entries(M).forEach(([be,Ee])=>{Ee!==void 0&&le.set(be,String(Ee))}),i&&le.set("state",i),Q.hash=le.toString()}else Object.entries(M).forEach(([le,be])=>{be!==void 0&&Q.searchParams.set(le,String(be))}),i&&Q.searchParams.set("state",i);const se={Location:Q.toString()},we=H.get("set-cookie");return we&&(se["set-cookie"]=we),new Response(null,{status:302,headers:se})}const GP=["email","sms","Username-Password-Authentication"],xb=o.z.object({client_id:o.z.string().optional(),vendor_id:o.z.string().optional(),redirect_uri:o.z.string().optional(),scope:o.z.string().optional(),state:o.z.string().optional(),prompt:o.z.string().optional(),response_mode:o.z.nativeEnum(pn).optional(),response_type:o.z.nativeEnum(ot).optional(),audience:o.z.string().optional(),connection:o.z.string().optional(),nonce:o.z.string().optional(),max_age:o.z.string().optional(),acr_values:o.z.string().optional(),login_ticket:o.z.string().optional(),code_challenge_method:o.z.nativeEnum(uu).optional(),code_challenge:o.z.string().optional(),realm:o.z.string().optional(),auth0Client:o.z.string().optional(),organization:o.z.string().optional(),login_hint:o.z.string().optional(),screen_hint:o.z.string().optional(),ui_locales:o.z.string().optional()});function WP(e){try{const t=e.split(".");if(t.length<2||!t[1])return null;const n=new TextDecoder().decode(wr.decode(t[1],{strict:!1})),r=JSON.parse(n);return typeof r!="object"||r===null?null:r}catch{return null}}const JP=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:xb.extend({client_id:o.z.string(),screen_hint:o.z.string().openapi({example:"signup",description:'Optional hint for the screen to show, like "signup" or "login".'}).optional(),request:o.z.string().openapi({description:"JWT containing authorization request parameters (OpenID Connect Core Section 6.1)"}).optional()}).passthrough()},responses:{200:{description:"Successful authorization response. This can be an HTML page (e.g., for silent authentication iframe or universal login page) or a JSON object containing tokens (e.g., for response_mode=web_message).",content:{"text/html":{schema:o.z.string().openapi({example:"<html>...</html>"})},"application/json":{schema:vh}}},302:{description:"Redirect to the client's redirect URI, an authentication page, or an external identity provider.",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request. Invalid parameters or other client-side errors.",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}},403:{description:"Forbidden. The request is not allowed (e.g., invalid origin).",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async e=>{const{env:t}=e,n=e.req.valid("query");let r={};if(n.request){const D=WP(n.request);if(D){const Q=xb.safeParse(D);Q.success&&(r=Q.data)}}const{client_id:i,vendor_id:s,redirect_uri:a,scope:c,state:l,audience:u,nonce:d,connection:f,response_type:p,response_mode:h,code_challenge:_,code_challenge_method:g,prompt:y,max_age:m,acr_values:v,login_ticket:k,realm:x,login_hint:b,ui_locales:S,organization:A}={...r,...n};e.set("log","authorize");const C=await He(t,i);e.set("client_id",C.client_id),Vt(e,C.tenant.id);let P=a;typeof a=="string"&&(P=a.split("#")[0]);const R=e.req.header("origin");if(R&&!Zk(R,C.web_origins||[]))throw new I(403,{message:`Origin ${R} not allowed`});if(!p){if(P){const D=new URL(P);return D.searchParams.set("error","invalid_request"),D.searchParams.set("error_description","Missing required parameter: response_type"),l&&D.searchParams.set("state",l),e.redirect(D.toString())}throw new I(400,{message:"Missing required parameter: response_type"})}const E={redirect_uri:P,scope:c,state:l,client_id:i,vendor_id:s,audience:u,nonce:d,prompt:y,response_type:p,response_mode:h,code_challenge:_,code_challenge_method:g,username:b,ui_locales:S,organization:A,max_age:m?parseInt(m,10):void 0,acr_values:v};if(E.redirect_uri){const D=C.callbacks||[];if(e.var.host&&(D.push(`${wu(e.env)}/*`),D.push(`${_t(e.env)}/*`)),!N_(E.redirect_uri,D,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new I(400,{message:`Invalid redirect URI - ${E.redirect_uri}`})}let L;const M=Ez(C.tenant.id,e.req.header("cookie"));for(const D of M){const Q=await t.data.sessions.get(C.tenant.id,D);if(Q&&!Q.revoked_at){L=Q;break}}if(y=="none"){if(!P||!l||!p)throw new I(400,{message:"Missing required parameters for silent auth: redirect_uri, state, and response_type"});return KP({ctx:e,session:L||void 0,redirect_uri:P,state:l,response_type:p,response_mode:h,client:C,nonce:d,code_challenge_method:g,code_challenge:_,audience:u,scope:c,organization:A,max_age:m?parseInt(m,10):void 0})}if(C.connections.length===1&&C.connections[0]&&!GP.includes(C.connections[0].strategy||""))return Jy(e,C,C.connections[0].name,E);if(f&&f!=="email")return Jy(e,C,f,E);if(k){const D=await VP(e,C.tenant.id,k,E,x);return D instanceof Response?D:e.json(D)}const H=await FP({ctx:e,client:C,authParams:E,session:L||void 0,connection:f,login_hint:b});return H instanceof Response?H:e.json(H)}),ZP=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:o.z.object({client_id:o.z.string(),redirect_url:o.z.string().optional(),login_hint:o.z.string().toLowerCase().optional(),screen_hint:o.z.enum(["account","change-email","change-phone","change-password"]).optional().default("account")})},responses:{302:{description:"Redirect to the account page with login session state or login page",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request. Invalid parameters or other client-side errors.",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async e=>{const{env:t}=e,{client_id:n,redirect_url:r,login_hint:i,screen_hint:s}=e.req.valid("query");e.set("log","account");const a=await He(t,n);e.set("client_id",a.client_id),Vt(e,a.tenant.id);const c={redirect_uri:r||e.req.url,client_id:n,username:i},l=e.req.header("origin");if(l&&!Zk(l,a.web_origins||[]))throw new I(403,{message:`Origin ${l} not allowed`});if(c.redirect_uri){const v=a.callbacks||[];if(e.var.host&&(v.push(`${wu(e.env)}/*`),v.push(`${_t(e.env)}/*`)),!N_(c.redirect_uri,v,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new I(400,{message:`Invalid redirect URI - ${c.redirect_uri}`})}const u=ui(a.tenant.id,e.req.header("cookie")),d=u?await t.data.sessions.get(a.tenant.id,u):void 0,f=d&&!d.revoked_at?d:void 0,p=new URL(e.req.url);e.var.custom_domain&&(p.hostname=e.var.custom_domain);const{ip:h,auth0_client:_,useragent:g}=e.var,y=rr(_),m=await t.data.loginSessions.create(a.tenant.id,{expires_at:new Date(Date.now()+li*1e3).toISOString(),authParams:c,csrf_token:Oe(),authorization_url:p.toString(),ip:h,useragent:g,auth0Client:y});if(f){if(i&&(await t.data.users.get(a.tenant.id,f.user_id))?.email!==i)return e.redirect(`${_t(e.env)}login/identifier?state=${encodeURIComponent(m.id)}`);if(await t.data.loginSessions.update(a.tenant.id,m.id,{session_id:f.id}),s==="change-email"){const k=new URL("/u/account/change-email",e.req.url);return k.searchParams.set("state",m.id),e.redirect(k.toString())}const v=new URL("/u/account",e.req.url);return v.searchParams.set("state",m.id),e.redirect(v.toString())}return e.redirect(`${_t(e.env)}login/identifier?state=${encodeURIComponent(m.id)}`)});function XP(e){const t=new o.OpenAPIHono;t.use(async(r,i)=>{const s=Do(r,e.dataAdapter),a=e.dataAdapter.cache||ts({defaultTtlSeconds:0,maxEntries:100,cleanupIntervalMs:0}),c=e.dataAdapter.cache?300:0,l=Ja(s,{defaultTtl:c,cacheEntities:["tenants","connections","clientConnections","customDomains","clients","branding","themes","promptSettings","forms","resourceServers","roles","organizations","userRoles","userPermissions"],cache:a});return r.env.data=Wa(r,l),i()}),t.use("/oauth/token",Rk({origin:r=>r||"",allowHeaders:["Tenant-Id","Content-Type","Auth0-Client","Upgrade-Insecure-Requests"],allowMethods:["POST"],maxAge:600})),t.use(es).use(Qo).use(wd(t));const n=t.route("/v2/logout",oN).route("/userinfo",cN).route("/.well-known",lN).route("/oauth/token",PP).route("/dbconnections",RP).route("/passwordless",LP).route("/co/authenticate",MP).route("/authorize",JP).route("/account",ZP).route("/callback",rN);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Oauth API"},security:[{oauth2:["openid","email","profile"]}]}),I_(n),n}var B_=Symbol("RENDERER"),J0=Symbol("ERROR_HANDLER"),qe=Symbol("STASH"),Xk=Symbol("INTERNAL"),YP=Symbol("MEMO"),tu=Symbol("PERMALINK"),Sb=e=>(e[Xk]=!0,e),Yk=e=>({value:t,children:n})=>{if(!n)return;const r={children:[{tag:Sb(()=>{e.push(t)}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:Sb(()=>{e.pop()}),props:{}});const i={tag:"",props:r,type:""};return i[J0]=s=>{throw e.pop(),s},i},Qk=e=>{const t=[e],n=Yk(t);return n.values=t,n.Provider=n,No.push(n),n},No=[],e4=e=>{const t=[e],n=(r=>{t.push(r.value);let i;try{i=r.children?(Array.isArray(r.children)?new i4("",{},r.children):r.children).toString():""}catch(s){throw t.pop(),s}return i instanceof Promise?i.finally(()=>t.pop()).then(s=>Cr(s,s.callbacks)):(t.pop(),Cr(i))});return n.values=t,n.Provider=n,n[B_]=Yk(t),No.push(n),n},rs=e=>e.values.at(-1),Oc={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},Z0={},Rc="data-precedence",Ya=e=>Array.isArray(e)?e:[e],zb=new WeakMap,Ab=(e,t,n,r)=>({buffer:i,context:s})=>{if(!i)return;const a=zb.get(s)||{};zb.set(s,a);const c=a[e]||=[];let l=!1;const u=Oc[e];if(u.length>0){e:for(const[,d]of c)for(const f of u)if((d?.[f]??null)===n?.[f]){l=!0;break e}}if(l?i[0]=i[0].replaceAll(t,""):u.length>0?c.push([t,n,r]):c.unshift([t,n,r]),i[0].indexOf("</head>")!==-1){let d;if(r===void 0)d=c.map(([f])=>f);else{const f=[];d=c.map(([p,,h])=>{let _=f.indexOf(h);return _===-1&&(f.push(h),_=f.length-1),[p,_]}).sort((p,h)=>p[1]-h[1]).map(([p])=>p)}d.forEach(f=>{i[0]=i[0].replaceAll(f,"")}),i[0]=i[0].replace(/(?=<\/head>)/,d.join(""))}},Qa=(e,t,n)=>Cr(new _n(e,n,Ya(t??[])).toString()),ec=(e,t,n,r)=>{if("itemProp"in n)return Qa(e,t,n);let{precedence:i,blocking:s,...a}=n;i=r?i??"":void 0,r&&(a[Rc]=i);const c=new _n(e,a,Ya(t||[])).toString();return c instanceof Promise?c.then(l=>Cr(c,[...l.callbacks||[],Ab(e,l,a,i)])):Cr(c,[Ab(e,c,a,i)])},QP=({children:e,...t})=>{const n=M_();if(n){const r=rs(n);if(r==="svg"||r==="head")return new _n("title",t,Ya(e??[]))}return ec("title",e,t,!1)},eO=({children:e,...t})=>{const n=M_();return["src","async"].some(r=>!t[r])||n&&rs(n)==="head"?Qa("script",e,t):ec("script",e,t,!1)},tO=({children:e,...t})=>["href","precedence"].every(n=>n in t)?(t["data-href"]=t.href,delete t.href,ec("style",e,t,!0)):Qa("style",e,t),nO=({children:e,...t})=>["onLoad","onError"].some(n=>n in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?Qa("link",e,t):ec("link",e,t,"precedence"in t),rO=({children:e,...t})=>{const n=M_();return n&&rs(n)==="head"?Qa("meta",e,t):ec("meta",e,t,!1)},t4=(e,{children:t,...n})=>new _n(e,n,Ya(t??[])),iO=e=>(typeof e.action=="function"&&(e.action=tu in e.action?e.action[tu]:void 0),t4("form",e)),n4=(e,t)=>(typeof t.formAction=="function"&&(t.formAction=tu in t.formAction?t.formAction[tu]:void 0),t4(e,t)),oO=e=>n4("input",e),sO=e=>n4("button",e);const fp=Object.freeze(Object.defineProperty({__proto__:null,button:sO,form:iO,input:oO,link:nO,meta:rO,script:eO,style:tO,title:QP},Symbol.toStringTag,{value:"Module"}));var aO=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),nu=e=>aO.get(e)||e,r4=(e,t)=>{for(const[n,r]of Object.entries(e)){const i=n[0]==="-"||!/[A-Z]/.test(n)?n:n.replace(/[A-Z]/g,s=>`-${s.toLowerCase()}`);t(i,r==null?null:typeof r=="number"?i.match(/^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/)?`${r}`:`${r}px`:r)}},wa=void 0,M_=()=>wa,cO=e=>/[A-Z]/.test(e)&&e.match(/^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/)?e.replace(/([A-Z])/g,"-$1").toLowerCase():e,lO=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],uO=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","download","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"],q_=(e,t)=>{for(let n=0,r=e.length;n<r;n++){const i=e[n];if(typeof i=="string")po(i,t);else{if(typeof i=="boolean"||i===null||i===void 0)continue;i instanceof _n?i.toStringToBuffer(t):typeof i=="number"||i.isEscaped?t[0]+=i:i instanceof Promise?t.unshift("",i):q_(i,t)}}},_n=class{tag;props;key;children;isEscaped=!0;localContexts;constructor(e,t,n){this.tag=e,this.props=t,this.children=n}get type(){return this.tag}get ref(){return this.props.ref||null}toString(){const e=[""];this.localContexts?.forEach(([t,n])=>{t.values.push(n)});try{this.toStringToBuffer(e)}finally{this.localContexts?.forEach(([t])=>{t.values.pop()})}return e.length===1?"callbacks"in e?hj(Cr(e[0],e.callbacks)).toString():e[0]:fj(e,e.callbacks)}toStringToBuffer(e){const t=this.tag,n=this.props;let{children:r}=this;e[0]+=`<${t}`;const i=wa&&rs(wa)==="svg"?s=>cO(nu(s)):s=>nu(s);for(let[s,a]of Object.entries(n))if(s=i(s),s!=="children"){if(s==="style"&&typeof a=="object"){let c="";r4(a,(l,u)=>{u!=null&&(c+=`${c?";":""}${l}:${u}`)}),e[0]+=' style="',po(c,e),e[0]+='"'}else if(typeof a=="string")e[0]+=` ${s}="`,po(a,e),e[0]+='"';else if(a!=null)if(typeof a=="number"||a.isEscaped)e[0]+=` ${s}="${a}"`;else if(typeof a=="boolean"&&uO.includes(s))a&&(e[0]+=` ${s}=""`);else if(s==="dangerouslySetInnerHTML"){if(r.length>0)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");r=[Cr(a.__html)]}else if(a instanceof Promise)e[0]+=` ${s}="`,e.unshift('"',a);else if(typeof a=="function"){if(!s.startsWith("on")&&s!=="ref")throw new Error(`Invalid prop '${s}' of type 'function' supplied to '${t}'.`)}else e[0]+=` ${s}="`,po(a.toString(),e),e[0]+='"'}if(lO.includes(t)&&r.length===0){e[0]+="/>";return}e[0]+=">",q_(r,e),e[0]+=`</${t}>`}},hp=class extends _n{toStringToBuffer(e){const{children:t}=this,n={...this.props};t.length&&(n.children=t.length===1?t[0]:t);const r=this.tag.call(null,n);if(!(typeof r=="boolean"||r==null))if(r instanceof Promise)if(No.length===0)e.unshift("",r);else{const i=No.map(s=>[s,s.values.at(-1)]);e.unshift("",r.then(s=>(s instanceof _n&&(s.localContexts=i),s)))}else r instanceof _n?r.toStringToBuffer(e):typeof r=="number"||r.isEscaped?(e[0]+=r,r.callbacks&&(e.callbacks||=[],e.callbacks.push(...r.callbacks))):po(r,e)}},i4=class extends _n{toStringToBuffer(e){q_(this.children,e)}},dO=(e,t,...n)=>{t??={},n.length&&(t.children=n.length===1?n[0]:n);const r=t.key;delete t.key;const i=Lc(e,t,n);return i.key=r,i},Eb=!1,Lc=(e,t,n)=>{if(!Eb){for(const r in Z0)fp[r][B_]=Z0[r];Eb=!0}return typeof e=="function"?new hp(e,t,n):fp[e]?new hp(fp[e],t,n):e==="svg"||e==="head"?(wa||=e4(""),new _n(e,t,[new hp(wa,{value:e},n)])):new _n(e,t,n)},To=({children:e})=>new i4("",{children:e},Array.isArray(e)?e:e?[e]:[]),pO=(e,t,...n)=>{let r;if(n.length>0)r=n;else{const i=e.props.children;r=Array.isArray(i)?i:[i]}return dO(e.tag,{...e.props,...t},...r)};function w(e,t,n){let r;if(!t||!("children"in t))r=Lc(e,t,[]);else{const i=t.children;r=Array.isArray(i)?Lc(e,t,i):Lc(e,t,[i])}return r.key=n,r}async function Ae(e,t,n=!1){const{env:r}=e,i=await r.data.loginSessions.get(e.var.tenant_id||"",t);if(!i)throw new W(400,{message:"Login session not found"});e.set("loginSession",i);const s=await He(r,i.authParams.client_id);e.set("client_id",s.client_id),Vt(e,s.tenant.id);const a=s.tenant;if(i.session_id&&!n){if(!i.authParams.redirect_uri)throw new W(400,{message:"Login session closed and no redirect URI available"});const p=new URL(i.authParams.redirect_uri);throw p.searchParams.set("error","access_denied"),p.searchParams.set("error_description","Login session closed"),i.authParams.state&&p.searchParams.set("state",i.authParams.state),new qt(p.toString(),302)}const[c,l]=await Promise.all([r.data.themes.get(a.id,"default"),r.data.branding.get(a.id)]),u=c??uf,d=l?{...l,favicon_url:e.var.custom_domain?l.favicon_url:void 0}:null,f=i.authParams?.ui_locales?.split(" ")?.map(p=>p.split("-")[0])?.find(p=>{if(Array.isArray(T.options.supportedLngs))return T.options.supportedLngs.includes(p)});return await T.changeLanguage(f||"en"),{theme:u,branding:d,client:s,tenant:a,loginSession:i}}async function Ai(e,t,n){const{theme:r,branding:i,client:s,tenant:a,loginSession:c}=await Ae(e,t,!0),l=ui(s.tenant.id,e.req.header("cookie")),u=l?await e.env.data.sessions.get(s.tenant.id,l):null;if(n?.continuationScope&&RA(c,n.continuationScope)){if(!c.user_id)throw new qt(`/u/login/identifier?state=${encodeURIComponent(t)}`);const h=await e.env.data.users.get(s.tenant.id,c.user_id);if(!h)throw new qt(`/u/login/identifier?state=${encodeURIComponent(t)}`);const _=c.session_id?await e.env.data.sessions.get(s.tenant.id,c.session_id):null;return{theme:r,branding:i,client:s,user:h,tenant:a,loginSession:c,session:_,isContinuation:!0}}if(!u||u.revoked_at||!c.session_id)throw new qt(`/u/login/identifier?state=${encodeURIComponent(t)}`);const f=await e.env.data.sessions.get(s.tenant.id,c.session_id),p=await e.env.data.users.get(s.tenant.id,u.user_id);if(!p||f?.user_id!==u.user_id)throw new qt(`/u/login/identifier?state=${encodeURIComponent(t)}`);return{theme:r,branding:i,client:s,user:p,tenant:a,loginSession:c,session:f,isContinuation:!1}}const _p={"Username-Password-Authentication":"password",email:"email",sms:"sms"};async function o4(e,t,n,r,i){if(r==="username"||i==="password")return"password";if(i==="code")return r==="sms"?"sms":"email";const a=(r==="email"?await Uo({userAdapter:e.env.data.users,tenant_id:t.tenant.id,email:n}):await Xn({userAdapter:e.env.data.users,tenant_id:t.tenant.id,username:n,provider:r==="sms"?"sms":Pe}))?.app_metadata?.strategy;if(a&&_p[a])return _p[a];const c=t.connections.map(u=>_p[u.strategy]).filter(u=>u!==void 0);return c.length===1&&c[0]?c[0]:(await e.env.data.promptSettings.get(t.tenant.id)).password_first&&c.includes("password")?"password":r==="sms"?"sms":"email"}const F_=({theme:e,branding:t})=>{const n=e?.widget?.logo_url||t?.logo_url;return n?w("div",{className:"inline-flex h-9 items-center",children:w("img",{src:n,className:"h-full w-auto",alt:"Logo"})}):w(To,{})},s4=e=>w("div",{className:"mt-8",children:e.client?.client_metadata?.termsAndConditionsUrl&&w("div",{className:"text-xs text-gray-300",children:[T.t("agree_to")," ",w("a",{href:e.client.client_metadata.termsAndConditionsUrl,className:"text-primary hover:underline",target:"_blank",rel:"noreferrer",children:T.t("terms")})]})});var mp={exports:{}};var Cb;function fO(){return Cb||(Cb=1,(function(e){(function(){var t={}.hasOwnProperty;function n(){for(var s="",a=0;a<arguments.length;a++){var c=arguments[a];c&&(s=i(s,r(c)))}return s}function r(s){if(typeof s=="string"||typeof s=="number")return s;if(typeof s!="object")return"";if(Array.isArray(s))return n.apply(null,s);if(s.toString!==Object.prototype.toString&&!s.toString.toString().includes("[native code]"))return s.toString();var a="";for(var c in s)t.call(s,c)&&s[c]&&(a=i(a,c));return a}function i(s,a){return a?s?s+" "+a:s+a:s}e.exports?(n.default=n,e.exports=n):window.classNames=n})()})(mp)),mp.exports}var hO=fO();const Be=Bw(hO),_O=e=>e==="small"?"text-base":e==="medium"?"text-2xl":e==="large"?"text-3xl":"",Ze=({name:e,size:t,className:n=""})=>{const r=_O(t);return w("span",{className:Be(`uicon-${e}`,n,r)})},mO=(e,t)=>{const n=e.replace("#",""),r=parseInt(n,16),i=r>>16&255,s=r>>8&255,a=r&255,c=Math.min(255,Math.round(i+(255-i)*t)),l=Math.min(255,Math.round(s+(255-s)*t)),u=Math.min(255,Math.round(a+(255-a)*t));return`#${(c<<16|l<<8|u).toString(16).padStart(6,"0")}`},Po="mm9lzezw",gO=(e,t)=>{const n=e?.colors?.primary_button||t?.colors?.primary||"#000000",r=e?.colors?.base_hover_color||mO(n,.2),i=e?.colors?.primary_button_label||"#ffffff";return`
|
|
87
87
|
body {
|
|
88
88
|
--primary-color: ${n};
|
|
89
89
|
--primary-hover: ${r};
|
|
@@ -440,4 +440,4 @@ Varmista, että avaat kirjautumislinkin samalla selaimella, jolla aloitit kirjau
|
|
|
440
440
|
Voit aloittaa uuden kirjautumisen klikkaamalla alla olevaa linkkiä.`,ize="Virheellinen linkki",oze="Linkitetyt tilit",sze="Kirjaudu sisään napsauttamalla painiketta",aze="Kirjaudu sisään",cze="Tai kirjoita koodi osoitteessa {{vendorName}} kirjautumisen loppuun saattamiseksi.",lze="Kirjoita sähköpostiosoitteesi avataksesi tämän ohjelman osoitteessa {{service}}",uze="Yhdistä tilisi {{service}}",dze="Olet kirjautunut sisään nimellä",pze="Kirjaudu sisään",fze="Kirjoita sähköpostiosoitteesi kirjautuaksesi sisään.",hze="Anna sähköpostiosoitteesi, niin lähetämme sinulle kirjautumiskoodin.",_ze="Kirjoita sähköpostiosoitteesi tai puhelinnumerosi kirjautuaksesi sisään",mze="Anna sähköpostiosoitteesi, niin lähetämme sinulle kirjautumislinkin.",gze="Anna puhelinnumerosi kirjautuaksesi sisään",yze="Kirjoita {{authMethod}} kirjautuaksesi sisään.",bze="Kirjaudu ulos",vze="Uusi sähköpostiosoite",wze="Yksi kertainen koodi lähetetään uuteen sähköpostiosoitteeseesi, syötä koodi seuraavassa vaiheessa.",kze="Ei sähköpostiosoitetta asetettu",$ze="Ei, haluan käyttää toista tiliä",xze="tai",Sze="Salasana",zze="Salasana sisältää kielletyn sanan",Aze="Salasana ei saa sisältää henkilötietoja, kuten nimeäsi tai sähköpostiosoitettasi",Eze="Salasana on nollattu",Cze="Menestys",Ize="Salasanan on sisällettävä vähintään yksi pieni kirjain",jze="Salasanan on sisällettävä vähintään yksi numero",Nze="Salasanan on sisällettävä vähintään yksi erikoismerkki",Tze="Salasanan on sisällettävä vähintään yksi iso kirjain",Pze="Koodia ei löytynyt tai se on vanhentunut",Oze="Salasanaa ei voitu nollata",Rze="Salasanaa on käytetty äskettäin, eikä sitä voi käyttää uudelleen",Lze="Salasanan on oltava vähintään {{minLength}} merkkiä",Dze="Vaihda salasana tilillesi {{vendorName}} ",Uze="Vaihda salasana tilillesi {{vendorName}} ",Bze="Puhelinnumero",Mze="Tietosuojakäytäntö",qze="Uudelleenohjaus",Fze="Vahvista salasana",Hze="Rekisteröi uusi salasana",Vze="Lähetä koodi uudelleen",Kze="Vaihda salasana",Gze="Kirjoita alla oleva uusi salasanasi sähköpostitiliä varten: ",Wze="Napsauta painiketta salasanasi palauttamiseksi",Jze="Napsauta painiketta salasanasi palauttamiseksi",Zze="Nollaa salasanasi",Xze="Vaihda salasana tilillesi {{vendorName}} ",Yze="Nollaa salasana",Qze="Lähetä",e9e="Lähetä minulle uusi maaginen linkki",t9e="Muista tarkistaa roskapostikansiosi, jos sähköposti ei ole saapunut.",n9e="Aseta salasana",r9e="Näytä salasana",i9e="Kirjaudu sisään",o9e="Rekisteröityminen",s9e="Rekisteröidy onnistuneesti",a9e="{{code}} on kirjautumiskoodisi {{vendorName}}",c9e="Näyttää siltä, että Spotify-tilisi on tällä hetkellä yhdistetty toiseen Sesamy-tiliin. Mutta älä pelkää, me opastamme sinua prosessin läpi, jotta saat tämän korjattua.",l9e="Siirry Spotifyn Content Access -sivulle",u9e='Aloitetaan poistamalla Spotify-tilisi linkitys. Klikkaa alla olevaa painiketta siirtyäksesi Spotifyn Content Access -sivulle. Kun olet kirjautunut sisään Spotify-tilillesi, etsi Sesamy yhdistettyjen alustojen luettelosta. Napsauta "Unlink" Sesamyn logon vieressä.',d9e="Vaihe 1: Poista Spotify-tilisi linkitys",p9e="Kun olet onnistuneesti irrottanut Spotify-tilisi, voit yhdistää sen uudelleen Sesamyn kanssa. Toista vain aiemmin tekemäsi vaiheet, jotka johtivat sinut tälle sivulle.",f9e="Vaihe 2: Yhdistä Spotify-tilisi uudelleen Sesamyn kanssa",h9e="Hups! Spotify-tilisi on jo linkitetty",_9e="Valmis",m9e="Jos sinulla on kysyttävää tai tarvitset apua, voit ottaa yhteyttä tukitiimiimme.",g9e="Ehdot ja edellytykset",y9e="Jokin meni pieleen. Yritä uudelleen.",b9e="Irrota",v9e="Sähköpostiosoitteesi on vahvistettava. Olemme lähettäneet uuden sähköpostiviestin sähköpostiisi.",w9e="Päivitä sähköposti",k9e="Käyttäjätiliä ei ole olemassa",$9e="Käyttäjätiliä ei ole olemassa",x9e="Emme löytäneet käyttäjää, jolla on annettu sähköpostiosoite. Yritä uudelleen.",S9e="Yritä uudelleen.",z9e="Validoi koodi",A9e="Tarkista sähköpostin vahvistusohjeet postilaatikostasi.",E9e="Rekisteröitynyt",C9e="Vahvista sähköpostiosoitteesi napsauttamalla painiketta",I9e="Vahvista sähköpostiosoitteesi",j9e="Vahvista sähköpostiosoitteesi",N9e="Vahvista tili",T9e="Vahvista sähköpostiosoitteesi",P9e="Tervetuloa",O9e="Tervetuloa tilillesi {{vendorName}}!",R9e="Tarkista sähköpostisi osoitteesta <0>{{email}}</0> ja syötä lähettämämme kuusinumeroinen koodi.",L9e="Jatka tällä tilillä",D9e="Kyllä, jatka {{text}}",U9e="Kyllä, jatka olemassa olevalla tilillä",B9e={account_detected:Rxe,account_page_description:Lxe,account_title:Dxe,account_with_sso_provider:Uxe,agree_to:Bxe,and:Mxe,auth_method_email:qxe,auth_method_email_or_phone:Fxe,auth_method_phone:Hxe,callback_url_mismatch:Vxe,callback_url_not_allowed:Kxe,change_email:Gxe,check_email_title:Wxe,click_to_sign_up_description:Jxe,code_email_enter_code:Zxe,code_email_subject:Xxe,code_email_title:Yxe,code_expired:Qxe,code_invalid:eSe,code_sent_template:tSe,code_used:nSe,code_valid_30_minutes:rSe,configuration_error_message:iSe,confirm_password:oSe,confirm_unlink:sSe,contact_support:aSe,contact_us:cSe,continue:"Jatka",continue_social_login:lSe,continue_with:uSe,continue_with_sso_provider_headline:dSe,copyright:pSe,copyright_sesamy:fSe,create_account_description:hSe,create_account_email_invalid:_Se,create_account_passwords_didnt_match:mSe,create_account_title:gSe,create_account_weak_password:ySe,create_new_account_link:bSe,create_password_account_title:vSe,dont_have_account:wSe,current_email:kSe,currently_logged_in_as:$Se,edit:xSe,email:SSe,email_already_taken:zSe,email_changed_to_template:ASe,email_or_phone_placeholder:ESe,email_placeholder:CSe,email_validated:ISe,email_validated_cta:jSe,email_verification_for_signup_sent_description:NSe,email_verification_for_signup_sent_title:TSe,embedded_browser_detected:PSe,embedded_browser_warning:OSe,enter_a_code_btn:RSe,enter_email_for_verification_description:LSe,enter_new_email:DSe,enter_new_password_placeholder:USe,enter_password:BSe,enter_password_description:MSe,enter_your_password_btn:qSe,error_page_title:FSe,expired_code:HSe,fokus_info_message:VSe,forgot_password_cta:KSe,forgot_password_description:GSe,forgot_password_email_sent:WSe,forgot_password_link:JSe,forgot_password_title:ZSe,go_back:XSe,hide_password:YSe,incognito_mode_detected:QSe,incognito_mode_warning:eze,"invalid-email":"Virheellinen sähköpostiosoite",invalid_identifier:tze,invalid_password:nze,invalid_session_body:rze,invalid_session_title:ize,linked_accounts:oze,link_email_click_to_login:sze,link_email_login:aze,link_email_or_enter_code:cze,link_page_body:lze,link_page_headline:uze,logged_in_as:dze,login:pze,login_description:fze,login_description_code:hze,login_description_combined:_ze,login_description_link:mze,login_description_phone:gze,login_description_template:yze,logout:bze,new_email:vze,new_email_code_info:wze,no_email_address:kze,no_use_another:$ze,or:xze,password:Sze,password_contains_forbidden_word:zze,password_contains_personal_info:Aze,password_has_been_reset:Eze,password_has_been_reset_title:Cze,password_missing_lowercase:Ize,password_missing_number:jze,password_missing_special:Nze,password_missing_uppercase:Tze,password_reset_code_expired:Pze,password_reset_failed:Oze,password_reused:Rze,password_too_short:Lze,password_reset_subject:Dze,password_reset_title:Uze,phone_placeholder:Bze,privacy_policy:Mze,redirecting:qze,reenter_new_password_placeholder:Fze,register_password_account:Hze,resend_code:Vze,reset_password_cta:Kze,reset_password_description:Gze,reset_password_email_click_to_reset:Wze,reset_password_email_cta:Jze,reset_password_email_reset:Zze,reset_password_subject:Xze,reset_password_title:Yze,send:Qze,send_me_a_new_magic_link:e9e,sent_code_spam:t9e,"Server error: Invalid code":"Virheellinen koodi",set_password:n9e,show_password:r9e,sign_in:i9e,signup:o9e,signup_success:s9e,sms_code_text:a9e,spotify_already_linked_body:c9e,spotify_already_linked_cta:l9e,spotify_already_linked_step1_body:u9e,spotify_already_linked_step1_title:d9e,spotify_already_linked_step2_body:p9e,spotify_already_linked_step2_title:f9e,spotify_already_linked_title:h9e,success:_9e,support_info:m9e,terms:g9e,unexpected_error_try_again:y9e,unlink:b9e,unverified_email:v9e,update_email:w9e,user_account_does_not_exist:k9e,user_not_found:$9e,user_not_found_body:x9e,user_not_found_cta:S9e,validate_code:z9e,validate_email_body:A9e,validate_email_title:E9e,verify_email_click_to_verify:C9e,verify_email_subject:I9e,verify_email_title:j9e,verify_email_verify:N9e,verify_your_email:T9e,welcome:P9e,welcome_to_your_account:O9e,we_sent_a_code_to:R9e,yes_continue:L9e,yes_continue_with:D9e,yes_continue_with_existing_account:U9e},M9e="Konto opdaget",q9e="Administrer dine kontooplysninger",F9e="Konto",H9e="Vi har opdaget, at du allerede har oprettet en konto gennem",V9e="Når du logger ind, accepterer du vores",K9e="og",G9e="e-mail-adresse",W9e="e-mail eller telefonnummer",J9e="Telefonnummer",Z9e="Uoverensstemmelse mellem URL og tilbagekald",X9e="Den angivne redirect_uri er ikke på listen over tilladte tilbagekalds-URL'er.",Y9e="Ændre e-mailadresse",Q9e="Fortsæt med brugeren",eAe="Klik på knappen for at oprette en ny adgangskodekonto.",tAe="Indtast koden på {{vendorName}} for at gennemføre login.",nAe="Velkommen til {{vendorName}}! {{code}} er login-koden",rAe="Velkommen til {{vendorName}}! {{code}} er login-koden",iAe="Koden er udløbet",oAe="Ugyldig kode",sAe="Tjek venligst <0>{{username}}</0> og indtast den sekscifrede kode, som vi har sendt til dig.",aAe="Koden er allerede brugt",cAe="Koden er gyldig i 30 minutter",lAe="Der opstod en konfigurationsfejl.",uAe="Bekræft adgangskode",dAe="Er du sikker på, at du vil fjerne forbindelsen til denne konto?",pAe="Har du brug for hjælp?",fAe="Kontakt os",hAe="eller fortsæt med social konto",_Ae="Fortsæt med {{provider}}",mAe="Vil du gerne fortsætte med din eksisterende konto?",gAe="Ophavsret © 2023 SESAMY. Alle rettigheder forbeholdes.",yAe="©2023 Sesamy",bAe="Vælg en adgangskode med en blanding af store og små bogstaver, tal og symboler.",vAe="Indtast venligst en gyldig e-mailadresse.",wAe="Adgangskoderne stemte ikke overens. Prøv igen.",kAe="Vælg adgangskode",$Ae="Adgangskoden skal være mindst 8 tegn lang og indeholde mindst et lille bogstav, et stort bogstav, et tal og et symbol.",xAe="Tilmeld dig",SAe="Tilmeld dig med adgangskode",zAe="Har du ikke en konto?",AAe="Nuværende e-mailadresse",EAe="Du er i øjeblikket logget ind som <0>{{email}}</0>",CAe="Rediger",IAe="E-mail",jAe="E-mailen er allerede optaget",NAe="E-mail ændret til <0>{{email}}</0> ",TAe="E-mail eller telefonnummer",PAe="E-mail-adresse",OAe="Din e-mailadresse er blevet valideret",RAe="Indtast nu din adgangskode for at logge ind igen",LAe="Der er sendt en e-mail til <0>{{email}}</0> med et bekræftelseslink. Klik på linket for at bekræfte din e-mailadresse og angive en adgangskode.",DAe="E-mail-bekræftelse sendt",UAe="Skal man blive ved med at logge ind?",BAe="Du er i øjeblikket inde på {{browserName}}. Denne browser logger dig ofte ud, så vi anbefaler, at du bruger din telefons standardbrowser i stedet.",MAe="Indtast en kode",qAe="Vi sender dig et bekræftelseslink for at sikre, at du ejer denne e-mailadresse.",FAe="Indtast ny e-mail",HAe="Indtast ny adgangskode",VAe="Indtast adgangskode",KAe="Indtast din e-mailadresse og adgangskode for at logge ind.",GAe="Indtast din adgangskode",WAe="Noget gik galt",JAe="Det magiske link er udløbet. Klik på knappen nedenfor for at modtage et nyt link i din indbakke.",ZAe="Hej! Vi har opdateret vores login-oplevelse. <0>Klik her for at lære mere om det.</0>",XAe="Send e-mail til nulstilling af adgangskode",YAe="Klik på knappen nedenfor, så sender vi instruktioner om, hvordan du nulstiller din adgangskode.",QAe="E-mail til nulstilling af adgangskode sendt",eEe="Har du glemt din adgangskode?",tEe="Har du glemt din adgangskode?",nEe="Gå tilbage",rEe="Skjul adgangskode",iEe="Inkognitotilstand opdaget",oEe="Du er i inkognito/privat tilstand. Sessionsdata fortsætter muligvis ikke på tværs af sideopdateringer. Nogle funktioner fungerer måske ikke som forventet.",sEe="Ugyldig identifikator",aEe="Ugyldig adgangskode",cEe="Linket er ikke længere gyldigt. Sørg for at åbne login-linket i den samme browser, som du startede login med. Du kan klikke på linket nedenfor for at starte et nyt login.",lEe="Ugyldigt link",uEe="Koblede konti",dEe="Klik på knappen for at logge ind",pEe="Login",fEe="Eller indtast koden på {{vendorName}} for at gennemføre login.",hEe="Indtast din e-mailadresse for at låse op for dette show på {{service}}",_Ee="Forbind din konto med {{service}}",mEe="Du er logget ind som",gEe="Login",yEe="Indtast din e-mailadresse for at logge ind.",bEe="Indtast din e-mailadresse, så sender vi dig en login-kode.",vEe="Indtast din e-mail eller dit telefonnummer for at logge ind",wEe="Indtast din e-mailadresse, så sender vi dig et login-link.",kEe="Indtast dit telefonnummer for at logge ind",$Ee="Indtast din {{authMethod}} for at logge ind.",xEe="Log ud",SEe="Ny emailadresse",zEe="En engangskode vil blive sendt til din nye e-mailadresse, indtast koden i næste trin.",AEe="Ingen e-mailadresse er angivet",EEe="Nej, jeg vil bruge en anden konto",CEe="eller",IEe="Adgangskode",jEe="Adgangskoden indeholder et forbudt ord",NEe="Adgangskoden må ikke indeholde personlige oplysninger som dit navn eller e-mail",TEe="Adgangskoden er blevet nulstillet",PEe="Succes",OEe="Adgangskoden skal indeholde mindst ét lille bogstav",REe="Adgangskoden skal indeholde mindst ét tal",LEe="Adgangskoden skal indeholde mindst ét specialtegn",DEe="Adgangskoden skal indeholde mindst ét stort bogstav",UEe="Koden blev ikke fundet eller er udløbet",BEe="Adgangskoden kunne ikke nulstilles",MEe="Adgangskoden er blevet brugt for nylig og kan ikke genbruges",qEe="Adgangskoden skal være mindst {{minLength}} tegn",FEe="Skift adgangskode til din {{vendorName}} konto",HEe="Skift adgangskode til din {{vendorName}} -konto",VEe="Telefonnummer",KEe="Politik for beskyttelse af personlige oplysninger",GEe="Omdirigering",WEe="Bekræft adgangskode",JEe="Registrer en ny adgangskode",ZEe="Send koden igen",XEe="Skift adgangskode",YEe="Indtast din nye adgangskode til e-mailkontoen nedenfor: ",QEe="Klik på knappen for at nulstille din adgangskode",e7e="Klik på knappen for at nulstille din adgangskode",t7e="Nulstil din adgangskode",n7e="Skift adgangskode til din {{vendorName}} -konto",r7e="Nulstil adgangskode",i7e="Send",o7e="Send mig et nyt magisk link",s7e="Husk at tjekke din spam-mappe, hvis e-mailen ikke er kommet frem.",a7e="Indstil adgangskode",c7e="Vis adgangskode",l7e="Log ind",u7e="Tilmelding",d7e="Tilmeld dig med succes",p7e="{{code}} er din login-kode til {{vendorName}}",f7e="Det ser ud til, at din Spotify-konto i øjeblikket er knyttet til en anden Sesamy-konto. Men frygt ikke, vi er her for at guide dig gennem processen med at få det løst.",h7e="Gå til Spotifys side for adgang til indhold",_7e='Lad os starte med at fjerne forbindelsen til din Spotify-konto. Klik på knappen nedenfor for at gå til Spotifys Content Access-side. Når du har logget ind på din Spotify-konto, skal du finde Sesamy på listen over tilsluttede platforme. Klik på "Unlink" ved siden af Sesamy-logoet.',m7e="Trin 1: Fjern forbindelsen til din Spotify-konto",g7e="Når du har afkoblet din Spotify-konto, kan du koble den til Sesamy igen. Du skal blot gentage de trin, du tidligere har taget, og som førte dig til denne side.",y7e="Trin 2: Relink din Spotify-konto til Sesamy",b7e="Ups! Din Spotify-konto er allerede forbundet",v7e="Færdig",w7e="Hvis du har spørgsmål eller brug for hjælp, kan du kontakte vores supportteam",k7e="Vilkår og betingelser",$7e="Noget gik galt. Prøv venligst igen.",x7e="Frakobl",S7e="Din e-mailadresse skal valideres. Vi har sendt en ny e-mail til din indbakke",z7e="Opdatering af e-mail",A7e="Brugerkontoen findes ikke",E7e="Brugerkontoen findes ikke",C7e="Vi kunne ikke finde en bruger med den angivne e-mailadresse. Prøv venligst igen.",I7e="Prøv igen.",j7e="Valider koden",N7e="Tjek din indbakke for instruktioner om validering af e-mail.",T7e="Tilmeldte sig",P7e="Klik på knappen for at bekræfte din e-mailadresse",O7e="Bekræft din e-mailadresse",R7e="Bekræft din e-mailadresse",L7e="Bekræft konto",D7e="Bekræft din e-mail",U7e="Velkommen",B7e="Velkommen til din {{vendorName}} konto!",M7e="Tjek venligst din e-mail på <0>{{email}}</0> og indtast den sekscifrede kode, vi har sendt dig.",q7e="Fortsæt med denne konto",F7e="Ja, fortsæt med {{text}}",H7e="Ja, fortsæt med eksisterende konto",V7e={account_detected:M9e,account_page_description:q9e,account_title:F9e,account_with_sso_provider:H9e,agree_to:V9e,and:K9e,auth_method_email:G9e,auth_method_email_or_phone:W9e,auth_method_phone:J9e,callback_url_mismatch:Z9e,callback_url_not_allowed:X9e,change_email:Y9e,check_email_title:Q9e,click_to_sign_up_description:eAe,code_email_enter_code:tAe,code_email_subject:nAe,code_email_title:rAe,code_expired:iAe,code_invalid:oAe,code_sent_template:sAe,code_used:aAe,code_valid_30_minutes:cAe,configuration_error_message:lAe,confirm_password:uAe,confirm_unlink:dAe,contact_support:pAe,contact_us:fAe,continue:"Fortsæt",continue_social_login:hAe,continue_with:_Ae,continue_with_sso_provider_headline:mAe,copyright:gAe,copyright_sesamy:yAe,create_account_description:bAe,create_account_email_invalid:vAe,create_account_passwords_didnt_match:wAe,create_account_title:kAe,create_account_weak_password:$Ae,create_new_account_link:xAe,create_password_account_title:SAe,dont_have_account:zAe,current_email:AAe,currently_logged_in_as:EAe,edit:CAe,email:IAe,email_already_taken:jAe,email_changed_to_template:NAe,email_or_phone_placeholder:TAe,email_placeholder:PAe,email_validated:OAe,email_validated_cta:RAe,email_verification_for_signup_sent_description:LAe,email_verification_for_signup_sent_title:DAe,embedded_browser_detected:UAe,embedded_browser_warning:BAe,enter_a_code_btn:MAe,enter_email_for_verification_description:qAe,enter_new_email:FAe,enter_new_password_placeholder:HAe,enter_password:VAe,enter_password_description:KAe,enter_your_password_btn:GAe,error_page_title:WAe,expired_code:JAe,fokus_info_message:ZAe,forgot_password_cta:XAe,forgot_password_description:YAe,forgot_password_email_sent:QAe,forgot_password_link:eEe,forgot_password_title:tEe,go_back:nEe,hide_password:rEe,incognito_mode_detected:iEe,incognito_mode_warning:oEe,"invalid-email":"Ugyldig e-mail",invalid_identifier:sEe,invalid_password:aEe,invalid_session_body:cEe,invalid_session_title:lEe,linked_accounts:uEe,link_email_click_to_login:dEe,link_email_login:pEe,link_email_or_enter_code:fEe,link_page_body:hEe,link_page_headline:_Ee,logged_in_as:mEe,login:gEe,login_description:yEe,login_description_code:bEe,login_description_combined:vEe,login_description_link:wEe,login_description_phone:kEe,login_description_template:$Ee,logout:xEe,new_email:SEe,new_email_code_info:zEe,no_email_address:AEe,no_use_another:EEe,or:CEe,password:IEe,password_contains_forbidden_word:jEe,password_contains_personal_info:NEe,password_has_been_reset:TEe,password_has_been_reset_title:PEe,password_missing_lowercase:OEe,password_missing_number:REe,password_missing_special:LEe,password_missing_uppercase:DEe,password_reset_code_expired:UEe,password_reset_failed:BEe,password_reused:MEe,password_too_short:qEe,password_reset_subject:FEe,password_reset_title:HEe,phone_placeholder:VEe,privacy_policy:KEe,redirecting:GEe,reenter_new_password_placeholder:WEe,register_password_account:JEe,resend_code:ZEe,reset_password_cta:XEe,reset_password_description:YEe,reset_password_email_click_to_reset:QEe,reset_password_email_cta:e7e,reset_password_email_reset:t7e,reset_password_subject:n7e,reset_password_title:r7e,send:i7e,send_me_a_new_magic_link:o7e,sent_code_spam:s7e,"Server error: Invalid code":"Ugyldig kode",set_password:a7e,show_password:c7e,sign_in:l7e,signup:u7e,signup_success:d7e,sms_code_text:p7e,spotify_already_linked_body:f7e,spotify_already_linked_cta:h7e,spotify_already_linked_step1_body:_7e,spotify_already_linked_step1_title:m7e,spotify_already_linked_step2_body:g7e,spotify_already_linked_step2_title:y7e,spotify_already_linked_title:b7e,success:v7e,support_info:w7e,terms:k7e,unexpected_error_try_again:$7e,unlink:x7e,unverified_email:S7e,update_email:z7e,user_account_does_not_exist:A7e,user_not_found:E7e,user_not_found_body:C7e,user_not_found_cta:I7e,validate_code:j7e,validate_email_body:N7e,validate_email_title:T7e,verify_email_click_to_verify:P7e,verify_email_subject:O7e,verify_email_title:R7e,verify_email_verify:L7e,verify_your_email:D7e,welcome:U7e,welcome_to_your_account:B7e,we_sent_a_code_to:M7e,yes_continue:q7e,yes_continue_with:F7e,yes_continue_with_existing_account:H7e},K7e="https://assets.sesamy.com/images/login-bg.jpg",G7e=({title:e,children:t,theme:n,branding:r})=>{const i=n?.page_background?.page_layout||"center",s=n?.page_background?.background_color||"#ffffff",a=n?.page_background?.background_image_url,c=a??K7e,l=c?.startsWith("linear-gradient")||c?.startsWith("radial-gradient")||c?.startsWith("conic-gradient"),u=c?l?c:`url(${c})`:void 0;let d="justify-center",f="p-6 md:p-10";i==="left"?(d="justify-start",f="pl-12 pr-6 py-6 md:pl-20 md:pr-10 md:py-10"):i==="right"&&(d="justify-end",f="pr-12 pl-6 py-6 md:pr-20 md:pl-10 md:py-10");const p=Be("min-h-screen w-full flex bg-cover bg-center",d,f),h={...u&&{backgroundImage:u},backgroundColor:s,display:"flex",alignItems:"stretch",justifyContent:i==="left"?"flex-start":i==="right"?"flex-end":"center",minHeight:"100vh",width:"100%"},_=Be("w-full max-w-sm","flex flex-col justify-center");return w("html",{lang:T.language||"en",children:[w("head",{children:[w("title",{children:e}),w("meta",{charset:"UTF-8"}),w("meta",{name:"robots",content:"noindex, follow"}),w("link",{rel:"stylesheet",href:`/u/css/tailwind.css?v=${Po}`}),w("meta",{name:"viewport",content:"width=device-width, initial-scale=1, maximum-scale=1"}),w("meta",{name:"theme-color",content:"#000000"}),r?.favicon_url&&w("link",{rel:"icon",type:"image/x-icon",href:r.favicon_url}),n?.fonts?.font_url&&w("link",{rel:"stylesheet",href:n.fonts.font_url})]}),w("body",{children:[w("div",{className:p,style:h,children:w("div",{className:_,children:[t,r?.powered_by_logo_url&&w("div",{className:"mt-5 text-left",children:w("a",{href:"https://authhero.com",target:"_blank",rel:"noopener noreferrer",className:"inline-block",children:w("img",{src:r.powered_by_logo_url,alt:"Powered by",className:"h-9 opacity-60 hover:opacity-100 transition-opacity"})})})]})}),w("div",{id:"client-root"}),w("script",{type:"module",src:`/u/js/client.js?v=${Po}`})]})]})},G$=({children:e,className:t,style:n})=>w("div",{className:Be("rounded-lg border border-gray-200 bg-white shadow-sm dark:border-gray-700 dark:bg-gray-800",t),style:n,children:e}),W$=({children:e,className:t})=>w("div",{className:Be("flex flex-col space-y-1.5 p-6",t),children:e}),J$=({children:e,className:t,style:n})=>w("h3",{className:Be("text-2xl font-semibold leading-none tracking-tight",t),style:n,children:e}),Z$=({children:e,className:t,style:n})=>w("p",{className:Be("text-sm text-gray-500 dark:text-gray-400",t),style:n,children:e}),X$=({children:e,className:t})=>w("div",{className:Be("p-6 pt-0",t),children:e}),W7e=({children:e,className:t})=>w("div",{className:Be("flex items-center p-6 pt-0",t),children:e}),Y$=({id:e,type:t="text",name:n,placeholder:r,className:i,required:s=!1,value:a,disabled:c=!1,error:l=!1,style:u})=>w("input",{id:e,type:t,name:n,placeholder:r,required:s,value:a,disabled:c,className:Be("flex h-10 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm ring-offset-white transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:ring-offset-gray-900 dark:placeholder:text-gray-400",l&&"border-red-500 focus-visible:ring-red-500",i),style:u}),Q$=({children:e,className:t,variant:n="default",size:r="default",type:i="button",disabled:s=!1,style:a})=>{const c={default:"bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-700 dark:hover:bg-blue-800",outline:"border border-gray-300 bg-transparent hover:bg-gray-100 dark:border-gray-600 dark:hover:bg-gray-800",ghost:"hover:bg-gray-100 dark:hover:bg-gray-800"},l={default:"h-10 px-4 py-2",sm:"h-9 px-3 text-sm",lg:"h-11 px-8"};return w("button",{type:i,disabled:s,className:Be("inline-flex items-center justify-center gap-2 rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 disabled:pointer-events-none disabled:opacity-50",c[n],l[r],t),style:a,children:e})},ex=({htmlFor:e,className:t,style:n,children:r})=>w("label",{for:e,className:Be("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",t),style:n,children:r}),J7e=({error:e,theme:t,branding:n,loginSession:r,email:i,client:s,className:a,isEmbedded:c,browserName:l})=>{const u=s.connections.map(({strategy:ce})=>ce),d=u.includes("email")||u.includes("Username-Password-Authentication"),f=u.includes("sms"),p=new Set(["email","sms","Username-Password-Authentication","auth0"]),h=s.connections.filter(ce=>!p.has(ce.strategy)).filter(ce=>ce.show_as_button!==!1).map(ce=>{const ut=Cu[ce.strategy];return ut?{...ut,connectionName:ce.name,displayName:ce.display_name||ut.displayName||ce.name,iconUrl:ce.options.icon_url}:null}).filter(ce=>ce!==null).filter(ce=>!(c&&ce.disableEmbeddedBrowsers)),_=d||f,g=d&&f?"email_or_phone_placeholder":d?"email_placeholder":f?"phone_placeholder":null,y=g?T.t(g,d&&f?"Email or Phone Number":d?"Email Address":"Phone Number"):"",m=t?.colors?.primary_button||n?.colors?.primary||"#0066cc",v=t?.colors?.primary_button_label||"#ffffff",k=t?.colors?.body_text||"#333333",x=t?.colors?.input_background||"#ffffff",b=t?.colors?.input_border||"#d1d5db",S=t?.colors?.input_filled_text||"#111827",A=t?.colors?.error||"#dc2626",C=t?.colors?.widget_background||"#ffffff",P=t?.colors?.widget_border||"#e5e7eb",R=t?.borders?.widget_corner_radius||8,E=t?.borders?.input_border_radius||4,L=t?.borders?.button_border_radius||4,M=t?.borders?.show_widget_shadow??!0,H=t?.fonts?.title?.size||24,D=t?.fonts?.title?.bold??!0,Q=t?.fonts?.body_text?.size||14,pe={backgroundColor:C,borderColor:P,borderRadius:`${R}px`,boxShadow:M?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:k},se={fontSize:`${H}px`,fontWeight:D?"700":"400",color:t?.colors?.header||k},we={fontSize:`${Q}px`,color:t?.colors?.input_labels_placeholders||"#6b7280"},le={backgroundColor:x,borderColor:e?A:b,borderRadius:`${E}px`,color:S},be={backgroundColor:m,color:v,borderRadius:`${L}px`},Ee=t?.widget?.logo_position||"center",V=Ee==="left"?"text-left":Ee==="right"?"text-right":"text-center",Te=t?.widget?.logo_url||n?.logo_url,$t=Ee!=="none"&&Te;return w("div",{className:Be("flex flex-col gap-6 w-full max-w-sm",a),children:[w("div",{id:"incognito-warning-container",className:"mb-4 hidden rounded-md border border-yellow-200 bg-yellow-50 p-4 text-sm text-yellow-800 dark:border-yellow-900 dark:bg-yellow-900/20 dark:text-yellow-100",role:"alert",children:w("div",{className:"flex items-start gap-3",children:[w("span",{className:"text-lg leading-none",children:"⚠️"}),w("div",{children:[w("strong",{children:T.t("incognito_mode_detected")}),w("p",{className:"mt-1 text-xs opacity-90",children:T.t("incognito_mode_warning")})]})]})}),c&&w("div",{className:"mb-4 rounded-md border border-orange-200 bg-orange-50 p-4 text-sm text-orange-800 dark:border-orange-900 dark:bg-orange-900/20 dark:text-orange-100",role:"alert",children:w("div",{className:"flex items-start gap-3",children:[w("span",{className:"text-lg leading-none",children:"⚠️"}),w("div",{children:[w("strong",{children:T.t("embedded_browser_detected")}),w("p",{className:"mt-1 text-xs opacity-90",children:T.t("embedded_browser_warning",{browserName:l||"the app"})})]})]})}),w(G$,{style:pe,className:"border",children:[w(W$,{children:[$t&&w("div",{className:Be("mb-4",V),children:w(F_,{theme:t,branding:n})}),w(J$,{style:se,children:T.t("welcome","Login")}),w(Z$,{style:we,children:_?T.t("login_description_template",{authMethod:T.t(g,{defaultValue:d&&f?"email or phone number":d?"email address":"phone number"}).toLocaleLowerCase(),defaultValue:"Enter your {{authMethod}} below to login to your account"}):T.t("login_description_social_only","Choose how to login")})]}),w(X$,{children:w("form",{method:"post",children:w("div",{className:"grid gap-6",children:[_&&w(To,{children:[w("div",{className:"grid gap-2",children:[w(ex,{htmlFor:"username",style:we,children:T.t(g,d&&f?"Email or Phone Number":d?"Email":"Phone Number")}),w(Y$,{id:"username",name:"username",type:"text",placeholder:y,required:!0,value:i||"",error:!!e,className:"border lowercase",style:le}),e&&w(Jt,{children:e})]}),w(Q$,{type:"submit",className:"w-full transition-colors hover:brightness-90",style:be,children:T.t("continue","Continue")})]}),h.length>0&&w(To,{children:[_&&w("div",{className:"relative text-center",style:{color:t?.colors?.input_labels_placeholders||"#6b7280",fontSize:`${Q}px`},children:[w("div",{className:"absolute left-0 right-0 top-1/2 border-b",style:{borderColor:P}}),w("div",{className:"relative inline-block px-2",style:{backgroundColor:C},children:T.t("or","Or")})]}),w("div",{className:"flex gap-4 sm:flex-col short:flex-row",children:h.map(ce=>{const ut=ce.iconUrl||ce.logoDataUri;return w("a",{href:`/authorize/redirect?state=${r.id}&connection=${ce.connectionName}`,className:"inline-flex items-center justify-center gap-2 rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 disabled:pointer-events-none disabled:opacity-50 border bg-transparent hover:bg-gray-100 dark:hover:bg-gray-800 h-10 px-4 py-2 w-full sm:w-full short:flex-1",style:{borderColor:b,borderRadius:`${L}px`,color:k},children:[ut&&w("img",{src:ut,alt:ce.displayName,className:"h-5 w-5"}),w("span",{className:"sm:inline short:hidden",children:T.t("continue_with","Login with {{provider}}",{provider:ce.displayName})}),w("span",{className:"hidden short:inline",children:ce.displayName})]},ce.connectionName)})})]})]})})})]})]})},Z7e=({...e})=>w("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",...e,children:[w("path",{d:"M44.1035 23.0123C44.1054 21.4791 43.9758 19.9486 43.716 18.4375H22.498V27.1028H34.6507C34.4021 28.4868 33.8757 29.8061 33.1034 30.9812C32.3311 32.1562 31.3289 33.1628 30.1571 33.9401V39.5649H37.41C41.6567 35.6494 44.1035 29.859 44.1035 23.0123Z",fill:"#4285F4"}),w("path",{d:"M22.4982 44.9997C28.5698 44.9997 33.6821 43.0061 37.4101 39.5687L30.1573 33.9439C28.1386 35.3126 25.5387 36.0938 22.4982 36.0938C16.6296 36.0938 11.6485 32.1377 9.86736 26.8066H2.39575V32.6033C4.26839 36.3297 7.13989 39.4622 10.6896 41.6512C14.2394 43.8402 18.3277 44.9995 22.4982 44.9997Z",fill:"#34A853"}),w("path",{d:"M9.86737 26.8073C8.92572 24.0138 8.92572 20.9886 9.86737 18.1951V12.3984H2.39576C0.820432 15.5332 0 18.9929 0 22.5012C0 26.0095 0.820432 29.4692 2.39576 32.604L9.86737 26.8073Z",fill:"#FBBC04"}),w("path",{d:"M22.4982 8.90741C25.7068 8.85499 28.8071 10.0673 31.1291 12.2823L37.5507 5.86064C33.4788 2.03602 28.0843 -0.0637686 22.4982 0.00147616C18.3277 0.00166623 14.2394 1.16098 10.6896 3.34999C7.13989 5.539 4.26839 8.67155 2.39575 12.3979L9.86736 18.1946C11.6485 12.8635 16.6296 8.90741 22.4982 8.90741Z",fill:"#EA4335"})]}),X7e=e=>{const{theme:t,branding:n,client:r,authParams:i}=e,a=`/authorize?${new URLSearchParams(Object.entries(i).filter(([,c])=>c!==void 0).map(([c,l])=>[c,String(l)]))}`;return w(Ve,{theme:t,branding:n,client:r,title:T.t("user_not_found"),children:w("div",{className:"flex flex-1 flex-col justify-center",children:[w("p",{className:"mb-8 text-gray-300 text-lg",children:T.t("user_not_found_body")}),w(Fe,{Component:"a",href:a,children:T.t("user_not_found_cta")})]})})},Y7e=({...e})=>w("svg",{version:"1.1",id:"Layer_1",xmlns:"http://www.w3.org/2000/svg",x:"0px",y:"0px",viewBox:"0 0 48 48",enableBackground:"new 0 0 48 48",width:"45",height:"45",...e,children:[w("path",{fill:"#FF5B24",d:"M3.5,8h41c1.9,0,3.5,1.6,3.5,3.5v25c0,1.9-1.6,3.5-3.5,3.5h-41C1.6,40,0,38.4,0,36.5v-25C0,9.6,1.6,8,3.5,8z"}),w("path",{fillRule:"evenodd",clipRule:"evenodd",fill:"#FFFFFF",d:`M27.9,20.3c1.4,0,2.6-1,2.6-2.5h0c0-1.5-1.2-2.5-2.6-2.5c-1.4,0-2.6,1-2.6,2.5C25.3,19.2,26.5,20.3,27.9,20.3z
|
|
441
441
|
M31.2,24.4c-1.7,2.2-3.5,3.8-6.7,3.8h0c-3.2,0-5.8-2-7.7-4.8c-0.8-1.2-2-1.4-2.9-0.8c-0.8,0.6-1,1.8-0.3,2.9
|
|
442
442
|
c2.7,4.1,6.5,6.6,10.9,6.6c4,0,7.2-2,9.6-5.2c0.9-1.2,0.9-2.5,0-3.1C33.3,22.9,32.1,23.2,31.2,24.4z`})]});async function Q7e(e,t){const{tenantId:n,userId:r}=t,{data:i}=e.env;i.sessionCleanup&&await i.sessionCleanup({tenant_id:n,user_id:r})}const Ns=[{description:"Read Client Grants",value:"read:client_grants"},{description:"Create Client Grants",value:"create:client_grants"},{description:"Delete Client Grants",value:"delete:client_grants"},{description:"Update Client Grants",value:"update:client_grants"},{description:"Read Users",value:"read:users"},{description:"Update Users",value:"update:users"},{description:"Delete Users",value:"delete:users"},{description:"Create Users",value:"create:users"},{description:"Read Users App Metadata",value:"read:users_app_metadata"},{description:"Update Users App Metadata",value:"update:users_app_metadata"},{description:"Delete Users App Metadata",value:"delete:users_app_metadata"},{description:"Create Users App Metadata",value:"create:users_app_metadata"},{description:"Read Custom User Blocks",value:"read:user_custom_blocks"},{description:"Create Custom User Blocks",value:"create:user_custom_blocks"},{description:"Delete Custom User Blocks",value:"delete:user_custom_blocks"},{description:"Create User Tickets",value:"create:user_tickets"},{description:"Read Clients",value:"read:clients"},{description:"Update Clients",value:"update:clients"},{description:"Delete Clients",value:"delete:clients"},{description:"Create Clients",value:"create:clients"},{description:"Read Client Keys",value:"read:client_keys"},{description:"Update Client Keys",value:"update:client_keys"},{description:"Delete Client Keys",value:"delete:client_keys"},{description:"Create Client Keys",value:"create:client_keys"},{description:"Read Client Credentials",value:"read:client_credentials"},{description:"Update Client Credentials",value:"update:client_credentials"},{description:"Delete Client Credentials",value:"delete:client_credentials"},{description:"Create Client Credentials",value:"create:client_credentials"},{description:"Read Connections",value:"read:connections"},{description:"Update Connections",value:"update:connections"},{description:"Delete Connections",value:"delete:connections"},{description:"Create Connections",value:"create:connections"},{description:"Read Resource Servers",value:"read:resource_servers"},{description:"Update Resource Servers",value:"update:resource_servers"},{description:"Delete Resource Servers",value:"delete:resource_servers"},{description:"Create Resource Servers",value:"create:resource_servers"},{description:"Read Device Credentials",value:"read:device_credentials"},{description:"Update Device Credentials",value:"update:device_credentials"},{description:"Delete Device Credentials",value:"delete:device_credentials"},{description:"Create Device Credentials",value:"create:device_credentials"},{description:"Read Rules",value:"read:rules"},{description:"Update Rules",value:"update:rules"},{description:"Delete Rules",value:"delete:rules"},{description:"Create Rules",value:"create:rules"},{description:"Read Rules Configs",value:"read:rules_configs"},{description:"Update Rules Configs",value:"update:rules_configs"},{description:"Delete Rules Configs",value:"delete:rules_configs"},{description:"Read Hooks",value:"read:hooks"},{description:"Update Hooks",value:"update:hooks"},{description:"Delete Hooks",value:"delete:hooks"},{description:"Create Hooks",value:"create:hooks"},{description:"Read Actions",value:"read:actions"},{description:"Update Actions",value:"update:actions"},{description:"Delete Actions",value:"delete:actions"},{description:"Create Actions",value:"create:actions"},{description:"Read Email Provider",value:"read:email_provider"},{description:"Update Email Provider",value:"update:email_provider"},{description:"Delete Email Provider",value:"delete:email_provider"},{description:"Create Email Provider",value:"create:email_provider"},{description:"Blacklist Tokens",value:"blacklist:tokens"},{description:"Read Stats",value:"read:stats"},{description:"Read Insights",value:"read:insights"},{description:"Read Tenant Settings",value:"read:tenant_settings"},{description:"Update Tenant Settings",value:"update:tenant_settings"},{description:"Read Logs",value:"read:logs"},{description:"Read logs relating to users",value:"read:logs_users"},{description:"Read Shields",value:"read:shields"},{description:"Create Shields",value:"create:shields"},{description:"Update Shields",value:"update:shields"},{description:"Delete Shields",value:"delete:shields"},{description:"Read Anomaly Detection Blocks",value:"read:anomaly_blocks"},{description:"Delete Anomaly Detection Blocks",value:"delete:anomaly_blocks"},{description:"Update Triggers",value:"update:triggers"},{description:"Read Triggers",value:"read:triggers"},{description:"Read User Grants",value:"read:grants"},{description:"Delete User Grants",value:"delete:grants"},{description:"Read Guardian factors configuration",value:"read:guardian_factors"},{description:"Update Guardian factors",value:"update:guardian_factors"},{description:"Read Guardian enrollments",value:"read:guardian_enrollments"},{description:"Delete Guardian enrollments",value:"delete:guardian_enrollments"},{description:"Create enrollment tickets for Guardian",value:"create:guardian_enrollment_tickets"},{description:"Read Users IDP tokens",value:"read:user_idp_tokens"},{description:"Create password checking jobs",value:"create:passwords_checking_job"},{description:"Deletes password checking job and all its resources",value:"delete:passwords_checking_job"},{description:"Read custom domains configurations",value:"read:custom_domains"},{description:"Delete custom domains configurations",value:"delete:custom_domains"},{description:"Configure new custom domains",value:"create:custom_domains"},{description:"Update custom domain configurations",value:"update:custom_domains"},{description:"Read email templates",value:"read:email_templates"},{description:"Create email templates",value:"create:email_templates"},{description:"Update email templates",value:"update:email_templates"},{description:"Read Multifactor Authentication policies",value:"read:mfa_policies"},{description:"Update Multifactor Authentication policies",value:"update:mfa_policies"},{description:"Read roles",value:"read:roles"},{description:"Create roles",value:"create:roles"},{description:"Delete roles",value:"delete:roles"},{description:"Update roles",value:"update:roles"},{description:"Read prompts settings",value:"read:prompts"},{description:"Update prompts settings",value:"update:prompts"},{description:"Read branding settings",value:"read:branding"},{description:"Update branding settings",value:"update:branding"},{description:"Delete branding settings",value:"delete:branding"},{description:"Read log_streams",value:"read:log_streams"},{description:"Create log_streams",value:"create:log_streams"},{description:"Delete log_streams",value:"delete:log_streams"},{description:"Update log_streams",value:"update:log_streams"},{description:"Create signing keys",value:"create:signing_keys"},{description:"Read signing keys",value:"read:signing_keys"},{description:"Update signing keys",value:"update:signing_keys"},{description:"Read entity limits",value:"read:limits"},{description:"Update entity limits",value:"update:limits"},{description:"Create role members",value:"create:role_members"},{description:"Read role members",value:"read:role_members"},{description:"Update role members",value:"delete:role_members"},{description:"Read entitlements",value:"read:entitlements"},{description:"Read attack protection",value:"read:attack_protection"},{description:"Update attack protection",value:"update:attack_protection"},{description:"Read organization summary",value:"read:organizations_summary"},{description:"Create Authentication Methods",value:"create:authentication_methods"},{description:"Read Authentication Methods",value:"read:authentication_methods"},{description:"Update Authentication Methods",value:"update:authentication_methods"},{description:"Delete Authentication Methods",value:"delete:authentication_methods"},{description:"Read Organizations",value:"read:organizations"},{description:"Update Organizations",value:"update:organizations"},{description:"Create Organizations",value:"create:organizations"},{description:"Delete Organizations",value:"delete:organizations"},{description:"Administer Organizations",value:"admin:organizations"},{description:"Read Organization Discovery Domains",value:"read:organization_discovery_domains"},{description:"Update Organization Discovery Domains",value:"update:organization_discovery_domains"},{description:"Create Organization Discovery Domains",value:"create:organization_discovery_domains"},{description:"Delete Organization Discovery Domains",value:"delete:organization_discovery_domains"},{description:"Create organization members",value:"create:organization_members"},{description:"Read organization members",value:"read:organization_members"},{description:"Delete organization members",value:"delete:organization_members"},{description:"Create organization connections",value:"create:organization_connections"},{description:"Read organization connections",value:"read:organization_connections"},{description:"Update organization connections",value:"update:organization_connections"},{description:"Delete organization connections",value:"delete:organization_connections"},{description:"Create organization member roles",value:"create:organization_member_roles"},{description:"Read organization member roles",value:"read:organization_member_roles"},{description:"Delete organization member roles",value:"delete:organization_member_roles"},{description:"Create organization invitations",value:"create:organization_invitations"},{description:"Read organization invitations",value:"read:organization_invitations"},{description:"Delete organization invitations",value:"delete:organization_invitations"},{description:"Read SCIM configuration",value:"read:scim_config"},{description:"Create SCIM configuration",value:"create:scim_config"},{description:"Update SCIM configuration",value:"update:scim_config"},{description:"Delete SCIM configuration",value:"delete:scim_config"},{description:"Create SCIM token",value:"create:scim_token"},{description:"Read SCIM token",value:"read:scim_token"},{description:"Delete SCIM token",value:"delete:scim_token"},{description:"Delete a Phone Notification Provider",value:"delete:phone_providers"},{description:"Create a Phone Notification Provider",value:"create:phone_providers"},{description:"Read a Phone Notification Provider",value:"read:phone_providers"},{description:"Update a Phone Notification Provider",value:"update:phone_providers"},{description:"Delete a Phone Notification Template",value:"delete:phone_templates"},{description:"Create a Phone Notification Template",value:"create:phone_templates"},{description:"Read a Phone Notification Template",value:"read:phone_templates"},{description:"Update a Phone Notification Template",value:"update:phone_templates"},{description:"Create encryption keys",value:"create:encryption_keys"},{description:"Read encryption keys",value:"read:encryption_keys"},{description:"Update encryption keys",value:"update:encryption_keys"},{description:"Delete encryption keys",value:"delete:encryption_keys"},{description:"Read Sessions",value:"read:sessions"},{description:"Update Sessions",value:"update:sessions"},{description:"Delete Sessions",value:"delete:sessions"},{description:"Read Refresh Tokens",value:"read:refresh_tokens"},{description:"Update Refresh Tokens",value:"update:refresh_tokens"},{description:"Delete Refresh Tokens",value:"delete:refresh_tokens"},{description:"Create Self Service Profiles",value:"create:self_service_profiles"},{description:"Read Self Service Profiles",value:"read:self_service_profiles"},{description:"Update Self Service Profiles",value:"update:self_service_profiles"},{description:"Delete Self Service Profiles",value:"delete:self_service_profiles"},{description:"Create SSO Access Tickets",value:"create:sso_access_tickets"},{description:"Delete SSO Access Tickets",value:"delete:sso_access_tickets"},{description:"Read Forms",value:"read:forms"},{description:"Update Forms",value:"update:forms"},{description:"Delete Forms",value:"delete:forms"},{description:"Create Forms",value:"create:forms"},{description:"Read Flows",value:"read:flows"},{description:"Update Flows",value:"update:flows"},{description:"Delete Flows",value:"delete:flows"},{description:"Create Flows",value:"create:flows"},{description:"Read Flows Vault items",value:"read:flows_vault"},{description:"Read Flows Vault connections",value:"read:flows_vault_connections"},{description:"Update Flows Vault connections",value:"update:flows_vault_connections"},{description:"Delete Flows Vault connections",value:"delete:flows_vault_connections"},{description:"Create Flows Vault connections",value:"create:flows_vault_connections"},{description:"Read Flows Executions",value:"read:flows_executions"},{description:"Delete Flows Executions",value:"delete:flows_executions"},{description:"Read Connections Options",value:"read:connections_options"},{description:"Update Connections Options",value:"update:connections_options"},{description:"Read Self Service Profile Custom Texts",value:"read:self_service_profile_custom_texts"},{description:"Update Self Service Profile Custom Texts",value:"update:self_service_profile_custom_texts"},{description:"Create Network ACLs",value:"create:network_acls"},{description:"Update Network ACLs",value:"update:network_acls"},{description:"Read Network ACLs",value:"read:network_acls"},{description:"Delete Network ACLs",value:"delete:network_acls"},{description:"Delete Verifiable Digital Credential Templates",value:"delete:vdcs_templates"},{description:"Read Verifiable Digital Credential Templates",value:"read:vdcs_templates"},{description:"Create Verifiable Digital Credential Templates",value:"create:vdcs_templates"},{description:"Update Verifiable Digital Credential Templates",value:"update:vdcs_templates"},{description:"Create Customer Provided Public Signing Keys",value:"create:custom_signing_keys"},{description:"Read Customer Provided Public Signing Keys",value:"read:custom_signing_keys"},{description:"Update Customer Provided Public Signing Keys",value:"update:custom_signing_keys"},{description:"Delete Customer Provided Public Signing Keys",value:"delete:custom_signing_keys"},{description:"List Federated Connections Tokensets belonging to a user",value:"read:federated_connections_tokens"},{description:"Delete Federated Connections Tokensets belonging to a user",value:"delete:federated_connections_tokens"},{description:"Create User Attribute Profiles",value:"create:user_attribute_profiles"},{description:"Read User Attribute Profiles",value:"read:user_attribute_profiles"},{description:"Update User Attribute Profiles",value:"update:user_attribute_profiles"},{description:"Delete User Attribute Profiles",value:"delete:user_attribute_profiles"},{description:"Read event streams",value:"read:event_streams"},{description:"Create event streams",value:"create:event_streams"},{description:"Delete event streams",value:"delete:event_streams"},{description:"Update event streams",value:"update:event_streams"},{description:"Read event stream deliveries",value:"read:event_deliveries"},{description:"Redeliver event(s) to an event stream",value:"update:event_deliveries"},{description:"Create Connection Profiles",value:"create:connection_profiles"},{description:"Read Connection Profiles",value:"read:connection_profiles"},{description:"Update Connection Profiles",value:"update:connection_profiles"},{description:"Delete Connection Profiles",value:"delete:connection_profiles"},{description:"Read Organization Client Grants",value:"read:organization_client_grants"},{description:"Create Organization Client Grants",value:"create:organization_client_grants"},{description:"Delete Organization Client Grants",value:"delete:organization_client_grants"},{description:"Create Token Exchange Profile",value:"create:token_exchange_profiles"},{description:"Read Token Exchange Profiles",value:"read:token_exchange_profiles"},{description:"Update Token Exchange Profile",value:"update:token_exchange_profiles"},{description:"Delete Token Exchange Profile",value:"delete:token_exchange_profiles"},{description:"Read connection keys",value:"read:connections_keys"},{description:"Update connection keys",value:"update:connections_keys"},{description:"Create connection keys",value:"create:connections_keys"},{description:"Read Tenants",value:"read:tenants"},{description:"Create Tenants",value:"create:tenants"},{description:"Update Tenants",value:"update:tenants"},{description:"Delete Tenants",value:"delete:tenants"},{description:"Read access to authentication resources",value:"auth:read"},{description:"Write access to authentication resources",value:"auth:write"}];async function eCe(e,t){const{adminUsername:n,adminPassword:r,tenantId:i="control_plane",tenantName:s="Control Plane",isControlPlane:a=!0,clientId:c="default",callbacks:l=["https://manage.authhero.net/auth-callback","https://local.authhero.net/auth-callback","https://localhost:5173/auth-callback","https://localhost:3000/auth-callback"],allowedLogoutUrls:u=["https://manage.authhero.net","https://local.authhero.net","https://localhost:5173","https://localhost:3000"],debug:d=!0}=t,f=t.audience||(a?"urn:authhero:management":`urn:authhero:tenant:${i}`);await e.tenants.get(i)?d&&console.log(`Tenant "${i}" already exists, skipping...`):(d&&console.log(`Creating tenant "${i}"...`),await e.tenants.create({id:i,friendly_name:s,audience:f,sender_email:"noreply@example.com",sender_name:"AuthHero"}),a&&await e.tenants.update(i,{allow_organization_name_in_authentication_api:!0,flags:{inherit_global_permissions_in_organizations:!0}}),d&&console.log("✅ Tenant created"));const{signingKeys:h}=await e.keys.list({q:"type:jwt_signing"});if(h.length===0){d&&console.log("Creating signing key...");const se=await Zl({name:`CN=${i}`});await e.keys.create(se),d&&console.log("✅ Signing key created")}else d&&console.log("Signing key already exists, skipping...");const _=await e.users.list(i,{q:`username:${n}`});let g;if(_.users.length===0){d&&console.log(`Creating admin user "${n}"...`);const{hash:se,algorithm:we}=await na(r);g=`${Pe}|${Ii()}`,await e.users.create(i,{user_id:g,username:n,email_verified:!1,connection:"Username-Password-Authentication",provider:Pe,password:{hash:se,algorithm:we}}),d&&(console.log("✅ Admin user created"),console.log(` Username: ${n}`))}else g=_.users[0].user_id,d&&console.log(`Admin user "${n}" already exists, skipping...`);(await e.connections.list(i)).connections.some(se=>se.name==="Username-Password-Authentication")?d&&console.log("Password connection already exists, skipping..."):(d&&console.log("Creating password connection..."),await e.connections.create(i,{name:"Username-Password-Authentication",strategy:"Username-Password-Authentication",options:{attributes:{username:{identifier:{active:!0}},email:{identifier:{active:!1}}}}}),d&&console.log("✅ Password connection created"));const v=await e.clients.get(i,c);let k;v?(k=v.client_secret||"",d&&console.log("Default client already exists, skipping...")):(d&&console.log("Creating default client..."),k=Oe(),await e.clients.create(i,{client_id:c,client_secret:k,name:"Default Application",callbacks:l,allowed_logout_urls:u,connections:["Username-Password-Authentication"],client_metadata:{universal_login_version:"2"}}),d&&(console.log("✅ Default client created"),console.log(` Client ID: ${c}`),console.log(` Callback URLs: ${l.join(", ")}`),console.log(` Allowed Logout URLs: ${u.join(", ")}`)));const x="urn:authhero:management";(await e.resourceServers.list(i,{})).resource_servers.some(se=>se.identifier===x)?d&&console.log("Management API resource server already exists, skipping..."):(d&&console.log("Creating Management API resource server..."),await e.resourceServers.create(i,{name:"Authhero Management API",identifier:x,allow_offline_access:!0,skip_consent_for_verifiable_first_party_clients:!1,token_lifetime:86400,token_lifetime_for_web:7200,signing_alg:"RS256",scopes:Ns,options:{enforce_policies:!0,token_dialect:"access_token_authz"}}),d&&(console.log("✅ Management API resource server created"),console.log(` Identifier: ${x}`),console.log(` Scopes: ${Ns.length} permissions`)));const{organizations:A}=await e.organizations.list(i,{q:`name:${i}`});let C=A[0];C?d&&console.log(`Organization "${i}" already exists, skipping...`):(d&&console.log(`Creating organization "${i}"...`),C=await e.organizations.create(i,{id:`org_${Oe()}`,name:i,display_name:s}),d&&console.log("✅ Organization created"));const P="Tenant Admin";let E=(await e.roles.list(i,{})).roles.find(se=>se.name===P);if(E)d&&console.log(`Admin role "${P}" already exists, skipping...`);else{d&&console.log(`Creating admin role "${P}"...`),E=await e.roles.create(i,{name:P,description:"Full access to tenant management operations"});const se=Ns.map(we=>({role_id:E.id,resource_server_identifier:x,permission_name:we.value}));await e.rolePermissions.assign(i,E.id,se),d&&console.log(`✅ Admin role created with ${Ns.length} permissions`)}return(await e.userOrganizations.listUserOrganizations(i,g,{})).organizations.some(se=>se.id===C.id)?d&&console.log("Admin user already in organization, skipping..."):(d&&console.log(`Adding admin user to organization "${C.name}"...`),await e.userOrganizations.create(i,{user_id:g,organization_id:C.id}),d&&console.log("✅ Admin user added to organization")),(await e.userRoles.list(i,g,void 0,C.id)).some(se=>se.id===E.id)?d&&console.log("Admin user already has admin role, skipping..."):(d&&console.log(`Assigning admin role to user in organization "${C.name}"...`),await e.userRoles.create(i,g,E.id,C.id),d&&console.log("✅ Admin role assigned to user")),(await e.userRoles.list(i,g,void 0,"")).some(se=>se.id===E.id)?d&&console.log("Admin user already has global admin role, skipping..."):(d&&console.log("Assigning global admin role to user..."),await e.userRoles.create(i,g,E.id,""),d&&console.log("✅ Global admin role assigned to user")),d&&console.log(`
|
|
443
|
-
🎉 Seeding complete!`),{tenantId:i,userId:g,username:n,clientId:c,clientSecret:k}}async function tCe(e,t,n={}){const{cursorField:r="id",sortOrder:i="asc",pageSize:s=100,maxItems:a=1e4,q:c}=n,l=[];let u,d=!0;for(;d;){let f=c||"";if(u){const y=`${r}:${i==="asc"?">":"<"}${u}`;f=f?`(${f}) AND ${y}`:y}const p={per_page:s,page:0,sort:{sort_by:r,sort_order:i},...f&&{q:f}},_=(await e(p))[t]||[];if(_.length===0)d=!1;else{l.push(..._);const g=_[_.length-1];if(g&&typeof g=="object"){const y=g[r];y!=null&&(u=String(y))}_.length<s&&(d=!1),a!==-1&&l.length>=a&&(console.warn(`fetchAll: Reached maxItems limit (${a}). There may be more items.`),d=!1)}}return l}T.init({supportedLngs:["en","it","nb","sv","pl","cs","fi","da"],fallbackLng:"en",resources:{en:{translation:ume},it:{translation:_be},nb:{translation:vwe},sv:{translation:Ske},pl:{translation:I5e},cs:{translation:Oxe},fi:{translation:B9e},da:{translation:V7e}}});function nCe(e){const t=new o.OpenAPIHono;t.onError((c,l)=>c instanceof I?c.getResponse():(console.error(c),l.json({message:"Internal Server Error"},500))),t.use("*",async(c,l)=>{e.hooks&&(c.env.hooks={...e.hooks,...c.env.hooks||{}}),e.samlSigner&&(c.env.samlSigner=e.samlSigner),e.poweredByLogo&&(c.env.poweredByLogo=e.poweredByLogo),await l()}),t.get("/",c=>c.json({name:"authhero"}));const n=nN(e);t.route("/api/v2",n);const r=XR(e);t.route("/u",r);const i=Ope(e);t.route("/u2",i);const s=r0e(e);t.route("/samlp",s);const a=XP(e);return t.route("/",a),{app:t,managementApp:n,oauthApp:a,samlApp:s,universalApp:r,u2App:i,createX509Certificate:Zl}}exports.AppLogo=F_;exports.Auth0ActionEnum=Px;exports.Auth0Client=iw;exports.AuthLayout=G7e;exports.AuthorizationResponseMode=pn;exports.AuthorizationResponseType=ot;exports.Button=Fe;exports.ButtonUI=Q$;exports.CardContent=X$;exports.CardDescription=Z$;exports.CardFooter=W7e;exports.CardHeader=W$;exports.CardTitle=J$;exports.CardUI=G$;exports.CheckEmailPage=v4;exports.CodeChallengeMethod=uu;exports.ComponentCategory=uh;exports.ComponentType=lh;exports.EmailActionEnum=Ox;exports.EmailValidatedPage=$4;exports.EnterCodePage=Q0;exports.EnterPasswordPage=Bc;exports.ErrorMessage=Jt;exports.FORM_FIELD_TYPES=_h;exports.FlowActionTypeEnum=Tx;exports.Footer=s4;exports.ForgotPasswordPage=y4;exports.ForgotPasswordSentPage=b4;exports.FormComponent=yn;exports.GoBack=Kt;exports.GoogleLogo=Z7e;exports.GrantType=an;exports.HttpSamlSigner=Kw;exports.Icon=Ze;exports.IdentifierForm=J7e;exports.IdentifierPage=Cs;exports.InputUI=Y$;exports.InvalidSession=k4;exports.LabelUI=ex;exports.Layout=Ve;exports.LocationInfo=ow;exports.LogTypes=ue;exports.LoginSessionState=We;exports.MANAGEMENT_API_AUDIENCE=bj;exports.MANAGEMENT_API_SCOPES=Ns;exports.Message=Gt;exports.NodeType=jv;exports.PreSignUpConfirmationPage=x4;exports.PreSignUpPage=w4;exports.RedirectTargetEnum=vv;exports.ResetPasswordPage=Xi;exports.SignUpPage=Xr;exports.SocialButton=c4;exports.Spinner=a4;exports.Trans=Ro;exports.USERNAME_PASSWORD_PROVIDER=Pe;exports.UnverifiedEmailPage=g4;exports.UserNotFoundPage=X7e;exports.VippsLogo=Y7e;exports.actionNodeSchema=Pv;exports.activeUsersResponseSchema=FS;exports.addEntityHooks=Ok;exports.addressSchema=xv;exports.auth0FlowInsertSchema=Mx;exports.auth0FlowSchema=Uv;exports.auth0QuerySchema=Rx;exports.auth0UpdateUserActionSchema=yv;exports.auth0UserResponseSchema=xn;exports.authParamsSchema=Js;exports.baseUserSchema=cu;exports.blockComponentSchema=Hv;exports.bordersSchema=uw;exports.brandingSchema=xc;exports.buttonComponentSchema=zv;exports.cleanupUserSessions=Q7e;exports.clientGrantInsertSchema=Zc;exports.clientGrantListSchema=Bx;exports.clientGrantSchema=ei;exports.clientInfoMiddleware=es;exports.clientInsertSchema=Jc;exports.clientSchema=Qr;exports.codeInsertSchema=Mv;exports.codeSchema=qx;exports.codeTypeSchema=Bv;exports.colorsSchema=dw;exports.componentMessageSchema=Wv;exports.componentSchema=Iv;exports.connectionInsertSchema=Xc;exports.connectionOptionsSchema=qv;exports.connectionSchema=_r;exports.coordinatesSchema=Ei;exports.createAuthMiddleware=wd;exports.createInMemoryCache=ts;exports.createPassthroughAdapter=KS;exports.createWriteOnlyAdapter=GS;exports.customDomainInsertSchema=dh;exports.customDomainSchema=fr;exports.customDomainWithTenantIdSchema=Fx;exports.customTextEntrySchema=HS;exports.customTextSchema=ro;exports.dailyStatsSchema=jw;exports.emailProviderSchema=zc;exports.emailVerificationRulesSchema=gv;exports.emailVerifyActionSchema=bv;exports.endingSchema=Dv;exports.fetchAll=tCe;exports.fieldComponentSchema=Kv;exports.flowActionStepSchema=kv;exports.flowInsertSchema=Kc;exports.flowSchema=Qi;exports.flowsFieldComponentSchema=Ev;exports.flowsFlowNodeSchema=Tv;exports.flowsStepNodeSchema=Nv;exports.fontDetailsSchema=Zr;exports.fontsSchema=pw;exports.formControlSchema=gS;exports.formInsertSchema=Yc;exports.formNodeComponentDefinition=hh;exports.formNodeSchema=Gv;exports.formSchema=eo;exports.genericComponentSchema=Cv;exports.genericNodeSchema=Ov;exports.getConnectionIdentifierConfig=Ci;exports.hookInsertSchema=af;exports.hookSchema=to;exports.hookTemplateId=mh;exports.hookTemplates=SS;exports.identitySchema=Gc;exports.init=nCe;exports.injectTailwindCSS=fR;exports.inviteInsertSchema=gh;exports.inviteSchema=Os;exports.inviteeSchema=ew;exports.inviterSchema=Qv;exports.isBlockComponent=kS;exports.isFieldComponent=xS;exports.isWidgetComponent=$S;exports.jwksKeySchema=tw;exports.jwksSchema=yh;exports.legalComponentSchema=Av;exports.logInsertSchema=sw;exports.logSchema=Qc;exports.loginSessionInsertSchema=rw;exports.loginSessionSchema=NS;exports.loginSessionStateSchema=nw;exports.nodeSchema=Rv;exports.openIDConfigurationSchema=cf;exports.organizationBrandingSchema=Aw;exports.organizationEnabledConnectionSchema=Ew;exports.organizationInsertSchema=il;exports.organizationSchema=mr;exports.organizationTokenQuotaSchema=Cw;exports.pageBackgroundSchema=fw;exports.parseUserId=VS;exports.passwordInsertSchema=aw;exports.passwordSchema=PS;exports.preDefinedHooks=s9;exports.profileDataSchema=$v;exports.promptScreenSchema=no;exports.promptSettingSchema=Rs;exports.redirectActionSchema=wv;exports.refreshTokenInsertSchema=wh;exports.refreshTokenSchema=OS;exports.resourceServerInsertSchema=tl;exports.resourceServerListSchema=DS;exports.resourceServerOptionsSchema=gw;exports.resourceServerSchema=ti;exports.resourceServerScopeSchema=mw;exports.richTextComponentSchema=Sv;exports.roleInsertSchema=nl;exports.roleListSchema=rl;exports.rolePermissionInsertSchema=yw;exports.rolePermissionListSchema=vw;exports.rolePermissionSchema=bw;exports.roleSchema=ni;exports.screenLinkSchema=Jv;exports.seed=eCe;exports.sessionInsertSchema=lw;exports.sessionSchema=du;exports.signingKeySchema=lf;exports.smsProviderSchema=LS;exports.smsSendParamsSchema=RS;exports.startSchema=Lv;exports.tailwindCss=K_;exports.tenantInsertSchema=bh;exports.tenantMiddleware=Qo;exports.tenantSchema=el;exports.tenantSettingsSchema=qS;exports.themeInsertSchema=_w;exports.themeSchema=Sc;exports.tokenResponseSchema=vh;exports.totalsSchema=It;exports.uiScreenSchema=wS;exports.userInsertSchema=Wc;exports.userOrganizationInsertSchema=Iw;exports.userOrganizationSchema=MS;exports.userPermissionInsertSchema=ww;exports.userPermissionListSchema=US;exports.userPermissionSchema=kw;exports.userPermissionWithDetailsListSchema=xw;exports.userPermissionWithDetailsSchema=$w;exports.userResponseSchema=Lx;exports.userRoleInsertSchema=Sw;exports.userRoleListSchema=BS;exports.userRoleSchema=zw;exports.userSchema=ch;exports.verificationMethodsSchema=Fv;exports.waitUntil=Ow;exports.widgetComponentSchema=Vv;exports.widgetSchema=hw;
|
|
443
|
+
🎉 Seeding complete!`),{tenantId:i,userId:g,username:n,clientId:c,clientSecret:k}}async function tCe(e,t,n={}){const{cursorField:r="id",sortOrder:i="asc",pageSize:s=100,maxItems:a=1e4,q:c}=n,l=[];let u,d=!0;for(;d;){let f=c||"";if(u){const y=`${r}:${i==="asc"?">":"<"}${u}`;f=f?`(${f}) AND ${y}`:y}const p={per_page:s,page:0,sort:{sort_by:r,sort_order:i},...f&&{q:f}},_=(await e(p))[t]||[];if(_.length===0)d=!1;else{l.push(..._);const g=_[_.length-1];if(g&&typeof g=="object"){const y=g[r];y!=null&&(u=String(y))}_.length<s&&(d=!1),a!==-1&&l.length>=a&&(console.warn(`fetchAll: Reached maxItems limit (${a}). There may be more items.`),d=!1)}}return l}T.init({supportedLngs:["en","it","nb","sv","pl","cs","fi","da"],fallbackLng:"en",resources:{en:{translation:ume},it:{translation:_be},nb:{translation:vwe},sv:{translation:Ske},pl:{translation:I5e},cs:{translation:Oxe},fi:{translation:B9e},da:{translation:V7e}}});function nCe(e){const t=new o.OpenAPIHono;t.onError((c,l)=>c instanceof I?c.getResponse():(console.error(c),l.json({message:"Internal Server Error"},500))),t.use("*",async(c,l)=>{e.hooks&&(c.env.hooks={...e.hooks,...c.env.hooks||{}}),e.samlSigner&&(c.env.samlSigner=e.samlSigner),e.poweredByLogo&&(c.env.poweredByLogo=e.poweredByLogo),e.webhookInvoker&&(c.env.webhookInvoker=e.webhookInvoker),await l()}),t.get("/",c=>c.json({name:"authhero"}));const n=nN(e);t.route("/api/v2",n);const r=XR(e);t.route("/u",r);const i=Ope(e);t.route("/u2",i);const s=r0e(e);t.route("/samlp",s);const a=XP(e);return t.route("/",a),{app:t,managementApp:n,oauthApp:a,samlApp:s,universalApp:r,u2App:i,createX509Certificate:Zl}}exports.AppLogo=F_;exports.Auth0ActionEnum=Px;exports.Auth0Client=iw;exports.AuthLayout=G7e;exports.AuthorizationResponseMode=pn;exports.AuthorizationResponseType=ot;exports.Button=Fe;exports.ButtonUI=Q$;exports.CardContent=X$;exports.CardDescription=Z$;exports.CardFooter=W7e;exports.CardHeader=W$;exports.CardTitle=J$;exports.CardUI=G$;exports.CheckEmailPage=v4;exports.CodeChallengeMethod=uu;exports.ComponentCategory=uh;exports.ComponentType=lh;exports.EmailActionEnum=Ox;exports.EmailValidatedPage=$4;exports.EnterCodePage=Q0;exports.EnterPasswordPage=Bc;exports.ErrorMessage=Jt;exports.FORM_FIELD_TYPES=_h;exports.FlowActionTypeEnum=Tx;exports.Footer=s4;exports.ForgotPasswordPage=y4;exports.ForgotPasswordSentPage=b4;exports.FormComponent=yn;exports.GoBack=Kt;exports.GoogleLogo=Z7e;exports.GrantType=an;exports.HttpSamlSigner=Kw;exports.Icon=Ze;exports.IdentifierForm=J7e;exports.IdentifierPage=Cs;exports.InputUI=Y$;exports.InvalidSession=k4;exports.LabelUI=ex;exports.Layout=Ve;exports.LocationInfo=ow;exports.LogTypes=ue;exports.LoginSessionState=We;exports.MANAGEMENT_API_AUDIENCE=bj;exports.MANAGEMENT_API_SCOPES=Ns;exports.Message=Gt;exports.NodeType=jv;exports.PreSignUpConfirmationPage=x4;exports.PreSignUpPage=w4;exports.RedirectTargetEnum=vv;exports.ResetPasswordPage=Xi;exports.SignUpPage=Xr;exports.SocialButton=c4;exports.Spinner=a4;exports.Trans=Ro;exports.USERNAME_PASSWORD_PROVIDER=Pe;exports.UnverifiedEmailPage=g4;exports.UserNotFoundPage=X7e;exports.VippsLogo=Y7e;exports.actionNodeSchema=Pv;exports.activeUsersResponseSchema=FS;exports.addEntityHooks=Ok;exports.addressSchema=xv;exports.auth0FlowInsertSchema=Mx;exports.auth0FlowSchema=Uv;exports.auth0QuerySchema=Rx;exports.auth0UpdateUserActionSchema=yv;exports.auth0UserResponseSchema=xn;exports.authParamsSchema=Js;exports.baseUserSchema=cu;exports.blockComponentSchema=Hv;exports.bordersSchema=uw;exports.brandingSchema=xc;exports.buttonComponentSchema=zv;exports.cleanupUserSessions=Q7e;exports.clientGrantInsertSchema=Zc;exports.clientGrantListSchema=Bx;exports.clientGrantSchema=ei;exports.clientInfoMiddleware=es;exports.clientInsertSchema=Jc;exports.clientSchema=Qr;exports.codeInsertSchema=Mv;exports.codeSchema=qx;exports.codeTypeSchema=Bv;exports.colorsSchema=dw;exports.componentMessageSchema=Wv;exports.componentSchema=Iv;exports.connectionInsertSchema=Xc;exports.connectionOptionsSchema=qv;exports.connectionSchema=_r;exports.coordinatesSchema=Ei;exports.createAuthMiddleware=wd;exports.createInMemoryCache=ts;exports.createPassthroughAdapter=KS;exports.createWriteOnlyAdapter=GS;exports.customDomainInsertSchema=dh;exports.customDomainSchema=fr;exports.customDomainWithTenantIdSchema=Fx;exports.customTextEntrySchema=HS;exports.customTextSchema=ro;exports.dailyStatsSchema=jw;exports.emailProviderSchema=zc;exports.emailVerificationRulesSchema=gv;exports.emailVerifyActionSchema=bv;exports.endingSchema=Dv;exports.fetchAll=tCe;exports.fieldComponentSchema=Kv;exports.flowActionStepSchema=kv;exports.flowInsertSchema=Kc;exports.flowSchema=Qi;exports.flowsFieldComponentSchema=Ev;exports.flowsFlowNodeSchema=Tv;exports.flowsStepNodeSchema=Nv;exports.fontDetailsSchema=Zr;exports.fontsSchema=pw;exports.formControlSchema=gS;exports.formInsertSchema=Yc;exports.formNodeComponentDefinition=hh;exports.formNodeSchema=Gv;exports.formSchema=eo;exports.genericComponentSchema=Cv;exports.genericNodeSchema=Ov;exports.getConnectionIdentifierConfig=Ci;exports.hookInsertSchema=af;exports.hookSchema=to;exports.hookTemplateId=mh;exports.hookTemplates=SS;exports.identitySchema=Gc;exports.init=nCe;exports.injectTailwindCSS=fR;exports.inviteInsertSchema=gh;exports.inviteSchema=Os;exports.inviteeSchema=ew;exports.inviterSchema=Qv;exports.isBlockComponent=kS;exports.isFieldComponent=xS;exports.isWidgetComponent=$S;exports.jwksKeySchema=tw;exports.jwksSchema=yh;exports.legalComponentSchema=Av;exports.logInsertSchema=sw;exports.logSchema=Qc;exports.loginSessionInsertSchema=rw;exports.loginSessionSchema=NS;exports.loginSessionStateSchema=nw;exports.nodeSchema=Rv;exports.openIDConfigurationSchema=cf;exports.organizationBrandingSchema=Aw;exports.organizationEnabledConnectionSchema=Ew;exports.organizationInsertSchema=il;exports.organizationSchema=mr;exports.organizationTokenQuotaSchema=Cw;exports.pageBackgroundSchema=fw;exports.parseUserId=VS;exports.passwordInsertSchema=aw;exports.passwordSchema=PS;exports.preDefinedHooks=s9;exports.profileDataSchema=$v;exports.promptScreenSchema=no;exports.promptSettingSchema=Rs;exports.redirectActionSchema=wv;exports.refreshTokenInsertSchema=wh;exports.refreshTokenSchema=OS;exports.resourceServerInsertSchema=tl;exports.resourceServerListSchema=DS;exports.resourceServerOptionsSchema=gw;exports.resourceServerSchema=ti;exports.resourceServerScopeSchema=mw;exports.richTextComponentSchema=Sv;exports.roleInsertSchema=nl;exports.roleListSchema=rl;exports.rolePermissionInsertSchema=yw;exports.rolePermissionListSchema=vw;exports.rolePermissionSchema=bw;exports.roleSchema=ni;exports.screenLinkSchema=Jv;exports.seed=eCe;exports.sessionInsertSchema=lw;exports.sessionSchema=du;exports.signingKeySchema=lf;exports.smsProviderSchema=LS;exports.smsSendParamsSchema=RS;exports.startSchema=Lv;exports.tailwindCss=K_;exports.tenantInsertSchema=bh;exports.tenantMiddleware=Qo;exports.tenantSchema=el;exports.tenantSettingsSchema=qS;exports.themeInsertSchema=_w;exports.themeSchema=Sc;exports.tokenResponseSchema=vh;exports.totalsSchema=It;exports.uiScreenSchema=wS;exports.userInsertSchema=Wc;exports.userOrganizationInsertSchema=Iw;exports.userOrganizationSchema=MS;exports.userPermissionInsertSchema=ww;exports.userPermissionListSchema=US;exports.userPermissionSchema=kw;exports.userPermissionWithDetailsListSchema=xw;exports.userPermissionWithDetailsSchema=$w;exports.userResponseSchema=Lx;exports.userRoleInsertSchema=Sw;exports.userRoleListSchema=BS;exports.userRoleSchema=zw;exports.userSchema=ch;exports.verificationMethodsSchema=Fv;exports.waitUntil=Ow;exports.widgetComponentSchema=Vv;exports.widgetSchema=hw;
|