authhero 0.294.0 → 0.295.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 CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@hono/zod-openapi"),Y=t=>typeof t=="string",Ei=()=>{let t,e;const n=new Promise((r,i)=>{t=r,e=i});return n.resolve=t,n.reject=e,n},df=t=>t==null?"":""+t,jw=(t,e,n)=>{t.forEach(r=>{e[r]&&(n[r]=e[r])})},Pw=/###/g,uf=t=>t&&t.indexOf("###")>-1?t.replace(Pw,"."):t,pf=t=>!t||Y(t),to=(t,e,n)=>{const r=Y(e)?e.split("."):e;let i=0;for(;i<r.length-1;){if(pf(t))return{};const s=uf(r[i]);!t[s]&&n&&(t[s]=new n),Object.prototype.hasOwnProperty.call(t,s)?t=t[s]:t={},++i}return pf(t)?{}:{obj:t,k:uf(r[i])}},ff=(t,e,n)=>{const{obj:r,k:i}=to(t,e,Object);if(r!==void 0||e.length===1){r[i]=n;return}let s=e[e.length-1],a=e.slice(0,e.length-1),c=to(t,a,Object);for(;c.obj===void 0&&a.length;)s=`${a[a.length-1]}.${s}`,a=a.slice(0,a.length-1),c=to(t,a,Object),c?.obj&&typeof c.obj[`${c.k}.${s}`]<"u"&&(c.obj=void 0);c.obj[`${c.k}.${s}`]=n},Ow=(t,e,n,r)=>{const{obj:i,k:s}=to(t,e,Object);i[s]=i[s]||[],i[s].push(n)},Ds=(t,e)=>{const{obj:n,k:r}=to(t,e);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},Tw=(t,e,n)=>{const r=Ds(t,n);return r!==void 0?r:Ds(e,n)},L0=(t,e,n)=>{for(const r in e)r!=="__proto__"&&r!=="constructor"&&(r in t?Y(t[r])||t[r]instanceof String||Y(e[r])||e[r]instanceof String?n&&(t[r]=e[r]):L0(t[r],e[r],n):t[r]=e[r]);return t},Ar=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Rw={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const Bw=t=>Y(t)?t.replace(/[&<>"'\/]/g,e=>Rw[e]):t;class Lw{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const n=this.regExpMap.get(e);if(n!==void 0)return n;const r=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,r),this.regExpQueue.push(e),r}}const Uw=[" ",",","?","!",";"],Dw=new Lw(20),Mw=(t,e,n)=>{e=e||"",n=n||"";const r=Uw.filter(a=>e.indexOf(a)<0&&n.indexOf(a)<0);if(r.length===0)return!0;const i=Dw.getRegExp(`(${r.map(a=>a==="?"?"\\?":a).join("|")})`);let s=!i.test(t);if(!s){const a=t.indexOf(n);a>0&&!i.test(t.substring(0,a))&&(s=!0)}return s},Tl=(t,e,n=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const r=e.split(n);let i=t;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},ho=t=>t?.replace("_","-"),qw={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){console?.[t]?.apply?.(console,e)}};class Ms{constructor(e,n={}){this.init(e,n)}init(e,n={}){this.prefix=n.prefix||"i18next:",this.logger=e||qw,this.options=n,this.debug=n.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,n,r,i){return i&&!this.debug?null:(Y(e[0])&&(e[0]=`${r}${this.prefix} ${e[0]}`),this.logger[n](e))}create(e){return new Ms(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Ms(this.logger,e)}}var Vt=new Ms;class Ha{constructor(){this.observers={}}on(e,n){return e.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(e,n){if(this.observers[e]){if(!n){delete this.observers[e];return}this.observers[e].delete(n)}}emit(e,...n){this.observers[e]&&Array.from(this.observers[e].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,[e,...n])})}}class hf extends Ha{constructor(e,n={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){const n=this.options.ns.indexOf(e);n>-1&&this.options.ns.splice(n,1)}getResource(e,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;e.indexOf(".")>-1?c=e.split("."):(c=[e,n],r&&(Array.isArray(r)?c.push(...r):Y(r)&&s?c.push(...r.split(s)):c.push(r)));const l=Ds(this.data,c);return!l&&!n&&!r&&e.indexOf(".")>-1&&(e=c[0],n=c[1],r=c.slice(2).join(".")),l||!a||!Y(r)?l:Tl(this.data?.[e]?.[n],r,s)}addResource(e,n,r,i,s={silent:!1}){const a=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let c=[e,n];r&&(c=c.concat(a?r.split(a):r)),e.indexOf(".")>-1&&(c=e.split("."),i=n,n=c[1]),this.addNamespaces(n),ff(this.data,c,i),s.silent||this.emit("added",e,n,r,i)}addResources(e,n,r,i={silent:!1}){for(const s in r)(Y(r[s])||Array.isArray(r[s]))&&this.addResource(e,n,s,r[s],{silent:!0});i.silent||this.emit("added",e,n,r)}addResourceBundle(e,n,r,i,s,a={silent:!1,skipCopy:!1}){let c=[e,n];e.indexOf(".")>-1&&(c=e.split("."),i=r,r=n,n=c[1]),this.addNamespaces(n);let l=Ds(this.data,c)||{};a.skipCopy||(r=JSON.parse(JSON.stringify(r))),i?L0(l,r,s):l={...l,...r},ff(this.data,c,l),a.silent||this.emit("added",e,n,r)}removeResourceBundle(e,n){this.hasResourceBundle(e,n)&&delete this.data[e][n],this.removeNamespaces(n),this.emit("removed",e,n)}hasResourceBundle(e,n){return this.getResource(e,n)!==void 0}getResourceBundle(e,n){return n||(n=this.options.defaultNS),this.getResource(e,n)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const n=this.getDataByLanguage(e);return!!(n&&Object.keys(n)||[]).find(i=>n[i]&&Object.keys(n[i]).length>0)}toJSON(){return this.data}}var U0={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,n,r,i){return t.forEach(s=>{e=this.processors[s]?.process(e,n,r,i)??e}),e}};const D0=Symbol("i18next/PATH_KEY");function Fw(){const t=[],e=Object.create(null);let n;return e.get=(r,i)=>(n?.revoke?.(),i===D0?t:(t.push(i),n=Proxy.revocable(r,e),n.proxy)),Proxy.revocable(Object.create(null),e).proxy}function Rl(t,e){const{[D0]:n}=t(Fw());return n.join(e?.keySeparator??".")}const gf={},cl=t=>!Y(t)&&typeof t!="boolean"&&typeof t!="number";class qs extends Ha{constructor(e,n={}){super(),jw(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Vt.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,n={interpolation:{}}){const r={...n};if(e==null)return!1;const i=this.resolve(e,r);if(i?.res===void 0)return!1;const s=cl(i.res);return!(r.returnObjects===!1&&s)}extractFromKey(e,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&&e.indexOf(r)>-1,c=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!Mw(e,r,i);if(a&&!c){const l=e.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:e,namespaces:Y(s)?[s]:s};const d=e.split(r);(r!==i||r===i&&this.options.ns.indexOf(d[0])>-1)&&(s=d.shift()),e=d.join(i)}return{key:e,namespaces:Y(s)?[s]:s}}translate(e,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={}),e==null)return"";typeof e=="function"&&(e=Rl(e,{...this.options,...i})),Array.isArray(e)||(e=[String(e)]);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(e[e.length-1],i),d=l[l.length-1];let u=i.nsSeparator!==void 0?i.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const f=i.lng||this.language,g=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(f?.toLowerCase()==="cimode")return g?s?{res:`${d}${u}${c}`,usedKey:c,exactUsedKey:c,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(i)}:`${d}${u}${c}`:s?{res:c,usedKey:c,exactUsedKey:c,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(i)}:c;const _=this.resolve(e,i);let w=_?.res;const k=_?.usedKey||c,z=_?.exactUsedKey||c,N=["[object Number]","[object Function]","[object RegExp]"],I=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,S=!this.i18nFormat||this.i18nFormat.handleAsObject,E=i.count!==void 0&&!Y(i.count),P=qs.hasDefaultValue(i),G=E?this.pluralResolver.getSuffix(f,i.count,i):"",Z=i.ordinal&&E?this.pluralResolver.getSuffix(f,i.count,{ordinal:!1}):"",W=E&&!i.ordinal&&i.count===0,M=W&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${G}`]||i[`defaultValue${Z}`]||i.defaultValue;let ce=w;S&&!w&&P&&(ce=M);const le=cl(ce),fe=Object.prototype.toString.apply(ce);if(S&&ce&&le&&N.indexOf(fe)<0&&!(Y(I)&&Array.isArray(ce))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const $e=this.options.returnedObjectHandler?this.options.returnedObjectHandler(k,ce,{...i,ns:l}):`key '${c} (${this.language})' returned an object instead of string.`;return s?(_.res=$e,_.usedParams=this.getUsedParamsDetails(i),_):$e}if(a){const $e=Array.isArray(ce),be=$e?[]:{},sn=$e?z:k;for(const Be in ce)if(Object.prototype.hasOwnProperty.call(ce,Be)){const Qe=`${sn}${a}${Be}`;P&&!w?be[Be]=this.translate(Qe,{...i,defaultValue:cl(M)?M[Be]:void 0,joinArrays:!1,ns:l}):be[Be]=this.translate(Qe,{...i,joinArrays:!1,ns:l}),be[Be]===Qe&&(be[Be]=ce[Be])}w=be}}else if(S&&Y(I)&&Array.isArray(w))w=w.join(I),w&&(w=this.extendTranslation(w,e,i,r));else{let $e=!1,be=!1;!this.isValidLookup(w)&&P&&($e=!0,w=M),this.isValidLookup(w)||(be=!0,w=c);const Be=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&be?void 0:w,Qe=P&&M!==w&&this.options.updateMissing;if(be||$e||Qe){if(this.logger.log(Qe?"updateKey":"missingKey",f,d,c,Qe?M:w),a){const Pe=this.resolve(c,{...i,keySeparator:!1});Pe&&Pe.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 Lt=[];const Ut=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&Ut&&Ut[0])for(let Pe=0;Pe<Ut.length;Pe++)Lt.push(Ut[Pe]);else this.options.saveMissingTo==="all"?Lt=this.languageUtils.toResolveHierarchy(i.lng||this.language):Lt.push(i.lng||this.language);const Hn=(Pe,et,K)=>{const vt=P&&K!==w?K:Be;this.options.missingKeyHandler?this.options.missingKeyHandler(Pe,d,et,vt,Qe,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(Pe,d,et,vt,Qe,i),this.emit("missingKey",Pe,d,et,w)};this.options.saveMissing&&(this.options.saveMissingPlurals&&E?Lt.forEach(Pe=>{const et=this.pluralResolver.getSuffixes(Pe,i);W&&i[`defaultValue${this.options.pluralSeparator}zero`]&&et.indexOf(`${this.options.pluralSeparator}zero`)<0&&et.push(`${this.options.pluralSeparator}zero`),et.forEach(K=>{Hn([Pe],c+K,i[`defaultValue${K}`]||M)})}):Hn(Lt,c,M))}w=this.extendTranslation(w,e,i,_,r),be&&w===c&&this.options.appendNamespaceToMissingKey&&(w=`${d}${u}${c}`),(be||$e)&&this.options.parseMissingKeyHandler&&(w=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${u}${c}`:c,$e?w:void 0,i))}return s?(_.res=w,_.usedParams=this.getUsedParamsDetails(i),_):w}extendTranslation(e,n,r,i,s){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...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=Y(e)&&(r?.interpolation?.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let d;if(l){const f=e.match(this.interpolator.nestingRegexp);d=f&&f.length}let u=r.replace&&!Y(r.replace)?r.replace:r;if(this.options.interpolation.defaultVariables&&(u={...this.options.interpolation.defaultVariables,...u}),e=this.interpolator.interpolate(e,u,r.lng||this.language||i.usedLng,r),l){const f=e.match(this.interpolator.nestingRegexp),g=f&&f.length;d<g&&(r.nest=!1)}!r.lng&&i&&i.res&&(r.lng=this.language||i.usedLng),r.nest!==!1&&(e=this.interpolator.nest(e,(...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=Y(a)?[a]:a;return e!=null&&c?.length&&r.applyPostProcessor!==!1&&(e=U0.handle(c,e,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(r)},...r}:r,this)),e}resolve(e,n={}){let r,i,s,a,c;return Y(e)&&(e=[e]),e.forEach(l=>{if(this.isValidLookup(r))return;const d=this.extractFromKey(l,n),u=d.key;i=u;let f=d.namespaces;this.options.fallbackNS&&(f=f.concat(this.options.fallbackNS));const g=n.count!==void 0&&!Y(n.count),_=g&&!n.ordinal&&n.count===0,w=n.context!==void 0&&(Y(n.context)||typeof n.context=="number")&&n.context!=="",k=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);f.forEach(z=>{this.isValidLookup(r)||(c=z,!gf[`${k[0]}-${z}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(c)&&(gf[`${k[0]}-${z}`]=!0,this.logger.warn(`key "${i}" for languages "${k.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!!!")),k.forEach(N=>{if(this.isValidLookup(r))return;a=N;const I=[u];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(I,u,N,z,n);else{let E;g&&(E=this.pluralResolver.getSuffix(N,n.count,n));const P=`${this.options.pluralSeparator}zero`,G=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(g&&(n.ordinal&&E.indexOf(G)===0&&I.push(u+E.replace(G,this.options.pluralSeparator)),I.push(u+E),_&&I.push(u+P)),w){const Z=`${u}${this.options.contextSeparator||"_"}${n.context}`;I.push(Z),g&&(n.ordinal&&E.indexOf(G)===0&&I.push(Z+E.replace(G,this.options.pluralSeparator)),I.push(Z+E),_&&I.push(Z+P))}}let S;for(;S=I.pop();)this.isValidLookup(r)||(s=S,r=this.getResource(N,z,S,n))}))})}),{res:r,usedKey:i,exactUsedKey:s,usedLng:a,usedNS:c}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,n,r,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,n,r,i):this.resourceStore.getResource(e,n,r,i)}getUsedParamsDetails(e={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=e.replace&&!Y(e.replace);let i=r?e.replace:e;if(r&&typeof e.count<"u"&&(i.count=e.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(e){const n="defaultValue";for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&n===r.substring(0,n.length)&&e[r]!==void 0)return!0;return!1}}class mf{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Vt.create("languageUtils")}getScriptPartFromCode(e){if(e=ho(e),!e||e.indexOf("-")<0)return null;const n=e.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(e){if(e=ho(e),!e||e.indexOf("-")<0)return e;const n=e.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(e){if(Y(e)&&e.indexOf("-")>-1){let n;try{n=Intl.getCanonicalLocales(e)[0]}catch{}return n&&this.options.lowerCaseLng&&(n=n.toLowerCase()),n||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let n;return e.forEach(r=>{if(n)return;const i=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(i))&&(n=i)}),!n&&this.options.supportedLngs&&e.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(e,n){if(!e)return[];if(typeof e=="function"&&(e=e(n)),Y(e)&&(e=[e]),Array.isArray(e))return e;if(!n)return e.default||[];let r=e[n];return r||(r=e[this.getScriptPartFromCode(n)]),r||(r=e[this.formatLanguageCode(n)]),r||(r=e[this.getLanguagePartFromCode(n)]),r||(r=e.default),r||[]}toResolveHierarchy(e,n){const r=this.getFallbackCodes((n===!1?[]:n)||this.options.fallbackLng||[],e),i=[],s=a=>{a&&(this.isSupportedCode(a)?i.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return Y(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&s(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&s(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&s(this.getLanguagePartFromCode(e))):Y(e)&&s(this.formatLanguageCode(e)),r.forEach(a=>{i.indexOf(a)<0&&s(this.formatLanguageCode(a))}),i}}const _f={zero:0,one:1,two:2,few:3,many:4,other:5},yf={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Hw{constructor(e,n={}){this.languageUtils=e,this.options=n,this.logger=Vt.create("pluralResolver"),this.pluralRulesCache={}}addRule(e,n){this.rules[e]=n}clearCache(){this.pluralRulesCache={}}getRule(e,n={}){const r=ho(e==="dev"?"en":e),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(!Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),yf;if(!e.match(/-|_/))return yf;const l=this.languageUtils.getLanguagePartFromCode(e);a=this.getRule(l,n)}return this.pluralRulesCache[s]=a,a}needsPlural(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,n,r={}){return this.getSuffixes(e,r).map(i=>`${n}${i}`)}getSuffixes(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?r.resolvedOptions().pluralCategories.sort((i,s)=>_f[i]-_f[s]).map(i=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i}`):[]}getSuffix(e,n,r={}){const i=this.getRule(e,r);return i?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${i.select(n)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",n,r))}}const wf=(t,e,n,r=".",i=!0)=>{let s=Tw(t,e,n);return!s&&i&&Y(n)&&(s=Tl(t,n,r),s===void 0&&(s=Tl(e,n,r))),s},ll=t=>t.replace(/\$/g,"$$$$");class bf{constructor(e={}){this.logger=Vt.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(n=>n),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:i,prefix:s,prefixEscaped:a,suffix:c,suffixEscaped:l,formatSeparator:d,unescapeSuffix:u,unescapePrefix:f,nestingPrefix:g,nestingPrefixEscaped:_,nestingSuffix:w,nestingSuffixEscaped:k,nestingOptionsSeparator:z,maxReplaces:N,alwaysFormat:I}=e.interpolation;this.escape=n!==void 0?n:Bw,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=s?Ar(s):a||"{{",this.suffix=c?Ar(c):l||"}}",this.formatSeparator=d||",",this.unescapePrefix=u?"":f||"-",this.unescapeSuffix=this.unescapePrefix?"":u||"",this.nestingPrefix=g?Ar(g):_||Ar("$t("),this.nestingSuffix=w?Ar(w):k||Ar(")"),this.nestingOptionsSeparator=z||",",this.maxReplaces=N||1e3,this.alwaysFormat=I!==void 0?I:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(n,r)=>n?.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,n,r,i){let s,a,c;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},d=_=>{if(_.indexOf(this.formatSeparator)<0){const N=wf(n,l,_,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(N,void 0,r,{...i,...n,interpolationkey:_}):N}const w=_.split(this.formatSeparator),k=w.shift().trim(),z=w.join(this.formatSeparator).trim();return this.format(wf(n,l,k,this.options.keySeparator,this.options.ignoreJSONStructure),z,r,{...i,...n,interpolationkey:k})};this.resetRegExp();const u=i?.missingInterpolationHandler||this.options.missingInterpolationHandler,f=i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:_=>ll(_)},{regex:this.regexp,safeValue:_=>this.escapeValue?ll(this.escape(_)):ll(_)}].forEach(_=>{for(c=0;s=_.regex.exec(e);){const w=s[1].trim();if(a=d(w),a===void 0)if(typeof u=="function"){const z=u(e,s,i);a=Y(z)?z:""}else if(i&&Object.prototype.hasOwnProperty.call(i,w))a="";else if(f){a=s[0];continue}else this.logger.warn(`missed to pass in variable ${w} for interpolating ${e}`),a="";else!Y(a)&&!this.useRawValueToEscape&&(a=df(a));const k=_.safeValue(a);if(e=e.replace(s[0],k),f?(_.regex.lastIndex+=a.length,_.regex.lastIndex-=s[0].length):_.regex.lastIndex=0,c++,c>=this.maxReplaces)break}}),e}nest(e,n,r={}){let i,s,a;const c=(l,d)=>{const u=this.nestingOptionsSeparator;if(l.indexOf(u)<0)return l;const f=l.split(new RegExp(`${u}[ ]*{`));let g=`{${f[1]}`;l=f[0],g=this.interpolate(g,a);const _=g.match(/'/g),w=g.match(/"/g);((_?.length??0)%2===0&&!w||w.length%2!==0)&&(g=g.replace(/'/g,'"'));try{a=JSON.parse(g),d&&(a={...d,...a})}catch(k){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,k),`${l}${u}${g}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,l};for(;i=this.nestingRegexp.exec(e);){let l=[];a={...r},a=a.replace&&!Y(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;const d=/{.*}/.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(d!==-1&&(l=i[1].slice(d).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),i[1]=i[1].slice(0,d)),s=n(c.call(this,i[1].trim(),a),a),s&&i[0]===e&&!Y(s))return s;Y(s)||(s=df(s)),s||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${e}`),s=""),l.length&&(s=l.reduce((u,f)=>this.format(u,f,r.lng,{...r,interpolationkey:i[1].trim()}),s.trim())),e=e.replace(i[0],s),this.regexp.lastIndex=0}return e}}const Vw=t=>{let e=t.toLowerCase().trim();const n={};if(t.indexOf("(")>-1){const r=t.split("(");e=r[0].toLowerCase().trim();const i=r[1].substring(0,r[1].length-1);e==="currency"&&i.indexOf(":")<0?n.currency||(n.currency=i.trim()):e==="relativetime"&&i.indexOf(":")<0?n.range||(n.range=i.trim()):i.split(";").forEach(a=>{if(a){const[c,...l]=a.split(":"),d=l.join(":").trim().replace(/^'+|'+$/g,""),u=c.trim();n[u]||(n[u]=d),d==="false"&&(n[u]=!1),d==="true"&&(n[u]=!0),isNaN(d)||(n[u]=parseInt(d,10))}})}return{formatName:e,formatOptions:n}},vf=t=>{const e={};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=e[a];return c||(c=t(ho(r),i),e[a]=c),c(n)}},Kw=t=>(e,n,r)=>t(ho(n),r)(e);class Gw{constructor(e={}){this.logger=Vt.create("formatter"),this.options=e,this.init(e)}init(e,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const r=n.cacheInBuiltFormats?vf:Kw;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(e,n){this.formats[e.toLowerCase().trim()]=n}addCached(e,n){this.formats[e.toLowerCase().trim()]=vf(n)}format(e,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:d,formatOptions:u}=Vw(l);if(this.formats[d]){let f=c;try{const g=i?.formatParams?.[i.interpolationkey]||{},_=g.locale||g.lng||i.locale||i.lng||r;f=this.formats[d](c,_,{...u,...i,...g})}catch(g){this.logger.warn(g)}return f}else this.logger.warn(`there was no format function for ${d}`);return c},e)}}const Ww=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Jw extends Ha{constructor(e,n,r,i={}){super(),this.backend=e,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=i,this.logger=Vt.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(e,n,r,i){const s={},a={},c={},l={};return e.forEach(d=>{let u=!0;n.forEach(f=>{const g=`${d}|${f}`;!r.reload&&this.store.hasResourceBundle(d,f)?this.state[g]=2:this.state[g]<0||(this.state[g]===1?a[g]===void 0&&(a[g]=!0):(this.state[g]=1,u=!1,a[g]===void 0&&(a[g]=!0),s[g]===void 0&&(s[g]=!0),l[f]===void 0&&(l[f]=!0)))}),u||(c[d]=!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(e,n,r){const i=e.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[e]=n?-1:2,n&&r&&(this.state[e]=0);const c={};this.queue.forEach(l=>{Ow(l.loaded,[s],a),Ww(l,e),n&&l.errors.push(n),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(d=>{c[d]||(c[d]={});const u=l.loaded[d];u.length&&u.forEach(f=>{c[d][f]===void 0&&(c[d][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(e,n,r,i=0,s=this.retryTimeout,a){if(!e.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:n,fcName:r,tried:i,wait:s,callback:a});return}this.readingCalls++;const c=(d,u)=>{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(d&&u&&i<this.maxRetries){setTimeout(()=>{this.read.call(this,e,n,r,i+1,s*2,a)},s);return}a(d,u)},l=this.backend[r].bind(this.backend);if(l.length===2){try{const d=l(e,n);d&&typeof d.then=="function"?d.then(u=>c(null,u)).catch(c):c(null,d)}catch(d){c(d)}return}return l(e,n,c)}prepareLoading(e,n,r={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();Y(e)&&(e=this.languageUtils.toResolveHierarchy(e)),Y(n)&&(n=[n]);const s=this.queueLoad(e,n,r,i);if(!s.toLoad.length)return s.pending.length||i(),null;s.toLoad.forEach(a=>{this.loadOne(a)})}load(e,n,r){this.prepareLoading(e,n,{},r)}reload(e,n,r){this.prepareLoading(e,n,{reload:!0},r)}loadOne(e,n=""){const r=e.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(e,a,c)})}saveMissing(e,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},d=this.backend.create.bind(this.backend);if(d.length<6)try{let u;d.length===5?u=d(e,n,r,i,l):u=d(e,n,r,i),u&&typeof u.then=="function"?u.then(f=>c(null,f)).catch(c):c(null,u)}catch(u){c(u)}else d(e,n,r,i,c,l)}!e||!e[0]||this.store.addResource(e[0],n,r,i)}}}const $f=()=>({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:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),Y(t[1])&&(e.defaultValue=t[1]),Y(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const n=t[3]||t[2];Object.keys(n).forEach(r=>{e[r]=n[r]})}return e},interpolation:{escapeValue:!0,format:t=>t,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),kf=t=>(Y(t.ns)&&(t.ns=[t.ns]),Y(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),Y(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs?.indexOf?.("cimode")<0&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),typeof t.initImmediate=="boolean"&&(t.initAsync=t.initImmediate),t),hs=()=>{},Xw=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(n=>{typeof t[n]=="function"&&(t[n]=t[n].bind(t))})};class no extends Ha{constructor(e={},n){if(super(),this.options=kf(e),this.services={},this.logger=Vt,this.modules={external:[]},Xw(this),n&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,n),this;setTimeout(()=>{this.init(e,n)},0)}}init(e={},n){this.isInitializing=!0,typeof e=="function"&&(n=e,e={}),e.defaultNS==null&&e.ns&&(Y(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const r=$f();this.options={...r,...this.options,...kf(e)},this.options.interpolation={...r.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=r.overloadTranslationOptionHandler);const i=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?Vt.init(i(this.modules.logger),this.options):Vt.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=Gw;const u=new mf(this.options);this.store=new hf(this.options.resources,this.options);const f=this.services;f.logger=Vt,f.resourceStore=this.store,f.languageUtils=u,f.pluralResolver=new Hw(u,{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"),d&&(!this.options.interpolation.format||this.options.interpolation.format===r.interpolation.format)&&(f.formatter=i(d),f.formatter.init&&f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new bf(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new Jw(i(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",(_,...w)=>{this.emit(_,...w)}),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 qs(this.services,this.options),this.translator.on("*",(_,...w)=>{this.emit(_,...w)}),this.modules.external.forEach(_=>{_.init&&_.init(this)})}if(this.format=this.options.interpolation.format,n||(n=hs),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const d=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);d.length>0&&d[0]!=="dev"&&(this.options.lng=d[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(d=>{this[d]=(...u)=>this.store[d](...u)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(d=>{this[d]=(...u)=>(this.store[d](...u),this)});const c=Ei(),l=()=>{const d=(u,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(u,f)};if(this.languages&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initAsync?l():setTimeout(l,0),c}loadResources(e,n=hs){let r=n;const i=Y(e)?e:this.language;if(typeof e=="function"&&(r=e),!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(d=>{d!=="cimode"&&s.indexOf(d)<0&&s.push(d)})};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(e,n,r){const i=Ei();return typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n=void 0),e||(e=this.languages),n||(n=this.options.ns),r||(r=hs),this.services.backendConnector.reload(e,n,s=>{i.resolve(),r(s)}),i}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&U0.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!(["cimode","dev"].indexOf(e)>-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(e)<0&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,n){this.isLanguageChangingTo=e;const r=Ei();this.emit("languageChanging",e);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===e&&(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((...d)=>this.t(...d)),n&&n(c,(...d)=>this.t(...d))},a=c=>{!e&&!c&&this.services.languageDetector&&(c=[]);const l=Y(c)?c:c&&c[0],d=this.store.hasLanguageSomeTranslations(l)?l:this.services.languageUtils.getBestMatchFromCodes(Y(c)?[c]:c);d&&(this.language||i(d),this.translator.language||this.translator.changeLanguage(d),this.services.languageDetector?.cacheUserLanguage?.(d)),this.loadResources(d,u=>{s(u,d)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?a(this.services.languageDetector.detect()):!e&&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(e),r}getFixedT(e,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 d=this.options.keySeparator||".";let u;return l.keyPrefix&&Array.isArray(s)?u=s.map(f=>(typeof f=="function"&&(f=Rl(f,{...this.options,...a})),`${l.keyPrefix}${d}${f}`)):(typeof s=="function"&&(s=Rl(s,{...this.options,...a})),u=l.keyPrefix?`${l.keyPrefix}${d}${s}`:s),this.t(u,l)};return Y(e)?i.lng=e:i.lngs=e,i.ns=n,i.keyPrefix=r,i}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,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 d=this.services.backendConnector.state[`${c}|${l}`];return d===-1||d===0||d===2};if(n.precheck){const c=n.precheck(this,a);if(c!==void 0)return c}return!!(this.hasResourceBundle(r,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(r,e)&&(!i||a(s,e)))}loadNamespaces(e,n){const r=Ei();return this.options.ns?(Y(e)&&(e=[e]),e.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(e,n){const r=Ei();Y(e)&&(e=[e]);const i=this.options.preload||[],s=e.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(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const i=new Intl.Locale(e);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 mf($f());return e.toLowerCase().indexOf("-latn")>1?"ltr":n.indexOf(r.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},n){const r=new no(e,n);return r.createInstance=no.createInstance,r}cloneInstance(e={},n=hs){const r=e.forkResourceStore;r&&delete e.forkResourceStore;const i={...this.options,...e,isClone:!0},s=new no(i);if((e.debug!==void 0||e.prefix!==void 0)&&(s.logger=s.logger.clone(e)),["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,d)=>(l[d]={...this.store.data[d]},l[d]=Object.keys(l[d]).reduce((u,f)=>(u[f]={...l[d][f]},u),l[d]),l),{});s.store=new hf(c,i),s.services.resourceStore=s.store}return e.interpolation&&(s.services.interpolator=new bf(i)),s.translator=new qs(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 y=no.createInstance();y.createInstance;y.dir;y.init;y.loadResources;y.reloadResources;y.use;y.changeLanguage;y.getFixedT;const X=y.t;y.exists;y.setDefaultNamespace;y.hasLoadedNamespace;y.loadNamespaces;y.loadLanguages;var M0=t=>{const n={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...t},r=(s=>typeof s=="string"?s==="*"?()=>s:a=>s===a?a:null:typeof s=="function"?s:a=>s.includes(a)?a:null)(n.origin),i=(s=>typeof s=="function"?s:Array.isArray(s)?()=>s:()=>[])(n.allowMethods);return async function(a,c){function l(u,f){a.res.headers.set(u,f)}const d=await r(a.req.header("origin")||"",a);if(d&&l("Access-Control-Allow-Origin",d),n.credentials&&l("Access-Control-Allow-Credentials","true"),n.exposeHeaders?.length&&l("Access-Control-Expose-Headers",n.exposeHeaders.join(",")),a.req.method==="OPTIONS"){n.origin!=="*"&&l("Vary","Origin"),n.maxAge!=null&&l("Access-Control-Max-Age",n.maxAge.toString());const u=await i(a.req.header("origin")||"",a);u.length&&l("Access-Control-Allow-Methods",u.join(","));let f=n.allowHeaders;if(!f?.length){const g=a.req.header("Access-Control-Request-Headers");g&&(f=g.split(/\s*,\s*/))}return f?.length&&(l("Access-Control-Allow-Headers",f.join(",")),a.res.headers.append("Vary","Access-Control-Request-Headers")),a.res.headers.delete("Content-Length"),a.res.headers.delete("Content-Type"),new Response(null,{headers:a.res.headers,status:204,statusText:"No Content"})}await c(),n.origin!=="*"&&a.header("Vary","Origin",{append:!0})}};const Zw=o.z.object({page:o.z.string().min(0).optional().default("0").transform(t=>parseInt(t,10)).openapi({description:"The page number where 0 is the first page"}),per_page:o.z.string().min(1).optional().default("10").transform(t=>parseInt(t,10)).openapi({description:"The number of items per page"}),include_totals:o.z.string().optional().default("false").transform(t=>t==="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()}),di=o.z.object({created_at:o.z.string(),updated_at:o.z.string()}),q0=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()),F0=o.z.object({connection:o.z.string(),user_id:o.z.string(),provider:o.z.string(),isSocial:o.z.boolean(),access_token:o.z.string().optional(),access_token_secret:o.z.string().optional(),refresh_token:o.z.string().optional(),profileData:q0.optional()}),Va=o.z.object({email:o.z.string().optional().transform(t=>t&&t.toLowerCase()),username:o.z.string().optional(),phone_number:o.z.string().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()}),Fs=Va.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()}),Su=o.z.object({...Fs.shape,...di.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(F0).optional()}),Ft=Su,Yw=Va.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()),Qw="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let eb=(t=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)e+=Qw[n[t]&63];return e};const Hs=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(()=>eb()).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)."}),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()}),Jn=o.z.object({created_at:o.z.string(),updated_at:o.z.string(),...Hs.shape}),Vs=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."})}),Xn=o.z.object({id:o.z.string().openapi({description:"ID of the client grant."}),...Vs.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),tb=o.z.array(Xn),ui=o.z.object({x:o.z.number(),y:o.z.number()});var zu=(t=>(t.RICH_TEXT="RICH_TEXT",t.NEXT_BUTTON="NEXT_BUTTON",t.BACK_BUTTON="BACK_BUTTON",t.SUBMIT_BUTTON="SUBMIT_BUTTON",t.DIVIDER="DIVIDER",t.TEXT="TEXT",t.EMAIL="EMAIL",t.PASSWORD="PASSWORD",t.NUMBER="NUMBER",t.PHONE="PHONE",t.DATE="DATE",t.CHECKBOX="CHECKBOX",t.RADIO="RADIO",t.SELECT="SELECT",t.HIDDEN="HIDDEN",t.LEGAL="LEGAL",t))(zu||{}),Au=(t=>(t.BLOCK="BLOCK",t.FIELD="FIELD",t))(Au||{});const Ka=o.z.object({id:o.z.string(),category:o.z.nativeEnum(Au),type:o.z.nativeEnum(zu)}),H0=Ka.extend({category:o.z.literal("BLOCK"),type:o.z.literal("RICH_TEXT"),config:o.z.object({content:o.z.string()}).passthrough()}),V0=Ka.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()}),K0=Ka.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()}),G0=Ka.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()}),W0=o.z.object({id:o.z.string(),category:o.z.string(),type:o.z.string()}).passthrough(),J0=o.z.union([H0,V0,K0,G0,W0]);var X0=(t=>(t.STEP="STEP",t.FLOW="FLOW",t.CONDITION="CONDITION",t.ACTION="ACTION",t))(X0||{});const Z0=o.z.object({id:o.z.string(),type:o.z.literal("STEP"),coordinates:ui,alias:o.z.string().optional(),config:o.z.object({components:o.z.array(J0),next_node:o.z.string()}).passthrough()}),Y0=o.z.object({id:o.z.string(),type:o.z.literal("FLOW"),coordinates:ui,alias:o.z.string().optional(),config:o.z.object({flow_id:o.z.string(),next_node:o.z.string()})}),Q0=o.z.object({id:o.z.string(),type:o.z.string(),coordinates:ui}).passthrough(),em=o.z.union([Z0,Y0,Q0]),tm=o.z.object({next_node:o.z.string(),coordinates:ui}).passthrough(),nm=o.z.object({resume_flow:o.z.boolean().optional(),coordinates:ui}).passthrough(),rm=o.z.object({id:o.z.string(),name:o.z.string(),languages:o.z.object({primary:o.z.string()}).passthrough(),nodes:o.z.array(em),start:tm,ending:nm,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(),nb=rm.omit({id:!0,created_at:!0,updated_at:!0});var mt=(t=>(t.TOKEN="token",t.TOKEN_ID_TOKEN="token id_token",t.CODE="code",t))(mt||{}),Ct=(t=>(t.QUERY="query",t.FRAGMENT="fragment",t.FORM_POST="form_post",t.WEB_MESSAGE="web_message",t.SAML_POST="saml_post",t))(Ct||{}),Ga=(t=>(t.S256="S256",t.Plain="plain",t))(Ga||{});const go=o.z.object({client_id:o.z.string(),act_as:o.z.string().optional(),response_type:o.z.nativeEnum(mt).optional(),response_mode:o.z.nativeEnum(Ct).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(Ga).optional(),code_challenge:o.z.string().optional(),username:o.z.string().optional(),ui_locales:o.z.string().optional(),vendor_id:o.z.string().optional()}),Bl=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()}),Dr=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()}),Ks=o.z.object({id:o.z.string().optional(),name:o.z.string(),display_name:o.z.string().optional(),strategy:o.z.string(),options:Dr.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()}),ht=o.z.object({id:o.z.string(),created_at:o.z.string().transform(t=>t===null?"":t),updated_at:o.z.string().transform(t=>t===null?"":t)}).extend(Ks.shape),ro=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()}).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()}),Sn=o.z.object({created_at:o.z.string().nullable().transform(t=>t??""),updated_at:o.z.string().nullable().transform(t=>t??""),...ro.shape,id:o.z.string()}),rb=o.z.object({...Jn.shape,tenant:Sn,connections:o.z.array(ht)}),im=o.z.enum(["password_reset","email_verification","otp","authorization_code","oauth2_state","ticket"]),om=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:im,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()}),ib=o.z.object({...om.shape,created_at:o.z.string()}),Eu=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()}),sm=o.z.object({name:o.z.literal("txt"),record:o.z.string(),domain:o.z.string()}),xn=o.z.object({...Eu.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(sm)}).optional(),tls_policy:o.z.string().optional()}),ob=xn.extend({tenant_id:o.z.string()}),sb=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()}),am=o.z.object({id:o.z.string(),order:o.z.number().optional(),visible:o.z.boolean().optional().default(!0)}),xf=am.extend({category:o.z.literal("BLOCK").optional()}),Ci=am.extend({category:o.z.literal("FIELD").optional(),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional()}),cm=o.z.discriminatedUnion("type",[xf.extend({type:o.z.literal("RICH_TEXT"),config:o.z.object({content:o.z.string()})}),Ci.omit({sensitive:!0}).extend({type:o.z.literal("LEGAL"),config:o.z.object({text:o.z.string(),html:o.z.boolean().optional()})}),Ci.extend({type:o.z.literal("TEXT"),config:o.z.object({placeholder:o.z.string().optional(),multiline:o.z.boolean().optional()})}),xf.extend({type:o.z.literal("NEXT_BUTTON"),config:o.z.object({text:o.z.string().optional()})}),Ci.extend({type:o.z.literal("EMAIL"),config:o.z.object({label:o.z.string().optional(),placeholder:o.z.string().optional()})}),Ci.extend({type:o.z.literal("NUMBER"),config:o.z.object({label:o.z.string().optional(),placeholder:o.z.string().optional()})}),Ci.extend({type:o.z.literal("PHONE"),config:o.z.object({label:o.z.string().optional(),placeholder:o.z.string().optional()})})]),Gs=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(o.z.discriminatedUnion("type",[o.z.object({id:o.z.string(),type:o.z.literal("FLOW"),coordinates:o.z.object({x:o.z.number(),y:o.z.number()}),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()})}),o.z.object({id:o.z.string(),type:o.z.literal("ROUTER"),coordinates:o.z.object({x:o.z.number(),y:o.z.number()}),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()})}),o.z.object({id:o.z.string(),type:o.z.literal("STEP"),coordinates:o.z.object({x:o.z.number(),y:o.z.number()}),alias:o.z.string().min(1).max(150).optional(),config:o.z.object({components:o.z.array(cm),next_node:o.z.string().optional()})})])).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:o.z.object({x:o.z.number(),y:o.z.number()}).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:o.z.object({x:o.z.number(),y:o.z.number()}).optional(),resume_flow:o.z.boolean().optional()}).optional(),style:o.z.object({css:o.z.string().optional()}).optional()}).openapi({description:"Schema for flow-based forms (matches new JSON structure)"}),Br=o.z.object({...di.shape,...Gs.shape,id:o.z.string()}),lm=o.z.enum(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),dm=o.z.enum(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Wa={enabled:o.z.boolean().default(!1),synchronous:o.z.boolean().default(!1),priority:o.z.number().optional(),hook_id:o.z.string().optional()},ab=o.z.object({...Wa,trigger_id:lm,url:o.z.string()}),cb=o.z.object({...Wa,trigger_id:dm,form_id:o.z.string()}),ks=o.z.union([ab,cb]),lb=o.z.object({...Wa,trigger_id:lm,...di.shape,hook_id:o.z.string(),url:o.z.string()}),db=o.z.object({...Wa,trigger_id:dm,...di.shape,hook_id:o.z.string(),form_id:o.z.string()}),Lr=o.z.union([lb,db]),um=o.z.object({name:o.z.string().optional()}),pm=o.z.object({email:o.z.string().optional()}),Cu=o.z.object({organization_id:o.z.string().max(50),inviter:um,invitee:pm,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()}),io=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(Cu.shape),Nu=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()}),fm=o.z.object({keys:o.z.array(Nu)}),Ll=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())}),hm=o.z.object({csrf_token:o.z.string(),auth0Client:o.z.string().optional(),authParams:go,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(),login_completed:o.z.boolean().optional().default(!1)}).openapi({description:"This represents a login sesion"}),ub=o.z.object({...hm.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()}),te={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_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",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"},pb=o.z.string().refine(t=>Object.values(te).includes(t),{message:"Invalid log type"}),gm=o.z.object({name:o.z.string(),version:o.z.string(),env:o.z.object({node:o.z.string().optional()}).optional()}),mm=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()}),_m=o.z.object({type:pb,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:gm.optional(),log_id:o.z.string().optional(),location_info:mm.optional()}),Ws=o.z.object({..._m.shape,log_id:o.z.string()}),ym=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)}),fb=ym.extend({id:o.z.string(),created_at:o.z.string(),updated_at:o.z.string()}),wm=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")}),bm=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:wm.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")}),Ja=o.z.object({created_at:o.z.string(),updated_at:o.z.string(),authenticated_at:o.z.string(),last_interaction_at:o.z.string(),...bm.shape}),Ul=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"})});var St=(t=>(t.RefreshToken="refresh_token",t.AuthorizationCode="authorization_code",t.ClientCredential="client_credentials",t.Passwordless="passwordless",t.Password="password",t.OTP="http://auth0.com/oauth/grant-type/passwordless/otp",t))(St||{});const Iu=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 vm=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()}),$m=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()}),Kn=o.z.object({bold:o.z.boolean(),size:o.z.number()}),km=o.z.object({body_text:Kn,buttons_text:Kn,font_url:o.z.string(),input_labels:Kn,links:Kn,links_style:o.z.enum(["normal","underlined"]),reference_text_size:o.z.number(),subtitle:Kn,title:Kn}),xm=o.z.object({background_color:o.z.string(),background_image_url:o.z.string(),page_layout:o.z.enum(["center","left","right"])}),Sm=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"])}),zm=o.z.object({borders:vm,colors:$m,displayName:o.z.string(),fonts:km,page_background:xm,widget:Sm}),xs=zm.extend({themeId:o.z.string()}),Ss=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()}),zs=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()}),ju=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:wm,resource_servers:o.z.array(o.z.object({audience:o.z.string(),scopes:o.z.string()})),rotating:o.z.boolean()}),hb=o.z.object({created_at:o.z.string(),...ju.shape}),gb=o.z.object({to:o.z.string(),message:o.z.string()}),mb=o.z.object({name:o.z.string(),options:o.z.object({})}),Am=o.z.object({value:o.z.string(),description:o.z.string().optional()}),Em=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()}),Js=o.z.object({name:o.z.string(),identifier:o.z.string(),scopes:o.z.array(Am).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:Em.optional()}),Zn=o.z.object({id:o.z.string().optional(),...Js.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),_b=o.z.array(Zn),Cm=o.z.object({role_id:o.z.string(),resource_server_identifier:o.z.string(),permission_name:o.z.string()}),Nm=o.z.object({...Cm.shape,created_at:o.z.string()}),Im=o.z.array(Nm),jm=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()}),Pm=o.z.object({...jm.shape,tenant_id:o.z.string(),created_at:o.z.string().optional()}),yb=o.z.array(Pm),Om=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()}),Tm=o.z.array(Om),Rm=o.z.object({user_id:o.z.string(),role_id:o.z.string(),organization_id:o.z.string().optional()}),Bm=o.z.object({...Rm.shape,tenant_id:o.z.string(),created_at:o.z.string().optional()}),wb=o.z.array(Bm),Xs=o.z.object({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"})}),Yn=o.z.object({id:o.z.string().openapi({description:"The unique identifier of the role"}),...Xs.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),Zs=o.z.array(Yn),Lm=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(),Um=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"})}),Dm=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(),Ys=o.z.object({id:o.z.string().optional(),name:o.z.string().min(1).openapi({description:"The name of the organization"}),display_name:o.z.string().optional().openapi({description:"The display name of the organization"}),branding:Lm,metadata:o.z.record(o.z.any()).default({}).optional().openapi({description:"Custom metadata for the organization"}),enabled_connections:o.z.array(Um).default([]).optional().openapi({description:"List of enabled connections for the organization"}),token_quota:Dm}),zn=o.z.object({...Ys.shape,...di.shape,id:o.z.string()}),Mm=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"})}),bb=o.z.object({...Mm.shape,...di.shape,id:o.z.string()}),vb=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()});function $b(t){const[e,n]=t.split("|");if(!e||!n)throw new Error(`Invalid user_id: ${t}`);return{connection:e,id:n}}function kb(t){const{primary:e,secondaries:n,syncMethods:r=["create","update","remove","delete","set"]}=t,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 d=await c.apply(s,l),u=[];for(const f of n){const g=f.adapter[a];if(typeof g!="function")continue;const _=(async()=>{try{await g.apply(f.adapter,l)}catch(w){try{f.onError?f.onError(w,a,l):console.error(`Passthrough adapter: secondary write failed for ${a}:`,w)}catch(k){console.error(`Passthrough adapter: onError handler threw for ${a}:`,k)}}})();f.blocking&&u.push(_)}return u.length>0&&await Promise.all(u),d}:c.bind(s)}};return new Proxy(e,i)}function xb(t){return t}const Sf={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:16},buttons_text:{bold:!1,size:16},font_url:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Regular.woff2",input_labels:{bold:!1,size:14},links:{bold:!1,size:16},links_style:"normal",reference_text_size:16,subtitle:{bold:!1,size:18},title:{bold:!0,size:24}},page_background:{background_color:"#F8F9FB",background_image_url:"https://assets.sesamy.com/images/login-bg.jpg",page_layout:"center"},widget:{header_text_alignment:"center",logo_height:36,logo_position:"center",logo_url:"https://assets.sesamy.com/static/images/sesamy/logos/sesamy_logo_black.svg",social_buttons_layout:"bottom"}};function Dl(t,e){const n=structuredClone(t);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,e)}const Sb=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:["auth:read"]}],responses:{200:{content:{"application/json":{schema:xs}},description:"Default theme settings"}}}),async t=>{const e=await t.env.data.themes.get(t.var.tenant_id,"default");return e?t.json(e):t.json(Sf)}).openapi(o.createRoute({tags:["branding"],method:"patch",path:"/default",request:{body:{content:{"application/json":{schema:xs.deepPartial()}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:xs}},description:"Updated theme settings"}}}),async t=>{const e=t.req.valid("json"),n=await t.env.data.themes.get(t.var.tenant_id,"default");if(n){const r=Dl(n,e);await t.env.data.themes.update(t.var.tenant_id,"default",r);const i=await t.env.data.themes.get(t.var.tenant_id,"default");return t.json(i)}else{const r=Dl(Sf,e),i=await t.env.data.themes.create(t.var.tenant_id,r);return t.json(i)}}),zb={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"}},Ab=new o.OpenAPIHono().openapi(o.createRoute({tags:["branding"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Bl}},description:"Branding settings"}}}),async t=>{const e=await t.env.data.branding.get(t.var.tenant_id);return e?t.json(e):t.json(zb)}).openapi(o.createRoute({tags:["branding"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Bl.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const e=t.req.valid("json");return await t.env.data.branding.set(t.var.tenant_id,e),t.text("OK")}).route("/themes",Sb);var v=class extends Error{res;status;constructor(t=500,e){super(e?.message,{cause:e?.cause}),this.res=e?.res,this.status=t}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}};const Eb={};var Ml=null;function Cb(t){try{return crypto.getRandomValues(new Uint8Array(t))}catch{}try{return Eb.randomBytes(t)}catch{}if(!Ml)throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative");return Ml(t)}function Nb(t){Ml=t}function Pu(t,e){if(t=t||Ou,typeof t!="number")throw Error("Illegal arguments: "+typeof t+", "+typeof e);t<4?t=4:t>31&&(t=31);var n=[];return n.push("$2b$"),t<10&&n.push("0"),n.push(t.toString()),n.push("$"),n.push(Qs(Cb(mo),mo)),n.join("")}function qm(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="function"&&(n=t,t=void 0),typeof t>"u")t=Ou;else if(typeof t!="number")throw Error("illegal arguments: "+typeof t);function r(i){zt(function(){try{i(null,Pu(t))}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 Fm(t,e){if(typeof e>"u"&&(e=Ou),typeof e=="number"&&(e=Pu(e)),typeof t!="string"||typeof e!="string")throw Error("Illegal arguments: "+typeof t+", "+typeof e);return ql(t,e)}function Hm(t,e,n,r){function i(s){typeof t=="string"&&typeof e=="number"?qm(e,function(a,c){ql(t,c,s,r)}):typeof t=="string"&&typeof e=="string"?ql(t,e,s,r):zt(s.bind(this,Error("Illegal arguments: "+typeof t+", "+typeof e)))}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 Vm(t,e){for(var n=t.length^e.length,r=0;r<t.length;++r)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}function Ib(t,e){if(typeof t!="string"||typeof e!="string")throw Error("Illegal arguments: "+typeof t+", "+typeof e);return e.length!==60?!1:Vm(Fm(t,e.substring(0,e.length-31)),e)}function jb(t,e,n,r){function i(s){if(typeof t!="string"||typeof e!="string"){zt(s.bind(this,Error("Illegal arguments: "+typeof t+", "+typeof e)));return}if(e.length!==60){zt(s.bind(this,null,!1));return}Hm(t,e.substring(0,29),function(a,c){a?s(a):s(null,Vm(c,e))},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 Pb(t){if(typeof t!="string")throw Error("Illegal arguments: "+typeof t);return parseInt(t.split("$")[2],10)}function Ob(t){if(typeof t!="string")throw Error("Illegal arguments: "+typeof t);if(t.length!==60)throw Error("Illegal hash length: "+t.length+" != 60");return t.substring(0,29)}function Tb(t){if(typeof t!="string")throw Error("Illegal arguments: "+typeof t);return Km(t)>72}var zt=typeof setImmediate=="function"?setImmediate:typeof scheduler=="object"&&typeof scheduler.postTask=="function"?scheduler.postTask.bind(scheduler):setTimeout;function Km(t){for(var e=0,n=0,r=0;r<t.length;++r)n=t.charCodeAt(r),n<128?e+=1:n<2048?e+=2:(n&64512)===55296&&(t.charCodeAt(r+1)&64512)===56320?(++r,e+=4):e+=3;return e}function Rb(t){for(var e=0,n,r,i=new Array(Km(t)),s=0,a=t.length;s<a;++s)n=t.charCodeAt(s),n<128?i[e++]=n:n<2048?(i[e++]=n>>6|192,i[e++]=n&63|128):(n&64512)===55296&&((r=t.charCodeAt(s+1))&64512)===56320?(n=65536+((n&1023)<<10)+(r&1023),++s,i[e++]=n>>18|240,i[e++]=n>>12&63|128,i[e++]=n>>6&63|128,i[e++]=n&63|128):(i[e++]=n>>12|224,i[e++]=n>>6&63|128,i[e++]=n&63|128);return i}var Er="./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),$n=[-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 Qs(t,e){var n=0,r=[],i,s;if(e<=0||e>t.length)throw Error("Illegal len: "+e);for(;n<e;){if(i=t[n++]&255,r.push(Er[i>>2&63]),i=(i&3)<<4,n>=e){r.push(Er[i&63]);break}if(s=t[n++]&255,i|=s>>4&15,r.push(Er[i&63]),i=(s&15)<<2,n>=e){r.push(Er[i&63]);break}s=t[n++]&255,i|=s>>6&3,r.push(Er[i&63]),r.push(Er[s&63])}return r.join("")}function Gm(t,e){var n=0,r=t.length,i=0,s=[],a,c,l,d,u,f;if(e<=0)throw Error("Illegal len: "+e);for(;n<r-1&&i<e&&(f=t.charCodeAt(n++),a=f<$n.length?$n[f]:-1,f=t.charCodeAt(n++),c=f<$n.length?$n[f]:-1,!(a==-1||c==-1||(u=a<<2>>>0,u|=(c&48)>>4,s.push(String.fromCharCode(u)),++i>=e||n>=r)||(f=t.charCodeAt(n++),l=f<$n.length?$n[f]:-1,l==-1)||(u=(c&15)<<4>>>0,u|=(l&60)>>2,s.push(String.fromCharCode(u)),++i>=e||n>=r)));)f=t.charCodeAt(n++),d=f<$n.length?$n[f]:-1,u=(l&3)<<6>>>0,u|=d,s.push(String.fromCharCode(u)),++i;var g=[];for(n=0;n<i;n++)g.push(s[n].charCodeAt(0));return g}var mo=16,Ou=10,Bb=16,Lb=100,zf=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],Af=[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],Wm=[1332899944,1700884034,1701343084,1684370003,1668446532,1869963892];function _o(t,e,n,r){var i,s=t[e],a=t[e+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],t[e]=a^n[Bb+1],t[e+1]=s,t}function Ir(t,e){for(var n=0,r=0;n<4;++n)r=r<<8|t[e]&255,e=(e+1)%t.length;return{key:r,offp:e}}function Ef(t,e,n){for(var r=0,i=[0,0],s=e.length,a=n.length,c,l=0;l<s;l++)c=Ir(t,r),r=c.offp,e[l]=e[l]^c.key;for(l=0;l<s;l+=2)i=_o(i,0,e,n),e[l]=i[0],e[l+1]=i[1];for(l=0;l<a;l+=2)i=_o(i,0,e,n),n[l]=i[0],n[l+1]=i[1]}function Ub(t,e,n,r){for(var i=0,s=[0,0],a=n.length,c=r.length,l,d=0;d<a;d++)l=Ir(e,i),i=l.offp,n[d]=n[d]^l.key;for(i=0,d=0;d<a;d+=2)l=Ir(t,i),i=l.offp,s[0]^=l.key,l=Ir(t,i),i=l.offp,s[1]^=l.key,s=_o(s,0,n,r),n[d]=s[0],n[d+1]=s[1];for(d=0;d<c;d+=2)l=Ir(t,i),i=l.offp,s[0]^=l.key,l=Ir(t,i),i=l.offp,s[1]^=l.key,s=_o(s,0,n,r),r[d]=s[0],r[d+1]=s[1]}function Cf(t,e,n,r,i){var s=Wm.slice(),a=s.length,c;if(n<4||n>31)if(c=Error("Illegal number of rounds (4-31): "+n),r){zt(r.bind(this,c));return}else throw c;if(e.length!==mo)if(c=Error("Illegal salt length: "+e.length+" != "+mo),r){zt(r.bind(this,c));return}else throw c;n=1<<n>>>0;var l,d,u=0,f;typeof Int32Array=="function"?(l=new Int32Array(zf),d=new Int32Array(Af)):(l=zf.slice(),d=Af.slice()),Ub(e,t,l,d);function g(){if(i&&i(u/n),u<n)for(var w=Date.now();u<n&&(u=u+1,Ef(t,l,d),Ef(e,l,d),!(Date.now()-w>Lb)););else{for(u=0;u<64;u++)for(f=0;f<a>>1;f++)_o(s,f<<1,l,d);var k=[];for(u=0;u<a;u++)k.push((s[u]>>24&255)>>>0),k.push((s[u]>>16&255)>>>0),k.push((s[u]>>8&255)>>>0),k.push((s[u]&255)>>>0);if(r){r(null,k);return}else return k}r&&zt(g)}if(typeof r<"u")g();else for(var _;;)if(typeof(_=g())<"u")return _||[]}function ql(t,e,n,r){var i;if(typeof t!="string"||typeof e!="string")if(i=Error("Invalid string / salt: Not a string"),n){zt(n.bind(this,i));return}else throw i;var s,a;if(e.charAt(0)!=="$"||e.charAt(1)!=="2")if(i=Error("Invalid salt version: "+e.substring(0,2)),n){zt(n.bind(this,i));return}else throw i;if(e.charAt(2)==="$")s="\0",a=3;else{if(s=e.charAt(2),s!=="a"&&s!=="b"&&s!=="y"||e.charAt(3)!=="$")if(i=Error("Invalid salt revision: "+e.substring(2,4)),n){zt(n.bind(this,i));return}else throw i;a=4}if(e.charAt(a+2)>"$")if(i=Error("Missing salt rounds"),n){zt(n.bind(this,i));return}else throw i;var c=parseInt(e.substring(a,a+1),10)*10,l=parseInt(e.substring(a+1,a+2),10),d=c+l,u=e.substring(a+3,a+25);t+=s>="a"?"\0":"";var f=Rb(t),g=Gm(u,mo);function _(w){var k=[];return k.push("$2"),s>="a"&&k.push(s),k.push("$"),d<10&&k.push("0"),k.push(d.toString()),k.push("$"),k.push(Qs(g,g.length)),k.push(Qs(w,Wm.length*4-1)),k.join("")}if(typeof n>"u")return _(Cf(f,g,d));Cf(f,g,d,function(w,k){w?n(w,null):n(null,_(k))},r)}function Db(t,e){return Qs(t,e)}function Mb(t,e){return Gm(t,e)}const Pn={setRandomFallback:Nb,genSaltSync:Pu,genSalt:qm,hashSync:Fm,hash:Hm,compareSync:Ib,compare:jb,getRounds:Pb,getSalt:Ob,truncates:Tb,encodeBase64:Db,decodeBase64:Mb},qb="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let Fb=t=>crypto.getRandomValues(new Uint8Array(t)),Hb=(t,e,n)=>{let r=(2<<Math.log2(t.length-1))-1,i=-~(1.6*r*e/t.length);return(s=e)=>{let a="";for(;;){let c=n(i),l=i|0;for(;l--;)if(a+=t[c[l]&r]||"",a.length>=s)return a}}},Jm=(t,e=21)=>Hb(t,e|0,Fb),pe=(t=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)e+=qb[n[t]&63];return e};const Vb=24;function Xa(){return Jm("0123456789abcdef",Vb)()}function gs(t){if(!t.includes("|"))return console.error("Invalid user_id format"),t;const[,e]=t.split("|");return e}function Kb(t){return async(e,n)=>{if(!n.email||!n.email_verified)return t.users.create(e,n);const r=await tc({userAdapter:t.users,tenant_id:e,email:n.email});if(!r)return t.users.create(e,n);await t.users.create(e,{...n,linked_to:r.user_id});const i=await t.users.get(e,r.user_id);if(!i)throw new Error("Failed to fetch primary user after linking");return i}}var Gb={deno:"Deno",bun:"Bun",workerd:"Cloudflare-Workers",node:"Node.js"},Xm=()=>{const t=globalThis;if(typeof navigator<"u"&&typeof navigator.userAgent=="string"){for(const[n,r]of Object.entries(Gb))if(Wb(r))return n}return typeof t?.EdgeRuntime=="string"?"edge-light":t?.fastly!==void 0?"fastly":t?.process?.release?.name==="node"?"node":"other"},Wb=t=>navigator.userAgent.startsWith(t);function Zm(t,e){Xm()==="workerd"&&t.executionCtx.waitUntil(e)}function Jb(t){return[...t].reduce((e,[n,r])=>({...e,[n]:r}),{})}async function ie(t,e,n){const r={};if(t.req.raw?.headers){const s=Jb(t.req.raw.headers);for(const[a,c]of Object.entries(s))r[a.toLowerCase()]=c}const i=async()=>{let s;if(t.env.data.geo)try{s=await t.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:t.var.ip,user_agent:t.var.useragent||"",auth0_client:t.var.auth0_client,date:new Date().toISOString(),details:{request:{method:t.req.method,path:t.req.path,qs:t.req.queries(),body:n.body||t.var.body||""},...n.response&&{response:n.response}},isMobile:!1,client_id:t.var.client_id,client_name:"",user_id:n.userId||t.var.user_id||"",hostname:t.req.header("host")||"",user_name:t.var.username||"",connection_id:"",connection:n.connection||t.var.connection||"",strategy:n.strategy||"",strategy_type:n.strategy_type||"",audience:n.audience||"",scope:n.scope||"",location_info:s};await t.env.data.logs.create(e,a)};n.waitForCompletion?await i():Zm(t,i())}class ea{constructor(e,n){this.value=e,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(e){return new ea(Math.round(this.milliseconds()*e),"ms")}}class Xb{hash;constructor(e){this.hash=e}async verify(e,n,r){const i=await crypto.subtle.importKey("spki",e,{name:"RSASSA-PKCS1-v1_5",hash:this.hash},!1,["verify"]);return await crypto.subtle.verify("RSASSA-PKCS1-v1_5",i,n,r)}async sign(e,n){const r=await crypto.subtle.importKey("pkcs8",e,{name:"RSASSA-PKCS1-v1_5",hash:this.hash},!1,["sign"]);return await crypto.subtle.sign("RSASSA-PKCS1-v1_5",r,n)}async generateKeyPair(e){const n=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",hash:this.hash,modulusLength:e??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 Ym(t){return await crypto.subtle.digest("SHA-256",t)}const Nf="0123456789abcdef";function Fl(t){const e=new Uint8Array(t);let n="";for(let r=0;r<e.length;r++){const i=e[r]>>4;n+=Nf[i];const s=e[r]&15;n+=Nf[s]}return n}class Qm{alphabet;padding;decodeMap=new Map;constructor(e,n){if(e.length!==32)throw new Error("Invalid alphabet");if(this.alphabet=e,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<e.length;r++)this.decodeMap.set(e[r],r)}encode(e,n){let r="",i=0,s=0;for(let c=0;c<e.length;c++)for(i=i<<8|e[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(e,n){const r=n?.strict??!0,i=Math.ceil(e.length/8),s=[];for(let a=0;a<i;a++){let c=0;const l=[];for(let u=0;u<8;u++){const f=e[a*8+u];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 g=this.decodeMap.get(f)??null;if(g===null)throw new Error(`Invalid character: ${f}`);l.push(g)}if(c===8||c===7||c===5||c===2)throw new Error("Invalid padding");const d=(l[0]<<3)+(l[1]>>2);if(s.push(d),c<6){const u=((l[1]&3)<<6)+(l[2]<<1)+(l[3]>>4);s.push(u)}if(c<4){const u=((l[3]&255)<<4)+(l[4]>>1);s.push(u)}if(c<3){const u=((l[4]&1)<<7)+(l[5]<<2)+(l[6]>>3);s.push(u)}if(c<1){const u=((l[6]&7)<<5)+l[7];s.push(u)}}return Uint8Array.from(s)}}new Qm("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");new Qm("0123456789ABCDEFGHIJKLMNOPQRSTUV");class e_{alphabet;padding;decodeMap=new Map;constructor(e,n){if(e.length!==64)throw new Error("Invalid alphabet");if(this.alphabet=e,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<e.length;r++)this.decodeMap.set(e[r],r)}encode(e,n){let r="",i=0,s=0;for(let c=0;c<e.length;c++)for(i=i<<8|e[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(e,n){const r=n?.strict??!0,i=Math.ceil(e.length/4),s=[];for(let a=0;a<i;a++){let c=0,l=0;for(let d=0;d<4;d++){const u=e[a*4+d];if(u==="="){if(a+1!==i)throw new Error(`Invalid character: ${u}`);c+=1;continue}if(u===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const f=this.decodeMap.get(u)??null;if(f===null)throw new Error(`Invalid character: ${u}`);l+=f<<6*(3-d)}s.push(l>>16&255),c<2&&s.push(l>>8&255),c<1&&s.push(l&255)}return Uint8Array.from(s)}}const Zb=new e_("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),tr=new e_("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");async function If(t,e,n,r){const i={alg:t,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=tr.encode(a.encode(JSON.stringify(i)),{includePadding:!1}),l=tr.encode(a.encode(JSON.stringify(s)),{includePadding:!1}),d=a.encode([c,l].join(".")),u=await Qb(t).sign(e,d),f=tr.encode(new Uint8Array(u),{includePadding:!1});return[c,l,f].join(".")}function Yb(t){const e=t.split(".");return e.length!==3?null:e}function Mo(t){const e=Yb(t);if(!e)return null;const n=new TextDecoder,r=tr.decode(e[0],{strict:!1}),i=tr.decode(e[1],{strict:!1}),s=JSON.parse(n.decode(r));if(typeof s!="object"||s===null||!("alg"in s)||!ev(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:t,header:{...s,typ:"JWT",alg:s.alg},payload:{...a},parts:e,...c}}function Qb(t){return new Xb(tv[t])}function ev(t){return typeof t!="string"?!1:["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512","PS256","PS384","PS512"].includes(t)}const tv={RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512"};function nv(){const t=new Uint8Array(32);return crypto.getRandomValues(t),tr.encode(t,{includePadding:!1})}function rv(t){try{const n=/-----BEGIN (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----([^-]*)-----END (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----/.exec(t);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{t=t.replace(/./g,"\0")}}async function iv(t,e){if(e==="plain")return t;const n=new TextEncoder().encode(t),r=await Ym(n);return tr.encode(new Uint8Array(r),{includePadding:!1})}const ms=300,Za=720*60*60,or=1440*60,ov="auth-token",As=1800*1e3,Hl=10080*60*1e3,sv=300,av=300,cv=1800*1e3,lv=1800*1e3,dv=1440*60*1e3;function t_(t,e,n){const r=[];return r.push([encodeURIComponent(t),encodeURIComponent(e)]),n?.domain!==void 0&&r.push(["Domain",n.domain]),n?.expires!==void 0&&r.push(["Expires",n.expires.toUTCString()]),n?.httpOnly&&r.push(["HttpOnly"]),n?.maxAge!==void 0&&r.push(["Max-Age",n.maxAge.toString()]),n?.path!==void 0&&r.push(["Path",n.path]),n?.sameSite==="lax"&&r.push(["SameSite","Lax"]),n?.sameSite==="none"&&r.push(["SameSite","None"]),n?.sameSite==="strict"&&r.push(["SameSite","Strict"]),n?.secure&&r.push(["Secure"]),r.map(i=>i.join("=")).join("; ")}function uv(t){const e=new Map,n=t.split("; ");for(const r of n){const i=r.split("="),s=i[0],a=i[1]??"";s&&e.set(decodeURIComponent(s),decodeURIComponent(a))}return e}function Tu(t){return`${t}-${ov}`}function n_(t){if(!t)return;const[e]=t.split(":");if(!e||e==="localhost"||/^(\d{1,3}\.){3}\d{1,3}$/.test(e))return;const n=e.split(".");return n.length>2?`.${n.slice(-2).join(".")}`:`.${e}`}function Wr(t,e){return e?uv(e).get(Tu(t)):void 0}function r_(t,e){return t_(Tu(t),"",{path:"/",httpOnly:!0,secure:!0,maxAge:0,sameSite:"none",domain:e?n_(e):void 0})}function ta(t,e,n){return t_(Tu(t),e,{path:"/",httpOnly:!0,secure:!0,maxAge:Za,sameSite:"none",domain:n?n_(n):void 0})}class B extends v{constructor(e,n){super(e,{message:JSON.stringify(n),res:new Response(JSON.stringify(n),{status:e,headers:{"Content-Type":"application/json"}})})}}var pv=Object.defineProperty,fv=(t,e,n)=>e in t?pv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Mr=(t,e,n)=>fv(t,typeof e!="symbol"?e+"":e,n);const He=o.z.object({"#text":o.z.string()}),hv=o.z.object({"#text":o.z.string(),"@_xmlns:saml":o.z.string().optional()});o.z.object({"samlp:AuthnRequest":o.z.object({"saml:Issuer":hv,"@_xmlns:samlp":o.z.string(),"@_xmlns:saml":o.z.string().optional(),"@_ForceAuthn":o.z.string().transform(t=>t.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(He)}))})),":@":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(He)}),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 gv=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()})}),mv=o.z.object({"ds:Transform":o.z.array(o.z.any()),":@":o.z.object({"@_Algorithm":o.z.string()})}),jf=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(mv)}),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(He)})])),":@":o.z.object({"@_URI":o.z.string().optional()}).optional()})]))}),o.z.object({"ds:SignatureValue":o.z.array(He)}),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(He)}),o.z.object({"ds:Exponent":o.z.array(He)})]))}))}),o.z.object({"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(He)}))}),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(He)}),o.z.object({"ds:Exponent":o.z.array(He)})]))})),"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(He)}))})]))})])),":@":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(He)}),jf,o.z.object({"samlp:Status":o.z.array(o.z.object({"samlp:StatusCode":o.z.array(He),":@":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(He)}),jf,o.z.object({"saml:Subject":o.z.array(o.z.union([o.z.object({"saml:NameID":o.z.array(He),":@":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(He)}))})),":@":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(He)}))})),":@":o.z.object({"@_AuthnInstant":o.z.string(),"@_SessionIndex":o.z.string(),"@_SessionNotOnOrAfter":o.z.string()})}),o.z.object({"saml:AttributeStatement":o.z.array(gv)})])),":@":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 _v={};(function(t){const e=":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=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+e+"]["+n+"]*",i=new RegExp("^"+r+"$"),s=function(c,l){const d=[];let u=l.exec(c);for(;u;){const f=[];f.startIndex=l.lastIndex-u[0].length;const g=u.length;for(let _=0;_<g;_++)f.push(u[_]);d.push(f),u=l.exec(c)}return d},a=function(c){const l=i.exec(c);return!(l===null||typeof l>"u")};t.isExist=function(c){return typeof c<"u"},t.isEmptyObject=function(c){return Object.keys(c).length===0},t.merge=function(c,l,d){if(l){const u=Object.keys(l),f=u.length;for(let g=0;g<f;g++)d==="strict"?c[u[g]]=[l[u[g]]]:c[u[g]]=l[u[g]]}},t.getValue=function(c){return t.isExist(c)?c:""},t.isName=a,t.getAllMatches=s,t.nameRegexp=r})(_v);function yv(t){return typeof t=="function"?t:Array.isArray(t)?e=>{for(const n of t)if(typeof n=="string"&&e===n||n instanceof RegExp&&n.test(e))return!0}:()=>!1}var wv=yv;const bv=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@hono/zod-openapi"),Y=t=>typeof t=="string",Ci=()=>{let t,e;const n=new Promise((r,i)=>{t=r,e=i});return n.resolve=t,n.reject=e,n},df=t=>t==null?"":""+t,jw=(t,e,n)=>{t.forEach(r=>{e[r]&&(n[r]=e[r])})},Pw=/###/g,uf=t=>t&&t.indexOf("###")>-1?t.replace(Pw,"."):t,pf=t=>!t||Y(t),no=(t,e,n)=>{const r=Y(e)?e.split("."):e;let i=0;for(;i<r.length-1;){if(pf(t))return{};const s=uf(r[i]);!t[s]&&n&&(t[s]=new n),Object.prototype.hasOwnProperty.call(t,s)?t=t[s]:t={},++i}return pf(t)?{}:{obj:t,k:uf(r[i])}},ff=(t,e,n)=>{const{obj:r,k:i}=no(t,e,Object);if(r!==void 0||e.length===1){r[i]=n;return}let s=e[e.length-1],a=e.slice(0,e.length-1),c=no(t,a,Object);for(;c.obj===void 0&&a.length;)s=`${a[a.length-1]}.${s}`,a=a.slice(0,a.length-1),c=no(t,a,Object),c?.obj&&typeof c.obj[`${c.k}.${s}`]<"u"&&(c.obj=void 0);c.obj[`${c.k}.${s}`]=n},Ow=(t,e,n,r)=>{const{obj:i,k:s}=no(t,e,Object);i[s]=i[s]||[],i[s].push(n)},Ds=(t,e)=>{const{obj:n,k:r}=no(t,e);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},Tw=(t,e,n)=>{const r=Ds(t,n);return r!==void 0?r:Ds(e,n)},L0=(t,e,n)=>{for(const r in e)r!=="__proto__"&&r!=="constructor"&&(r in t?Y(t[r])||t[r]instanceof String||Y(e[r])||e[r]instanceof String?n&&(t[r]=e[r]):L0(t[r],e[r],n):t[r]=e[r]);return t},Ar=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Rw={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const Bw=t=>Y(t)?t.replace(/[&<>"'\/]/g,e=>Rw[e]):t;class Lw{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const n=this.regExpMap.get(e);if(n!==void 0)return n;const r=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,r),this.regExpQueue.push(e),r}}const Uw=[" ",",","?","!",";"],Dw=new Lw(20),Mw=(t,e,n)=>{e=e||"",n=n||"";const r=Uw.filter(a=>e.indexOf(a)<0&&n.indexOf(a)<0);if(r.length===0)return!0;const i=Dw.getRegExp(`(${r.map(a=>a==="?"?"\\?":a).join("|")})`);let s=!i.test(t);if(!s){const a=t.indexOf(n);a>0&&!i.test(t.substring(0,a))&&(s=!0)}return s},Tl=(t,e,n=".")=>{if(!t)return;if(t[e])return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;const r=e.split(n);let i=t;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},go=t=>t?.replace("_","-"),qw={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){console?.[t]?.apply?.(console,e)}};class Ms{constructor(e,n={}){this.init(e,n)}init(e,n={}){this.prefix=n.prefix||"i18next:",this.logger=e||qw,this.options=n,this.debug=n.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,n,r,i){return i&&!this.debug?null:(Y(e[0])&&(e[0]=`${r}${this.prefix} ${e[0]}`),this.logger[n](e))}create(e){return new Ms(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Ms(this.logger,e)}}var Vt=new Ms;class Ha{constructor(){this.observers={}}on(e,n){return e.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(e,n){if(this.observers[e]){if(!n){delete this.observers[e];return}this.observers[e].delete(n)}}emit(e,...n){this.observers[e]&&Array.from(this.observers[e].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,[e,...n])})}}class hf extends Ha{constructor(e,n={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){const n=this.options.ns.indexOf(e);n>-1&&this.options.ns.splice(n,1)}getResource(e,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;e.indexOf(".")>-1?c=e.split("."):(c=[e,n],r&&(Array.isArray(r)?c.push(...r):Y(r)&&s?c.push(...r.split(s)):c.push(r)));const l=Ds(this.data,c);return!l&&!n&&!r&&e.indexOf(".")>-1&&(e=c[0],n=c[1],r=c.slice(2).join(".")),l||!a||!Y(r)?l:Tl(this.data?.[e]?.[n],r,s)}addResource(e,n,r,i,s={silent:!1}){const a=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator;let c=[e,n];r&&(c=c.concat(a?r.split(a):r)),e.indexOf(".")>-1&&(c=e.split("."),i=n,n=c[1]),this.addNamespaces(n),ff(this.data,c,i),s.silent||this.emit("added",e,n,r,i)}addResources(e,n,r,i={silent:!1}){for(const s in r)(Y(r[s])||Array.isArray(r[s]))&&this.addResource(e,n,s,r[s],{silent:!0});i.silent||this.emit("added",e,n,r)}addResourceBundle(e,n,r,i,s,a={silent:!1,skipCopy:!1}){let c=[e,n];e.indexOf(".")>-1&&(c=e.split("."),i=r,r=n,n=c[1]),this.addNamespaces(n);let l=Ds(this.data,c)||{};a.skipCopy||(r=JSON.parse(JSON.stringify(r))),i?L0(l,r,s):l={...l,...r},ff(this.data,c,l),a.silent||this.emit("added",e,n,r)}removeResourceBundle(e,n){this.hasResourceBundle(e,n)&&delete this.data[e][n],this.removeNamespaces(n),this.emit("removed",e,n)}hasResourceBundle(e,n){return this.getResource(e,n)!==void 0}getResourceBundle(e,n){return n||(n=this.options.defaultNS),this.getResource(e,n)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const n=this.getDataByLanguage(e);return!!(n&&Object.keys(n)||[]).find(i=>n[i]&&Object.keys(n[i]).length>0)}toJSON(){return this.data}}var U0={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,n,r,i){return t.forEach(s=>{e=this.processors[s]?.process(e,n,r,i)??e}),e}};const D0=Symbol("i18next/PATH_KEY");function Fw(){const t=[],e=Object.create(null);let n;return e.get=(r,i)=>(n?.revoke?.(),i===D0?t:(t.push(i),n=Proxy.revocable(r,e),n.proxy)),Proxy.revocable(Object.create(null),e).proxy}function Rl(t,e){const{[D0]:n}=t(Fw());return n.join(e?.keySeparator??".")}const gf={},cl=t=>!Y(t)&&typeof t!="boolean"&&typeof t!="number";class qs extends Ha{constructor(e,n={}){super(),jw(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=Vt.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,n={interpolation:{}}){const r={...n};if(e==null)return!1;const i=this.resolve(e,r);if(i?.res===void 0)return!1;const s=cl(i.res);return!(r.returnObjects===!1&&s)}extractFromKey(e,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&&e.indexOf(r)>-1,c=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!Mw(e,r,i);if(a&&!c){const l=e.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:e,namespaces:Y(s)?[s]:s};const d=e.split(r);(r!==i||r===i&&this.options.ns.indexOf(d[0])>-1)&&(s=d.shift()),e=d.join(i)}return{key:e,namespaces:Y(s)?[s]:s}}translate(e,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={}),e==null)return"";typeof e=="function"&&(e=Rl(e,{...this.options,...i})),Array.isArray(e)||(e=[String(e)]);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(e[e.length-1],i),d=l[l.length-1];let u=i.nsSeparator!==void 0?i.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const f=i.lng||this.language,g=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(f?.toLowerCase()==="cimode")return g?s?{res:`${d}${u}${c}`,usedKey:c,exactUsedKey:c,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(i)}:`${d}${u}${c}`:s?{res:c,usedKey:c,exactUsedKey:c,usedLng:f,usedNS:d,usedParams:this.getUsedParamsDetails(i)}:c;const _=this.resolve(e,i);let w=_?.res;const k=_?.usedKey||c,z=_?.exactUsedKey||c,N=["[object Number]","[object Function]","[object RegExp]"],I=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,S=!this.i18nFormat||this.i18nFormat.handleAsObject,E=i.count!==void 0&&!Y(i.count),P=qs.hasDefaultValue(i),G=E?this.pluralResolver.getSuffix(f,i.count,i):"",Z=i.ordinal&&E?this.pluralResolver.getSuffix(f,i.count,{ordinal:!1}):"",W=E&&!i.ordinal&&i.count===0,M=W&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${G}`]||i[`defaultValue${Z}`]||i.defaultValue;let ce=w;S&&!w&&P&&(ce=M);const le=cl(ce),fe=Object.prototype.toString.apply(ce);if(S&&ce&&le&&N.indexOf(fe)<0&&!(Y(I)&&Array.isArray(ce))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const $e=this.options.returnedObjectHandler?this.options.returnedObjectHandler(k,ce,{...i,ns:l}):`key '${c} (${this.language})' returned an object instead of string.`;return s?(_.res=$e,_.usedParams=this.getUsedParamsDetails(i),_):$e}if(a){const $e=Array.isArray(ce),be=$e?[]:{},sn=$e?z:k;for(const Be in ce)if(Object.prototype.hasOwnProperty.call(ce,Be)){const Qe=`${sn}${a}${Be}`;P&&!w?be[Be]=this.translate(Qe,{...i,defaultValue:cl(M)?M[Be]:void 0,joinArrays:!1,ns:l}):be[Be]=this.translate(Qe,{...i,joinArrays:!1,ns:l}),be[Be]===Qe&&(be[Be]=ce[Be])}w=be}}else if(S&&Y(I)&&Array.isArray(w))w=w.join(I),w&&(w=this.extendTranslation(w,e,i,r));else{let $e=!1,be=!1;!this.isValidLookup(w)&&P&&($e=!0,w=M),this.isValidLookup(w)||(be=!0,w=c);const Be=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&be?void 0:w,Qe=P&&M!==w&&this.options.updateMissing;if(be||$e||Qe){if(this.logger.log(Qe?"updateKey":"missingKey",f,d,c,Qe?M:w),a){const Pe=this.resolve(c,{...i,keySeparator:!1});Pe&&Pe.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 Lt=[];const Ut=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&Ut&&Ut[0])for(let Pe=0;Pe<Ut.length;Pe++)Lt.push(Ut[Pe]);else this.options.saveMissingTo==="all"?Lt=this.languageUtils.toResolveHierarchy(i.lng||this.language):Lt.push(i.lng||this.language);const Hn=(Pe,et,K)=>{const vt=P&&K!==w?K:Be;this.options.missingKeyHandler?this.options.missingKeyHandler(Pe,d,et,vt,Qe,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(Pe,d,et,vt,Qe,i),this.emit("missingKey",Pe,d,et,w)};this.options.saveMissing&&(this.options.saveMissingPlurals&&E?Lt.forEach(Pe=>{const et=this.pluralResolver.getSuffixes(Pe,i);W&&i[`defaultValue${this.options.pluralSeparator}zero`]&&et.indexOf(`${this.options.pluralSeparator}zero`)<0&&et.push(`${this.options.pluralSeparator}zero`),et.forEach(K=>{Hn([Pe],c+K,i[`defaultValue${K}`]||M)})}):Hn(Lt,c,M))}w=this.extendTranslation(w,e,i,_,r),be&&w===c&&this.options.appendNamespaceToMissingKey&&(w=`${d}${u}${c}`),(be||$e)&&this.options.parseMissingKeyHandler&&(w=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${u}${c}`:c,$e?w:void 0,i))}return s?(_.res=w,_.usedParams=this.getUsedParamsDetails(i),_):w}extendTranslation(e,n,r,i,s){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...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=Y(e)&&(r?.interpolation?.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let d;if(l){const f=e.match(this.interpolator.nestingRegexp);d=f&&f.length}let u=r.replace&&!Y(r.replace)?r.replace:r;if(this.options.interpolation.defaultVariables&&(u={...this.options.interpolation.defaultVariables,...u}),e=this.interpolator.interpolate(e,u,r.lng||this.language||i.usedLng,r),l){const f=e.match(this.interpolator.nestingRegexp),g=f&&f.length;d<g&&(r.nest=!1)}!r.lng&&i&&i.res&&(r.lng=this.language||i.usedLng),r.nest!==!1&&(e=this.interpolator.nest(e,(...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=Y(a)?[a]:a;return e!=null&&c?.length&&r.applyPostProcessor!==!1&&(e=U0.handle(c,e,n,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(r)},...r}:r,this)),e}resolve(e,n={}){let r,i,s,a,c;return Y(e)&&(e=[e]),e.forEach(l=>{if(this.isValidLookup(r))return;const d=this.extractFromKey(l,n),u=d.key;i=u;let f=d.namespaces;this.options.fallbackNS&&(f=f.concat(this.options.fallbackNS));const g=n.count!==void 0&&!Y(n.count),_=g&&!n.ordinal&&n.count===0,w=n.context!==void 0&&(Y(n.context)||typeof n.context=="number")&&n.context!=="",k=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);f.forEach(z=>{this.isValidLookup(r)||(c=z,!gf[`${k[0]}-${z}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(c)&&(gf[`${k[0]}-${z}`]=!0,this.logger.warn(`key "${i}" for languages "${k.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!!!")),k.forEach(N=>{if(this.isValidLookup(r))return;a=N;const I=[u];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(I,u,N,z,n);else{let E;g&&(E=this.pluralResolver.getSuffix(N,n.count,n));const P=`${this.options.pluralSeparator}zero`,G=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(g&&(n.ordinal&&E.indexOf(G)===0&&I.push(u+E.replace(G,this.options.pluralSeparator)),I.push(u+E),_&&I.push(u+P)),w){const Z=`${u}${this.options.contextSeparator||"_"}${n.context}`;I.push(Z),g&&(n.ordinal&&E.indexOf(G)===0&&I.push(Z+E.replace(G,this.options.pluralSeparator)),I.push(Z+E),_&&I.push(Z+P))}}let S;for(;S=I.pop();)this.isValidLookup(r)||(s=S,r=this.getResource(N,z,S,n))}))})}),{res:r,usedKey:i,exactUsedKey:s,usedLng:a,usedNS:c}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,n,r,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,n,r,i):this.resourceStore.getResource(e,n,r,i)}getUsedParamsDetails(e={}){const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=e.replace&&!Y(e.replace);let i=r?e.replace:e;if(r&&typeof e.count<"u"&&(i.count=e.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(e){const n="defaultValue";for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&n===r.substring(0,n.length)&&e[r]!==void 0)return!0;return!1}}class mf{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Vt.create("languageUtils")}getScriptPartFromCode(e){if(e=go(e),!e||e.indexOf("-")<0)return null;const n=e.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(e){if(e=go(e),!e||e.indexOf("-")<0)return e;const n=e.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(e){if(Y(e)&&e.indexOf("-")>-1){let n;try{n=Intl.getCanonicalLocales(e)[0]}catch{}return n&&this.options.lowerCaseLng&&(n=n.toLowerCase()),n||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let n;return e.forEach(r=>{if(n)return;const i=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(i))&&(n=i)}),!n&&this.options.supportedLngs&&e.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(e,n){if(!e)return[];if(typeof e=="function"&&(e=e(n)),Y(e)&&(e=[e]),Array.isArray(e))return e;if(!n)return e.default||[];let r=e[n];return r||(r=e[this.getScriptPartFromCode(n)]),r||(r=e[this.formatLanguageCode(n)]),r||(r=e[this.getLanguagePartFromCode(n)]),r||(r=e.default),r||[]}toResolveHierarchy(e,n){const r=this.getFallbackCodes((n===!1?[]:n)||this.options.fallbackLng||[],e),i=[],s=a=>{a&&(this.isSupportedCode(a)?i.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return Y(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&s(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&s(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&s(this.getLanguagePartFromCode(e))):Y(e)&&s(this.formatLanguageCode(e)),r.forEach(a=>{i.indexOf(a)<0&&s(this.formatLanguageCode(a))}),i}}const _f={zero:0,one:1,two:2,few:3,many:4,other:5},yf={select:t=>t===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Hw{constructor(e,n={}){this.languageUtils=e,this.options=n,this.logger=Vt.create("pluralResolver"),this.pluralRulesCache={}}addRule(e,n){this.rules[e]=n}clearCache(){this.pluralRulesCache={}}getRule(e,n={}){const r=go(e==="dev"?"en":e),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(!Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),yf;if(!e.match(/-|_/))return yf;const l=this.languageUtils.getLanguagePartFromCode(e);a=this.getRule(l,n)}return this.pluralRulesCache[s]=a,a}needsPlural(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,n,r={}){return this.getSuffixes(e,r).map(i=>`${n}${i}`)}getSuffixes(e,n={}){let r=this.getRule(e,n);return r||(r=this.getRule("dev",n)),r?r.resolvedOptions().pluralCategories.sort((i,s)=>_f[i]-_f[s]).map(i=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${i}`):[]}getSuffix(e,n,r={}){const i=this.getRule(e,r);return i?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${i.select(n)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",n,r))}}const wf=(t,e,n,r=".",i=!0)=>{let s=Tw(t,e,n);return!s&&i&&Y(n)&&(s=Tl(t,n,r),s===void 0&&(s=Tl(e,n,r))),s},ll=t=>t.replace(/\$/g,"$$$$");class bf{constructor(e={}){this.logger=Vt.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(n=>n),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:i,prefix:s,prefixEscaped:a,suffix:c,suffixEscaped:l,formatSeparator:d,unescapeSuffix:u,unescapePrefix:f,nestingPrefix:g,nestingPrefixEscaped:_,nestingSuffix:w,nestingSuffixEscaped:k,nestingOptionsSeparator:z,maxReplaces:N,alwaysFormat:I}=e.interpolation;this.escape=n!==void 0?n:Bw,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=s?Ar(s):a||"{{",this.suffix=c?Ar(c):l||"}}",this.formatSeparator=d||",",this.unescapePrefix=u?"":f||"-",this.unescapeSuffix=this.unescapePrefix?"":u||"",this.nestingPrefix=g?Ar(g):_||Ar("$t("),this.nestingSuffix=w?Ar(w):k||Ar(")"),this.nestingOptionsSeparator=z||",",this.maxReplaces=N||1e3,this.alwaysFormat=I!==void 0?I:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(n,r)=>n?.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,n,r,i){let s,a,c;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},d=_=>{if(_.indexOf(this.formatSeparator)<0){const N=wf(n,l,_,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(N,void 0,r,{...i,...n,interpolationkey:_}):N}const w=_.split(this.formatSeparator),k=w.shift().trim(),z=w.join(this.formatSeparator).trim();return this.format(wf(n,l,k,this.options.keySeparator,this.options.ignoreJSONStructure),z,r,{...i,...n,interpolationkey:k})};this.resetRegExp();const u=i?.missingInterpolationHandler||this.options.missingInterpolationHandler,f=i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:_=>ll(_)},{regex:this.regexp,safeValue:_=>this.escapeValue?ll(this.escape(_)):ll(_)}].forEach(_=>{for(c=0;s=_.regex.exec(e);){const w=s[1].trim();if(a=d(w),a===void 0)if(typeof u=="function"){const z=u(e,s,i);a=Y(z)?z:""}else if(i&&Object.prototype.hasOwnProperty.call(i,w))a="";else if(f){a=s[0];continue}else this.logger.warn(`missed to pass in variable ${w} for interpolating ${e}`),a="";else!Y(a)&&!this.useRawValueToEscape&&(a=df(a));const k=_.safeValue(a);if(e=e.replace(s[0],k),f?(_.regex.lastIndex+=a.length,_.regex.lastIndex-=s[0].length):_.regex.lastIndex=0,c++,c>=this.maxReplaces)break}}),e}nest(e,n,r={}){let i,s,a;const c=(l,d)=>{const u=this.nestingOptionsSeparator;if(l.indexOf(u)<0)return l;const f=l.split(new RegExp(`${u}[ ]*{`));let g=`{${f[1]}`;l=f[0],g=this.interpolate(g,a);const _=g.match(/'/g),w=g.match(/"/g);((_?.length??0)%2===0&&!w||w.length%2!==0)&&(g=g.replace(/'/g,'"'));try{a=JSON.parse(g),d&&(a={...d,...a})}catch(k){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,k),`${l}${u}${g}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,l};for(;i=this.nestingRegexp.exec(e);){let l=[];a={...r},a=a.replace&&!Y(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;const d=/{.*}/.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(d!==-1&&(l=i[1].slice(d).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),i[1]=i[1].slice(0,d)),s=n(c.call(this,i[1].trim(),a),a),s&&i[0]===e&&!Y(s))return s;Y(s)||(s=df(s)),s||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${e}`),s=""),l.length&&(s=l.reduce((u,f)=>this.format(u,f,r.lng,{...r,interpolationkey:i[1].trim()}),s.trim())),e=e.replace(i[0],s),this.regexp.lastIndex=0}return e}}const Vw=t=>{let e=t.toLowerCase().trim();const n={};if(t.indexOf("(")>-1){const r=t.split("(");e=r[0].toLowerCase().trim();const i=r[1].substring(0,r[1].length-1);e==="currency"&&i.indexOf(":")<0?n.currency||(n.currency=i.trim()):e==="relativetime"&&i.indexOf(":")<0?n.range||(n.range=i.trim()):i.split(";").forEach(a=>{if(a){const[c,...l]=a.split(":"),d=l.join(":").trim().replace(/^'+|'+$/g,""),u=c.trim();n[u]||(n[u]=d),d==="false"&&(n[u]=!1),d==="true"&&(n[u]=!0),isNaN(d)||(n[u]=parseInt(d,10))}})}return{formatName:e,formatOptions:n}},vf=t=>{const e={};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=e[a];return c||(c=t(go(r),i),e[a]=c),c(n)}},Kw=t=>(e,n,r)=>t(go(n),r)(e);class Gw{constructor(e={}){this.logger=Vt.create("formatter"),this.options=e,this.init(e)}init(e,n={interpolation:{}}){this.formatSeparator=n.interpolation.formatSeparator||",";const r=n.cacheInBuiltFormats?vf:Kw;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(e,n){this.formats[e.toLowerCase().trim()]=n}addCached(e,n){this.formats[e.toLowerCase().trim()]=vf(n)}format(e,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:d,formatOptions:u}=Vw(l);if(this.formats[d]){let f=c;try{const g=i?.formatParams?.[i.interpolationkey]||{},_=g.locale||g.lng||i.locale||i.lng||r;f=this.formats[d](c,_,{...u,...i,...g})}catch(g){this.logger.warn(g)}return f}else this.logger.warn(`there was no format function for ${d}`);return c},e)}}const Ww=(t,e)=>{t.pending[e]!==void 0&&(delete t.pending[e],t.pendingCount--)};class Jw extends Ha{constructor(e,n,r,i={}){super(),this.backend=e,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=i,this.logger=Vt.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(e,n,r,i){const s={},a={},c={},l={};return e.forEach(d=>{let u=!0;n.forEach(f=>{const g=`${d}|${f}`;!r.reload&&this.store.hasResourceBundle(d,f)?this.state[g]=2:this.state[g]<0||(this.state[g]===1?a[g]===void 0&&(a[g]=!0):(this.state[g]=1,u=!1,a[g]===void 0&&(a[g]=!0),s[g]===void 0&&(s[g]=!0),l[f]===void 0&&(l[f]=!0)))}),u||(c[d]=!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(e,n,r){const i=e.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[e]=n?-1:2,n&&r&&(this.state[e]=0);const c={};this.queue.forEach(l=>{Ow(l.loaded,[s],a),Ww(l,e),n&&l.errors.push(n),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(d=>{c[d]||(c[d]={});const u=l.loaded[d];u.length&&u.forEach(f=>{c[d][f]===void 0&&(c[d][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(e,n,r,i=0,s=this.retryTimeout,a){if(!e.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:n,fcName:r,tried:i,wait:s,callback:a});return}this.readingCalls++;const c=(d,u)=>{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(d&&u&&i<this.maxRetries){setTimeout(()=>{this.read.call(this,e,n,r,i+1,s*2,a)},s);return}a(d,u)},l=this.backend[r].bind(this.backend);if(l.length===2){try{const d=l(e,n);d&&typeof d.then=="function"?d.then(u=>c(null,u)).catch(c):c(null,d)}catch(d){c(d)}return}return l(e,n,c)}prepareLoading(e,n,r={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();Y(e)&&(e=this.languageUtils.toResolveHierarchy(e)),Y(n)&&(n=[n]);const s=this.queueLoad(e,n,r,i);if(!s.toLoad.length)return s.pending.length||i(),null;s.toLoad.forEach(a=>{this.loadOne(a)})}load(e,n,r){this.prepareLoading(e,n,{},r)}reload(e,n,r){this.prepareLoading(e,n,{reload:!0},r)}loadOne(e,n=""){const r=e.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(e,a,c)})}saveMissing(e,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},d=this.backend.create.bind(this.backend);if(d.length<6)try{let u;d.length===5?u=d(e,n,r,i,l):u=d(e,n,r,i),u&&typeof u.then=="function"?u.then(f=>c(null,f)).catch(c):c(null,u)}catch(u){c(u)}else d(e,n,r,i,c,l)}!e||!e[0]||this.store.addResource(e[0],n,r,i)}}}const $f=()=>({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:t=>{let e={};if(typeof t[1]=="object"&&(e=t[1]),Y(t[1])&&(e.defaultValue=t[1]),Y(t[2])&&(e.tDescription=t[2]),typeof t[2]=="object"||typeof t[3]=="object"){const n=t[3]||t[2];Object.keys(n).forEach(r=>{e[r]=n[r]})}return e},interpolation:{escapeValue:!0,format:t=>t,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),kf=t=>(Y(t.ns)&&(t.ns=[t.ns]),Y(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),Y(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs?.indexOf?.("cimode")<0&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),typeof t.initImmediate=="boolean"&&(t.initAsync=t.initImmediate),t),hs=()=>{},Xw=t=>{Object.getOwnPropertyNames(Object.getPrototypeOf(t)).forEach(n=>{typeof t[n]=="function"&&(t[n]=t[n].bind(t))})};class ro extends Ha{constructor(e={},n){if(super(),this.options=kf(e),this.services={},this.logger=Vt,this.modules={external:[]},Xw(this),n&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,n),this;setTimeout(()=>{this.init(e,n)},0)}}init(e={},n){this.isInitializing=!0,typeof e=="function"&&(n=e,e={}),e.defaultNS==null&&e.ns&&(Y(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const r=$f();this.options={...r,...this.options,...kf(e)},this.options.interpolation={...r.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=r.overloadTranslationOptionHandler);const i=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?Vt.init(i(this.modules.logger),this.options):Vt.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=Gw;const u=new mf(this.options);this.store=new hf(this.options.resources,this.options);const f=this.services;f.logger=Vt,f.resourceStore=this.store,f.languageUtils=u,f.pluralResolver=new Hw(u,{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"),d&&(!this.options.interpolation.format||this.options.interpolation.format===r.interpolation.format)&&(f.formatter=i(d),f.formatter.init&&f.formatter.init(f,this.options),this.options.interpolation.format=f.formatter.format.bind(f.formatter)),f.interpolator=new bf(this.options),f.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},f.backendConnector=new Jw(i(this.modules.backend),f.resourceStore,f,this.options),f.backendConnector.on("*",(_,...w)=>{this.emit(_,...w)}),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 qs(this.services,this.options),this.translator.on("*",(_,...w)=>{this.emit(_,...w)}),this.modules.external.forEach(_=>{_.init&&_.init(this)})}if(this.format=this.options.interpolation.format,n||(n=hs),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const d=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);d.length>0&&d[0]!=="dev"&&(this.options.lng=d[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(d=>{this[d]=(...u)=>this.store[d](...u)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(d=>{this[d]=(...u)=>(this.store[d](...u),this)});const c=Ci(),l=()=>{const d=(u,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(u,f)};if(this.languages&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initAsync?l():setTimeout(l,0),c}loadResources(e,n=hs){let r=n;const i=Y(e)?e:this.language;if(typeof e=="function"&&(r=e),!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(d=>{d!=="cimode"&&s.indexOf(d)<0&&s.push(d)})};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(e,n,r){const i=Ci();return typeof e=="function"&&(r=e,e=void 0),typeof n=="function"&&(r=n,n=void 0),e||(e=this.languages),n||(n=this.options.ns),r||(r=hs),this.services.backendConnector.reload(e,n,s=>{i.resolve(),r(s)}),i}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&U0.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!(["cimode","dev"].indexOf(e)>-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(e)<0&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,n){this.isLanguageChangingTo=e;const r=Ci();this.emit("languageChanging",e);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===e&&(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((...d)=>this.t(...d)),n&&n(c,(...d)=>this.t(...d))},a=c=>{!e&&!c&&this.services.languageDetector&&(c=[]);const l=Y(c)?c:c&&c[0],d=this.store.hasLanguageSomeTranslations(l)?l:this.services.languageUtils.getBestMatchFromCodes(Y(c)?[c]:c);d&&(this.language||i(d),this.translator.language||this.translator.changeLanguage(d),this.services.languageDetector?.cacheUserLanguage?.(d)),this.loadResources(d,u=>{s(u,d)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?a(this.services.languageDetector.detect()):!e&&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(e),r}getFixedT(e,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 d=this.options.keySeparator||".";let u;return l.keyPrefix&&Array.isArray(s)?u=s.map(f=>(typeof f=="function"&&(f=Rl(f,{...this.options,...a})),`${l.keyPrefix}${d}${f}`)):(typeof s=="function"&&(s=Rl(s,{...this.options,...a})),u=l.keyPrefix?`${l.keyPrefix}${d}${s}`:s),this.t(u,l)};return Y(e)?i.lng=e:i.lngs=e,i.ns=n,i.keyPrefix=r,i}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,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 d=this.services.backendConnector.state[`${c}|${l}`];return d===-1||d===0||d===2};if(n.precheck){const c=n.precheck(this,a);if(c!==void 0)return c}return!!(this.hasResourceBundle(r,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(r,e)&&(!i||a(s,e)))}loadNamespaces(e,n){const r=Ci();return this.options.ns?(Y(e)&&(e=[e]),e.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(e,n){const r=Ci();Y(e)&&(e=[e]);const i=this.options.preload||[],s=e.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(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const i=new Intl.Locale(e);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 mf($f());return e.toLowerCase().indexOf("-latn")>1?"ltr":n.indexOf(r.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},n){const r=new ro(e,n);return r.createInstance=ro.createInstance,r}cloneInstance(e={},n=hs){const r=e.forkResourceStore;r&&delete e.forkResourceStore;const i={...this.options,...e,isClone:!0},s=new ro(i);if((e.debug!==void 0||e.prefix!==void 0)&&(s.logger=s.logger.clone(e)),["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,d)=>(l[d]={...this.store.data[d]},l[d]=Object.keys(l[d]).reduce((u,f)=>(u[f]={...l[d][f]},u),l[d]),l),{});s.store=new hf(c,i),s.services.resourceStore=s.store}return e.interpolation&&(s.services.interpolator=new bf(i)),s.translator=new qs(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 y=ro.createInstance();y.createInstance;y.dir;y.init;y.loadResources;y.reloadResources;y.use;y.changeLanguage;y.getFixedT;const X=y.t;y.exists;y.setDefaultNamespace;y.hasLoadedNamespace;y.loadNamespaces;y.loadLanguages;var M0=t=>{const n={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...t},r=(s=>typeof s=="string"?s==="*"?()=>s:a=>s===a?a:null:typeof s=="function"?s:a=>s.includes(a)?a:null)(n.origin),i=(s=>typeof s=="function"?s:Array.isArray(s)?()=>s:()=>[])(n.allowMethods);return async function(a,c){function l(u,f){a.res.headers.set(u,f)}const d=await r(a.req.header("origin")||"",a);if(d&&l("Access-Control-Allow-Origin",d),n.credentials&&l("Access-Control-Allow-Credentials","true"),n.exposeHeaders?.length&&l("Access-Control-Expose-Headers",n.exposeHeaders.join(",")),a.req.method==="OPTIONS"){n.origin!=="*"&&l("Vary","Origin"),n.maxAge!=null&&l("Access-Control-Max-Age",n.maxAge.toString());const u=await i(a.req.header("origin")||"",a);u.length&&l("Access-Control-Allow-Methods",u.join(","));let f=n.allowHeaders;if(!f?.length){const g=a.req.header("Access-Control-Request-Headers");g&&(f=g.split(/\s*,\s*/))}return f?.length&&(l("Access-Control-Allow-Headers",f.join(",")),a.res.headers.append("Vary","Access-Control-Request-Headers")),a.res.headers.delete("Content-Length"),a.res.headers.delete("Content-Type"),new Response(null,{headers:a.res.headers,status:204,statusText:"No Content"})}await c(),n.origin!=="*"&&a.header("Vary","Origin",{append:!0})}};const Zw=o.z.object({page:o.z.string().min(0).optional().default("0").transform(t=>parseInt(t,10)).openapi({description:"The page number where 0 is the first page"}),per_page:o.z.string().min(1).optional().default("10").transform(t=>parseInt(t,10)).openapi({description:"The number of items per page"}),include_totals:o.z.string().optional().default("false").transform(t=>t==="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()}),ui=o.z.object({created_at:o.z.string(),updated_at:o.z.string()}),q0=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()),F0=o.z.object({connection:o.z.string(),user_id:o.z.string(),provider:o.z.string(),isSocial:o.z.boolean(),access_token:o.z.string().optional(),access_token_secret:o.z.string().optional(),refresh_token:o.z.string().optional(),profileData:q0.optional()}),Va=o.z.object({email:o.z.string().optional().transform(t=>t&&t.toLowerCase()),username:o.z.string().optional(),phone_number:o.z.string().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()}),Fs=Va.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()}),Su=o.z.object({...Fs.shape,...ui.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(F0).optional()}),Ft=Su,Yw=Va.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()),Qw="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let eb=(t=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)e+=Qw[n[t]&63];return e};const Hs=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(()=>eb()).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)."}),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()}),Jn=o.z.object({created_at:o.z.string(),updated_at:o.z.string(),...Hs.shape}),Vs=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."})}),Xn=o.z.object({id:o.z.string().openapi({description:"ID of the client grant."}),...Vs.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),tb=o.z.array(Xn),pi=o.z.object({x:o.z.number(),y:o.z.number()});var zu=(t=>(t.RICH_TEXT="RICH_TEXT",t.NEXT_BUTTON="NEXT_BUTTON",t.BACK_BUTTON="BACK_BUTTON",t.SUBMIT_BUTTON="SUBMIT_BUTTON",t.DIVIDER="DIVIDER",t.TEXT="TEXT",t.EMAIL="EMAIL",t.PASSWORD="PASSWORD",t.NUMBER="NUMBER",t.PHONE="PHONE",t.DATE="DATE",t.CHECKBOX="CHECKBOX",t.RADIO="RADIO",t.SELECT="SELECT",t.HIDDEN="HIDDEN",t.LEGAL="LEGAL",t))(zu||{}),Au=(t=>(t.BLOCK="BLOCK",t.FIELD="FIELD",t))(Au||{});const Ka=o.z.object({id:o.z.string(),category:o.z.nativeEnum(Au),type:o.z.nativeEnum(zu)}),H0=Ka.extend({category:o.z.literal("BLOCK"),type:o.z.literal("RICH_TEXT"),config:o.z.object({content:o.z.string()}).passthrough()}),V0=Ka.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()}),K0=Ka.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()}),G0=Ka.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()}),W0=o.z.object({id:o.z.string(),category:o.z.string(),type:o.z.string()}).passthrough(),J0=o.z.union([H0,V0,K0,G0,W0]);var X0=(t=>(t.STEP="STEP",t.FLOW="FLOW",t.CONDITION="CONDITION",t.ACTION="ACTION",t))(X0||{});const Z0=o.z.object({id:o.z.string(),type:o.z.literal("STEP"),coordinates:pi,alias:o.z.string().optional(),config:o.z.object({components:o.z.array(J0),next_node:o.z.string()}).passthrough()}),Y0=o.z.object({id:o.z.string(),type:o.z.literal("FLOW"),coordinates:pi,alias:o.z.string().optional(),config:o.z.object({flow_id:o.z.string(),next_node:o.z.string()})}),Q0=o.z.object({id:o.z.string(),type:o.z.string(),coordinates:pi}).passthrough(),em=o.z.union([Z0,Y0,Q0]),tm=o.z.object({next_node:o.z.string(),coordinates:pi}).passthrough(),nm=o.z.object({resume_flow:o.z.boolean().optional(),coordinates:pi}).passthrough(),rm=o.z.object({id:o.z.string(),name:o.z.string(),languages:o.z.object({primary:o.z.string()}).passthrough(),nodes:o.z.array(em),start:tm,ending:nm,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(),nb=rm.omit({id:!0,created_at:!0,updated_at:!0});var mt=(t=>(t.TOKEN="token",t.TOKEN_ID_TOKEN="token id_token",t.CODE="code",t))(mt||{}),Ct=(t=>(t.QUERY="query",t.FRAGMENT="fragment",t.FORM_POST="form_post",t.WEB_MESSAGE="web_message",t.SAML_POST="saml_post",t))(Ct||{}),Ga=(t=>(t.S256="S256",t.Plain="plain",t))(Ga||{});const mo=o.z.object({client_id:o.z.string(),act_as:o.z.string().optional(),response_type:o.z.nativeEnum(mt).optional(),response_mode:o.z.nativeEnum(Ct).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(Ga).optional(),code_challenge:o.z.string().optional(),username:o.z.string().optional(),ui_locales:o.z.string().optional(),vendor_id:o.z.string().optional()}),Bl=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()}),Dr=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()}),Ks=o.z.object({id:o.z.string().optional(),name:o.z.string(),display_name:o.z.string().optional(),strategy:o.z.string(),options:Dr.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()}),ht=o.z.object({id:o.z.string(),created_at:o.z.string().transform(t=>t===null?"":t),updated_at:o.z.string().transform(t=>t===null?"":t)}).extend(Ks.shape),io=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()}).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()}),Sn=o.z.object({created_at:o.z.string().nullable().transform(t=>t??""),updated_at:o.z.string().nullable().transform(t=>t??""),...io.shape,id:o.z.string()}),rb=o.z.object({...Jn.shape,tenant:Sn,connections:o.z.array(ht)}),im=o.z.enum(["password_reset","email_verification","otp","authorization_code","oauth2_state","ticket"]),om=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:im,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()}),ib=o.z.object({...om.shape,created_at:o.z.string()}),Eu=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()}),sm=o.z.object({name:o.z.literal("txt"),record:o.z.string(),domain:o.z.string()}),xn=o.z.object({...Eu.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(sm)}).optional(),tls_policy:o.z.string().optional()}),ob=xn.extend({tenant_id:o.z.string()}),sb=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()}),am=o.z.object({id:o.z.string(),order:o.z.number().optional(),visible:o.z.boolean().optional().default(!0)}),xf=am.extend({category:o.z.literal("BLOCK").optional()}),Ni=am.extend({category:o.z.literal("FIELD").optional(),required:o.z.boolean().optional(),sensitive:o.z.boolean().optional()}),cm=o.z.discriminatedUnion("type",[xf.extend({type:o.z.literal("RICH_TEXT"),config:o.z.object({content:o.z.string()})}),Ni.omit({sensitive:!0}).extend({type:o.z.literal("LEGAL"),config:o.z.object({text:o.z.string(),html:o.z.boolean().optional()})}),Ni.extend({type:o.z.literal("TEXT"),config:o.z.object({placeholder:o.z.string().optional(),multiline:o.z.boolean().optional()})}),xf.extend({type:o.z.literal("NEXT_BUTTON"),config:o.z.object({text:o.z.string().optional()})}),Ni.extend({type:o.z.literal("EMAIL"),config:o.z.object({label:o.z.string().optional(),placeholder:o.z.string().optional()})}),Ni.extend({type:o.z.literal("NUMBER"),config:o.z.object({label:o.z.string().optional(),placeholder:o.z.string().optional()})}),Ni.extend({type:o.z.literal("PHONE"),config:o.z.object({label:o.z.string().optional(),placeholder:o.z.string().optional()})})]),Gs=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(o.z.discriminatedUnion("type",[o.z.object({id:o.z.string(),type:o.z.literal("FLOW"),coordinates:o.z.object({x:o.z.number(),y:o.z.number()}),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()})}),o.z.object({id:o.z.string(),type:o.z.literal("ROUTER"),coordinates:o.z.object({x:o.z.number(),y:o.z.number()}),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()})}),o.z.object({id:o.z.string(),type:o.z.literal("STEP"),coordinates:o.z.object({x:o.z.number(),y:o.z.number()}),alias:o.z.string().min(1).max(150).optional(),config:o.z.object({components:o.z.array(cm),next_node:o.z.string().optional()})})])).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:o.z.object({x:o.z.number(),y:o.z.number()}).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:o.z.object({x:o.z.number(),y:o.z.number()}).optional(),resume_flow:o.z.boolean().optional()}).optional(),style:o.z.object({css:o.z.string().optional()}).optional()}).openapi({description:"Schema for flow-based forms (matches new JSON structure)"}),Br=o.z.object({...ui.shape,...Gs.shape,id:o.z.string()}),lm=o.z.enum(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),dm=o.z.enum(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Wa={enabled:o.z.boolean().default(!1),synchronous:o.z.boolean().default(!1),priority:o.z.number().optional(),hook_id:o.z.string().optional()},ab=o.z.object({...Wa,trigger_id:lm,url:o.z.string()}),cb=o.z.object({...Wa,trigger_id:dm,form_id:o.z.string()}),ks=o.z.union([ab,cb]),lb=o.z.object({...Wa,trigger_id:lm,...ui.shape,hook_id:o.z.string(),url:o.z.string()}),db=o.z.object({...Wa,trigger_id:dm,...ui.shape,hook_id:o.z.string(),form_id:o.z.string()}),Lr=o.z.union([lb,db]),um=o.z.object({name:o.z.string().optional()}),pm=o.z.object({email:o.z.string().optional()}),Cu=o.z.object({organization_id:o.z.string().max(50),inviter:um,invitee:pm,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()}),oo=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(Cu.shape),Nu=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()}),fm=o.z.object({keys:o.z.array(Nu)}),Ll=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())}),hm=o.z.object({csrf_token:o.z.string(),auth0Client:o.z.string().optional(),authParams:mo,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(),login_completed:o.z.boolean().optional().default(!1)}).openapi({description:"This represents a login sesion"}),ub=o.z.object({...hm.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()}),te={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_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",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"},pb=o.z.string().refine(t=>Object.values(te).includes(t),{message:"Invalid log type"}),gm=o.z.object({name:o.z.string(),version:o.z.string(),env:o.z.object({node:o.z.string().optional()}).optional()}),mm=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()}),_m=o.z.object({type:pb,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:gm.optional(),log_id:o.z.string().optional(),location_info:mm.optional()}),Ws=o.z.object({..._m.shape,log_id:o.z.string()}),ym=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)}),fb=ym.extend({id:o.z.string(),created_at:o.z.string(),updated_at:o.z.string()}),wm=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")}),bm=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:wm.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")}),Ja=o.z.object({created_at:o.z.string(),updated_at:o.z.string(),authenticated_at:o.z.string(),last_interaction_at:o.z.string(),...bm.shape}),Ul=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"})});var St=(t=>(t.RefreshToken="refresh_token",t.AuthorizationCode="authorization_code",t.ClientCredential="client_credentials",t.Passwordless="passwordless",t.Password="password",t.OTP="http://auth0.com/oauth/grant-type/passwordless/otp",t))(St||{});const Iu=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 vm=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()}),$m=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()}),Kn=o.z.object({bold:o.z.boolean(),size:o.z.number()}),km=o.z.object({body_text:Kn,buttons_text:Kn,font_url:o.z.string(),input_labels:Kn,links:Kn,links_style:o.z.enum(["normal","underlined"]),reference_text_size:o.z.number(),subtitle:Kn,title:Kn}),xm=o.z.object({background_color:o.z.string(),background_image_url:o.z.string(),page_layout:o.z.enum(["center","left","right"])}),Sm=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"])}),zm=o.z.object({borders:vm,colors:$m,displayName:o.z.string(),fonts:km,page_background:xm,widget:Sm}),xs=zm.extend({themeId:o.z.string()}),Ss=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()}),zs=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()}),ju=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:wm,resource_servers:o.z.array(o.z.object({audience:o.z.string(),scopes:o.z.string()})),rotating:o.z.boolean()}),hb=o.z.object({created_at:o.z.string(),...ju.shape}),gb=o.z.object({to:o.z.string(),message:o.z.string()}),mb=o.z.object({name:o.z.string(),options:o.z.object({})}),Am=o.z.object({value:o.z.string(),description:o.z.string().optional()}),Em=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()}),Js=o.z.object({name:o.z.string(),identifier:o.z.string(),scopes:o.z.array(Am).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:Em.optional()}),Zn=o.z.object({id:o.z.string().optional(),...Js.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),_b=o.z.array(Zn),Cm=o.z.object({role_id:o.z.string(),resource_server_identifier:o.z.string(),permission_name:o.z.string()}),Nm=o.z.object({...Cm.shape,created_at:o.z.string()}),Im=o.z.array(Nm),jm=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()}),Pm=o.z.object({...jm.shape,tenant_id:o.z.string(),created_at:o.z.string().optional()}),yb=o.z.array(Pm),Om=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()}),Tm=o.z.array(Om),Rm=o.z.object({user_id:o.z.string(),role_id:o.z.string(),organization_id:o.z.string().optional()}),Bm=o.z.object({...Rm.shape,tenant_id:o.z.string(),created_at:o.z.string().optional()}),wb=o.z.array(Bm),Xs=o.z.object({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"})}),Yn=o.z.object({id:o.z.string().openapi({description:"The unique identifier of the role"}),...Xs.shape,created_at:o.z.string().optional(),updated_at:o.z.string().optional()}),Zs=o.z.array(Yn),Lm=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(),Um=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"})}),Dm=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(),Ys=o.z.object({id:o.z.string().optional(),name:o.z.string().min(1).openapi({description:"The name of the organization"}),display_name:o.z.string().optional().openapi({description:"The display name of the organization"}),branding:Lm,metadata:o.z.record(o.z.any()).default({}).optional().openapi({description:"Custom metadata for the organization"}),enabled_connections:o.z.array(Um).default([]).optional().openapi({description:"List of enabled connections for the organization"}),token_quota:Dm}),zn=o.z.object({...Ys.shape,...ui.shape,id:o.z.string()}),Mm=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"})}),bb=o.z.object({...Mm.shape,...ui.shape,id:o.z.string()}),vb=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()});function $b(t){const[e,n]=t.split("|");if(!e||!n)throw new Error(`Invalid user_id: ${t}`);return{connection:e,id:n}}function kb(t){const{primary:e,secondaries:n,syncMethods:r=["create","update","remove","delete","set"]}=t,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 d=await c.apply(s,l),u=[];for(const f of n){const g=f.adapter[a];if(typeof g!="function")continue;const _=(async()=>{try{await g.apply(f.adapter,l)}catch(w){try{f.onError?f.onError(w,a,l):console.error(`Passthrough adapter: secondary write failed for ${a}:`,w)}catch(k){console.error(`Passthrough adapter: onError handler threw for ${a}:`,k)}}})();f.blocking&&u.push(_)}return u.length>0&&await Promise.all(u),d}:c.bind(s)}};return new Proxy(e,i)}function xb(t){return t}const Sf={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:16},buttons_text:{bold:!1,size:16},font_url:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Regular.woff2",input_labels:{bold:!1,size:14},links:{bold:!1,size:16},links_style:"normal",reference_text_size:16,subtitle:{bold:!1,size:18},title:{bold:!0,size:24}},page_background:{background_color:"#F8F9FB",background_image_url:"https://assets.sesamy.com/images/login-bg.jpg",page_layout:"center"},widget:{header_text_alignment:"center",logo_height:36,logo_position:"center",logo_url:"https://assets.sesamy.com/static/images/sesamy/logos/sesamy_logo_black.svg",social_buttons_layout:"bottom"}};function Dl(t,e){const n=structuredClone(t);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,e)}const Sb=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:["auth:read"]}],responses:{200:{content:{"application/json":{schema:xs}},description:"Default theme settings"}}}),async t=>{const e=await t.env.data.themes.get(t.var.tenant_id,"default");return e?t.json(e):t.json(Sf)}).openapi(o.createRoute({tags:["branding"],method:"patch",path:"/default",request:{body:{content:{"application/json":{schema:xs.deepPartial()}}},headers:o.z.object({"tenant-id":o.z.string().optional()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:xs}},description:"Updated theme settings"}}}),async t=>{const e=t.req.valid("json"),n=await t.env.data.themes.get(t.var.tenant_id,"default");if(n){const r=Dl(n,e);await t.env.data.themes.update(t.var.tenant_id,"default",r);const i=await t.env.data.themes.get(t.var.tenant_id,"default");return t.json(i)}else{const r=Dl(Sf,e),i=await t.env.data.themes.create(t.var.tenant_id,r);return t.json(i)}}),zb={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"}},Ab=new o.OpenAPIHono().openapi(o.createRoute({tags:["branding"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Bl}},description:"Branding settings"}}}),async t=>{const e=await t.env.data.branding.get(t.var.tenant_id);return e?t.json(e):t.json(zb)}).openapi(o.createRoute({tags:["branding"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Bl.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const e=t.req.valid("json");return await t.env.data.branding.set(t.var.tenant_id,e),t.text("OK")}).route("/themes",Sb);var v=class extends Error{res;status;constructor(t=500,e){super(e?.message,{cause:e?.cause}),this.res=e?.res,this.status=t}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}};const Eb={};var Ml=null;function Cb(t){try{return crypto.getRandomValues(new Uint8Array(t))}catch{}try{return Eb.randomBytes(t)}catch{}if(!Ml)throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative");return Ml(t)}function Nb(t){Ml=t}function Pu(t,e){if(t=t||Ou,typeof t!="number")throw Error("Illegal arguments: "+typeof t+", "+typeof e);t<4?t=4:t>31&&(t=31);var n=[];return n.push("$2b$"),t<10&&n.push("0"),n.push(t.toString()),n.push("$"),n.push(Qs(Cb(_o),_o)),n.join("")}function qm(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="function"&&(n=t,t=void 0),typeof t>"u")t=Ou;else if(typeof t!="number")throw Error("illegal arguments: "+typeof t);function r(i){zt(function(){try{i(null,Pu(t))}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 Fm(t,e){if(typeof e>"u"&&(e=Ou),typeof e=="number"&&(e=Pu(e)),typeof t!="string"||typeof e!="string")throw Error("Illegal arguments: "+typeof t+", "+typeof e);return ql(t,e)}function Hm(t,e,n,r){function i(s){typeof t=="string"&&typeof e=="number"?qm(e,function(a,c){ql(t,c,s,r)}):typeof t=="string"&&typeof e=="string"?ql(t,e,s,r):zt(s.bind(this,Error("Illegal arguments: "+typeof t+", "+typeof e)))}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 Vm(t,e){for(var n=t.length^e.length,r=0;r<t.length;++r)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}function Ib(t,e){if(typeof t!="string"||typeof e!="string")throw Error("Illegal arguments: "+typeof t+", "+typeof e);return e.length!==60?!1:Vm(Fm(t,e.substring(0,e.length-31)),e)}function jb(t,e,n,r){function i(s){if(typeof t!="string"||typeof e!="string"){zt(s.bind(this,Error("Illegal arguments: "+typeof t+", "+typeof e)));return}if(e.length!==60){zt(s.bind(this,null,!1));return}Hm(t,e.substring(0,29),function(a,c){a?s(a):s(null,Vm(c,e))},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 Pb(t){if(typeof t!="string")throw Error("Illegal arguments: "+typeof t);return parseInt(t.split("$")[2],10)}function Ob(t){if(typeof t!="string")throw Error("Illegal arguments: "+typeof t);if(t.length!==60)throw Error("Illegal hash length: "+t.length+" != 60");return t.substring(0,29)}function Tb(t){if(typeof t!="string")throw Error("Illegal arguments: "+typeof t);return Km(t)>72}var zt=typeof setImmediate=="function"?setImmediate:typeof scheduler=="object"&&typeof scheduler.postTask=="function"?scheduler.postTask.bind(scheduler):setTimeout;function Km(t){for(var e=0,n=0,r=0;r<t.length;++r)n=t.charCodeAt(r),n<128?e+=1:n<2048?e+=2:(n&64512)===55296&&(t.charCodeAt(r+1)&64512)===56320?(++r,e+=4):e+=3;return e}function Rb(t){for(var e=0,n,r,i=new Array(Km(t)),s=0,a=t.length;s<a;++s)n=t.charCodeAt(s),n<128?i[e++]=n:n<2048?(i[e++]=n>>6|192,i[e++]=n&63|128):(n&64512)===55296&&((r=t.charCodeAt(s+1))&64512)===56320?(n=65536+((n&1023)<<10)+(r&1023),++s,i[e++]=n>>18|240,i[e++]=n>>12&63|128,i[e++]=n>>6&63|128,i[e++]=n&63|128):(i[e++]=n>>12|224,i[e++]=n>>6&63|128,i[e++]=n&63|128);return i}var Er="./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),$n=[-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 Qs(t,e){var n=0,r=[],i,s;if(e<=0||e>t.length)throw Error("Illegal len: "+e);for(;n<e;){if(i=t[n++]&255,r.push(Er[i>>2&63]),i=(i&3)<<4,n>=e){r.push(Er[i&63]);break}if(s=t[n++]&255,i|=s>>4&15,r.push(Er[i&63]),i=(s&15)<<2,n>=e){r.push(Er[i&63]);break}s=t[n++]&255,i|=s>>6&3,r.push(Er[i&63]),r.push(Er[s&63])}return r.join("")}function Gm(t,e){var n=0,r=t.length,i=0,s=[],a,c,l,d,u,f;if(e<=0)throw Error("Illegal len: "+e);for(;n<r-1&&i<e&&(f=t.charCodeAt(n++),a=f<$n.length?$n[f]:-1,f=t.charCodeAt(n++),c=f<$n.length?$n[f]:-1,!(a==-1||c==-1||(u=a<<2>>>0,u|=(c&48)>>4,s.push(String.fromCharCode(u)),++i>=e||n>=r)||(f=t.charCodeAt(n++),l=f<$n.length?$n[f]:-1,l==-1)||(u=(c&15)<<4>>>0,u|=(l&60)>>2,s.push(String.fromCharCode(u)),++i>=e||n>=r)));)f=t.charCodeAt(n++),d=f<$n.length?$n[f]:-1,u=(l&3)<<6>>>0,u|=d,s.push(String.fromCharCode(u)),++i;var g=[];for(n=0;n<i;n++)g.push(s[n].charCodeAt(0));return g}var _o=16,Ou=10,Bb=16,Lb=100,zf=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],Af=[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],Wm=[1332899944,1700884034,1701343084,1684370003,1668446532,1869963892];function yo(t,e,n,r){var i,s=t[e],a=t[e+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],t[e]=a^n[Bb+1],t[e+1]=s,t}function Ir(t,e){for(var n=0,r=0;n<4;++n)r=r<<8|t[e]&255,e=(e+1)%t.length;return{key:r,offp:e}}function Ef(t,e,n){for(var r=0,i=[0,0],s=e.length,a=n.length,c,l=0;l<s;l++)c=Ir(t,r),r=c.offp,e[l]=e[l]^c.key;for(l=0;l<s;l+=2)i=yo(i,0,e,n),e[l]=i[0],e[l+1]=i[1];for(l=0;l<a;l+=2)i=yo(i,0,e,n),n[l]=i[0],n[l+1]=i[1]}function Ub(t,e,n,r){for(var i=0,s=[0,0],a=n.length,c=r.length,l,d=0;d<a;d++)l=Ir(e,i),i=l.offp,n[d]=n[d]^l.key;for(i=0,d=0;d<a;d+=2)l=Ir(t,i),i=l.offp,s[0]^=l.key,l=Ir(t,i),i=l.offp,s[1]^=l.key,s=yo(s,0,n,r),n[d]=s[0],n[d+1]=s[1];for(d=0;d<c;d+=2)l=Ir(t,i),i=l.offp,s[0]^=l.key,l=Ir(t,i),i=l.offp,s[1]^=l.key,s=yo(s,0,n,r),r[d]=s[0],r[d+1]=s[1]}function Cf(t,e,n,r,i){var s=Wm.slice(),a=s.length,c;if(n<4||n>31)if(c=Error("Illegal number of rounds (4-31): "+n),r){zt(r.bind(this,c));return}else throw c;if(e.length!==_o)if(c=Error("Illegal salt length: "+e.length+" != "+_o),r){zt(r.bind(this,c));return}else throw c;n=1<<n>>>0;var l,d,u=0,f;typeof Int32Array=="function"?(l=new Int32Array(zf),d=new Int32Array(Af)):(l=zf.slice(),d=Af.slice()),Ub(e,t,l,d);function g(){if(i&&i(u/n),u<n)for(var w=Date.now();u<n&&(u=u+1,Ef(t,l,d),Ef(e,l,d),!(Date.now()-w>Lb)););else{for(u=0;u<64;u++)for(f=0;f<a>>1;f++)yo(s,f<<1,l,d);var k=[];for(u=0;u<a;u++)k.push((s[u]>>24&255)>>>0),k.push((s[u]>>16&255)>>>0),k.push((s[u]>>8&255)>>>0),k.push((s[u]&255)>>>0);if(r){r(null,k);return}else return k}r&&zt(g)}if(typeof r<"u")g();else for(var _;;)if(typeof(_=g())<"u")return _||[]}function ql(t,e,n,r){var i;if(typeof t!="string"||typeof e!="string")if(i=Error("Invalid string / salt: Not a string"),n){zt(n.bind(this,i));return}else throw i;var s,a;if(e.charAt(0)!=="$"||e.charAt(1)!=="2")if(i=Error("Invalid salt version: "+e.substring(0,2)),n){zt(n.bind(this,i));return}else throw i;if(e.charAt(2)==="$")s="\0",a=3;else{if(s=e.charAt(2),s!=="a"&&s!=="b"&&s!=="y"||e.charAt(3)!=="$")if(i=Error("Invalid salt revision: "+e.substring(2,4)),n){zt(n.bind(this,i));return}else throw i;a=4}if(e.charAt(a+2)>"$")if(i=Error("Missing salt rounds"),n){zt(n.bind(this,i));return}else throw i;var c=parseInt(e.substring(a,a+1),10)*10,l=parseInt(e.substring(a+1,a+2),10),d=c+l,u=e.substring(a+3,a+25);t+=s>="a"?"\0":"";var f=Rb(t),g=Gm(u,_o);function _(w){var k=[];return k.push("$2"),s>="a"&&k.push(s),k.push("$"),d<10&&k.push("0"),k.push(d.toString()),k.push("$"),k.push(Qs(g,g.length)),k.push(Qs(w,Wm.length*4-1)),k.join("")}if(typeof n>"u")return _(Cf(f,g,d));Cf(f,g,d,function(w,k){w?n(w,null):n(null,_(k))},r)}function Db(t,e){return Qs(t,e)}function Mb(t,e){return Gm(t,e)}const Pn={setRandomFallback:Nb,genSaltSync:Pu,genSalt:qm,hashSync:Fm,hash:Hm,compareSync:Ib,compare:jb,getRounds:Pb,getSalt:Ob,truncates:Tb,encodeBase64:Db,decodeBase64:Mb},qb="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let Fb=t=>crypto.getRandomValues(new Uint8Array(t)),Hb=(t,e,n)=>{let r=(2<<Math.log2(t.length-1))-1,i=-~(1.6*r*e/t.length);return(s=e)=>{let a="";for(;;){let c=n(i),l=i|0;for(;l--;)if(a+=t[c[l]&r]||"",a.length>=s)return a}}},Jm=(t,e=21)=>Hb(t,e|0,Fb),pe=(t=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)e+=qb[n[t]&63];return e};const Vb=24;function Xa(){return Jm("0123456789abcdef",Vb)()}function gs(t){if(!t.includes("|"))return console.error("Invalid user_id format"),t;const[,e]=t.split("|");return e}function Kb(t){return async(e,n)=>{if(!n.email||!n.email_verified)return t.users.create(e,n);const r=await tc({userAdapter:t.users,tenant_id:e,email:n.email});if(!r)return t.users.create(e,n);await t.users.create(e,{...n,linked_to:r.user_id});const i=await t.users.get(e,r.user_id);if(!i)throw new Error("Failed to fetch primary user after linking");return i}}var Gb={deno:"Deno",bun:"Bun",workerd:"Cloudflare-Workers",node:"Node.js"},Xm=()=>{const t=globalThis;if(typeof navigator<"u"&&typeof navigator.userAgent=="string"){for(const[n,r]of Object.entries(Gb))if(Wb(r))return n}return typeof t?.EdgeRuntime=="string"?"edge-light":t?.fastly!==void 0?"fastly":t?.process?.release?.name==="node"?"node":"other"},Wb=t=>navigator.userAgent.startsWith(t);function Zm(t,e){Xm()==="workerd"&&t.executionCtx.waitUntil(e)}function Jb(t){return[...t].reduce((e,[n,r])=>({...e,[n]:r}),{})}async function ie(t,e,n){const r={};if(t.req.raw?.headers){const s=Jb(t.req.raw.headers);for(const[a,c]of Object.entries(s))r[a.toLowerCase()]=c}const i=async()=>{let s;if(t.env.data.geo)try{s=await t.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:t.var.ip,user_agent:t.var.useragent||"",auth0_client:t.var.auth0_client,date:new Date().toISOString(),details:{request:{method:t.req.method,path:t.req.path,qs:t.req.queries(),body:n.body||t.var.body||""},...n.response&&{response:n.response}},isMobile:!1,client_id:t.var.client_id,client_name:"",user_id:n.userId||t.var.user_id||"",hostname:t.req.header("host")||"",user_name:t.var.username||"",connection_id:"",connection:n.connection||t.var.connection||"",strategy:n.strategy||"",strategy_type:n.strategy_type||"",audience:n.audience||"",scope:n.scope||"",location_info:s};await t.env.data.logs.create(e,a)};n.waitForCompletion?await i():Zm(t,i())}class ea{constructor(e,n){this.value=e,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(e){return new ea(Math.round(this.milliseconds()*e),"ms")}}class Xb{hash;constructor(e){this.hash=e}async verify(e,n,r){const i=await crypto.subtle.importKey("spki",e,{name:"RSASSA-PKCS1-v1_5",hash:this.hash},!1,["verify"]);return await crypto.subtle.verify("RSASSA-PKCS1-v1_5",i,n,r)}async sign(e,n){const r=await crypto.subtle.importKey("pkcs8",e,{name:"RSASSA-PKCS1-v1_5",hash:this.hash},!1,["sign"]);return await crypto.subtle.sign("RSASSA-PKCS1-v1_5",r,n)}async generateKeyPair(e){const n=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",hash:this.hash,modulusLength:e??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 Ym(t){return await crypto.subtle.digest("SHA-256",t)}const Nf="0123456789abcdef";function Fl(t){const e=new Uint8Array(t);let n="";for(let r=0;r<e.length;r++){const i=e[r]>>4;n+=Nf[i];const s=e[r]&15;n+=Nf[s]}return n}class Qm{alphabet;padding;decodeMap=new Map;constructor(e,n){if(e.length!==32)throw new Error("Invalid alphabet");if(this.alphabet=e,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<e.length;r++)this.decodeMap.set(e[r],r)}encode(e,n){let r="",i=0,s=0;for(let c=0;c<e.length;c++)for(i=i<<8|e[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(e,n){const r=n?.strict??!0,i=Math.ceil(e.length/8),s=[];for(let a=0;a<i;a++){let c=0;const l=[];for(let u=0;u<8;u++){const f=e[a*8+u];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 g=this.decodeMap.get(f)??null;if(g===null)throw new Error(`Invalid character: ${f}`);l.push(g)}if(c===8||c===7||c===5||c===2)throw new Error("Invalid padding");const d=(l[0]<<3)+(l[1]>>2);if(s.push(d),c<6){const u=((l[1]&3)<<6)+(l[2]<<1)+(l[3]>>4);s.push(u)}if(c<4){const u=((l[3]&255)<<4)+(l[4]>>1);s.push(u)}if(c<3){const u=((l[4]&1)<<7)+(l[5]<<2)+(l[6]>>3);s.push(u)}if(c<1){const u=((l[6]&7)<<5)+l[7];s.push(u)}}return Uint8Array.from(s)}}new Qm("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");new Qm("0123456789ABCDEFGHIJKLMNOPQRSTUV");class e_{alphabet;padding;decodeMap=new Map;constructor(e,n){if(e.length!==64)throw new Error("Invalid alphabet");if(this.alphabet=e,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<e.length;r++)this.decodeMap.set(e[r],r)}encode(e,n){let r="",i=0,s=0;for(let c=0;c<e.length;c++)for(i=i<<8|e[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(e,n){const r=n?.strict??!0,i=Math.ceil(e.length/4),s=[];for(let a=0;a<i;a++){let c=0,l=0;for(let d=0;d<4;d++){const u=e[a*4+d];if(u==="="){if(a+1!==i)throw new Error(`Invalid character: ${u}`);c+=1;continue}if(u===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const f=this.decodeMap.get(u)??null;if(f===null)throw new Error(`Invalid character: ${u}`);l+=f<<6*(3-d)}s.push(l>>16&255),c<2&&s.push(l>>8&255),c<1&&s.push(l&255)}return Uint8Array.from(s)}}const Zb=new e_("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),tr=new e_("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");async function If(t,e,n,r){const i={alg:t,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=tr.encode(a.encode(JSON.stringify(i)),{includePadding:!1}),l=tr.encode(a.encode(JSON.stringify(s)),{includePadding:!1}),d=a.encode([c,l].join(".")),u=await Qb(t).sign(e,d),f=tr.encode(new Uint8Array(u),{includePadding:!1});return[c,l,f].join(".")}function Yb(t){const e=t.split(".");return e.length!==3?null:e}function Mo(t){const e=Yb(t);if(!e)return null;const n=new TextDecoder,r=tr.decode(e[0],{strict:!1}),i=tr.decode(e[1],{strict:!1}),s=JSON.parse(n.decode(r));if(typeof s!="object"||s===null||!("alg"in s)||!ev(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:t,header:{...s,typ:"JWT",alg:s.alg},payload:{...a},parts:e,...c}}function Qb(t){return new Xb(tv[t])}function ev(t){return typeof t!="string"?!1:["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512","PS256","PS384","PS512"].includes(t)}const tv={RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512"};function nv(){const t=new Uint8Array(32);return crypto.getRandomValues(t),tr.encode(t,{includePadding:!1})}function rv(t){try{const n=/-----BEGIN (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----([^-]*)-----END (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----/.exec(t);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{t=t.replace(/./g,"\0")}}async function iv(t,e){if(e==="plain")return t;const n=new TextEncoder().encode(t),r=await Ym(n);return tr.encode(new Uint8Array(r),{includePadding:!1})}const ms=300,Za=720*60*60,or=1440*60,ov="auth-token",As=1800*1e3,Hl=10080*60*1e3,sv=300,av=300,cv=1800*1e3,lv=1800*1e3,dv=1440*60*1e3;function t_(t,e,n){const r=[];return r.push([encodeURIComponent(t),encodeURIComponent(e)]),n?.domain!==void 0&&r.push(["Domain",n.domain]),n?.expires!==void 0&&r.push(["Expires",n.expires.toUTCString()]),n?.httpOnly&&r.push(["HttpOnly"]),n?.maxAge!==void 0&&r.push(["Max-Age",n.maxAge.toString()]),n?.path!==void 0&&r.push(["Path",n.path]),n?.sameSite==="lax"&&r.push(["SameSite","Lax"]),n?.sameSite==="none"&&r.push(["SameSite","None"]),n?.sameSite==="strict"&&r.push(["SameSite","Strict"]),n?.secure&&r.push(["Secure"]),r.map(i=>i.join("=")).join("; ")}function uv(t){const e=new Map,n=t.split("; ");for(const r of n){const i=r.split("="),s=i[0],a=i[1]??"";s&&e.set(decodeURIComponent(s),decodeURIComponent(a))}return e}function Tu(t){return`${t}-${ov}`}function n_(t){if(!t)return;const[e]=t.split(":");if(!e||e==="localhost"||/^(\d{1,3}\.){3}\d{1,3}$/.test(e))return;const n=e.split(".");return n.length>2?`.${n.slice(-2).join(".")}`:`.${e}`}function Wr(t,e){return e?uv(e).get(Tu(t)):void 0}function r_(t,e){return t_(Tu(t),"",{path:"/",httpOnly:!0,secure:!0,maxAge:0,sameSite:"none",domain:e?n_(e):void 0})}function ta(t,e,n){return t_(Tu(t),e,{path:"/",httpOnly:!0,secure:!0,maxAge:Za,sameSite:"none",domain:n?n_(n):void 0})}class B extends v{constructor(e,n){super(e,{message:JSON.stringify(n),res:new Response(JSON.stringify(n),{status:e,headers:{"Content-Type":"application/json"}})})}}var pv=Object.defineProperty,fv=(t,e,n)=>e in t?pv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Mr=(t,e,n)=>fv(t,typeof e!="symbol"?e+"":e,n);const He=o.z.object({"#text":o.z.string()}),hv=o.z.object({"#text":o.z.string(),"@_xmlns:saml":o.z.string().optional()});o.z.object({"samlp:AuthnRequest":o.z.object({"saml:Issuer":hv,"@_xmlns:samlp":o.z.string(),"@_xmlns:saml":o.z.string().optional(),"@_ForceAuthn":o.z.string().transform(t=>t.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(He)}))})),":@":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(He)}),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 gv=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()})}),mv=o.z.object({"ds:Transform":o.z.array(o.z.any()),":@":o.z.object({"@_Algorithm":o.z.string()})}),jf=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(mv)}),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(He)})])),":@":o.z.object({"@_URI":o.z.string().optional()}).optional()})]))}),o.z.object({"ds:SignatureValue":o.z.array(He)}),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(He)}),o.z.object({"ds:Exponent":o.z.array(He)})]))}))}),o.z.object({"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(He)}))}),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(He)}),o.z.object({"ds:Exponent":o.z.array(He)})]))})),"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(He)}))})]))})])),":@":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(He)}),jf,o.z.object({"samlp:Status":o.z.array(o.z.object({"samlp:StatusCode":o.z.array(He),":@":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(He)}),jf,o.z.object({"saml:Subject":o.z.array(o.z.union([o.z.object({"saml:NameID":o.z.array(He),":@":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(He)}))})),":@":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(He)}))})),":@":o.z.object({"@_AuthnInstant":o.z.string(),"@_SessionIndex":o.z.string(),"@_SessionNotOnOrAfter":o.z.string()})}),o.z.object({"saml:AttributeStatement":o.z.array(gv)})])),":@":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 _v={};(function(t){const e=":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=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+e+"]["+n+"]*",i=new RegExp("^"+r+"$"),s=function(c,l){const d=[];let u=l.exec(c);for(;u;){const f=[];f.startIndex=l.lastIndex-u[0].length;const g=u.length;for(let _=0;_<g;_++)f.push(u[_]);d.push(f),u=l.exec(c)}return d},a=function(c){const l=i.exec(c);return!(l===null||typeof l>"u")};t.isExist=function(c){return typeof c<"u"},t.isEmptyObject=function(c){return Object.keys(c).length===0},t.merge=function(c,l,d){if(l){const u=Object.keys(l),f=u.length;for(let g=0;g<f;g++)d==="strict"?c[u[g]]=[l[u[g]]]:c[u[g]]=l[u[g]]}},t.getValue=function(c){return t.isExist(c)?c:""},t.isName=a,t.getAllMatches=s,t.nameRegexp=r})(_v);function yv(t){return typeof t=="function"?t:Array.isArray(t)?e=>{for(const n of t)if(typeof n=="string"&&e===n||n instanceof RegExp&&n.test(e))return!0}:()=>!1}var wv=yv;const bv=`
2
2
  `;function vv(t,e){let n="";return e.format&&e.indentBy.length>0&&(n=bv),i_(t,e,"",n)}function i_(t,e,n,r){let i="",s=!1;for(let a=0;a<t.length;a++){const c=t[a],l=$v(c);if(l===void 0)continue;let d="";if(n.length===0?d=l:d=`${n}.${l}`,l===e.textNodeName){let w=c[l];kv(d,e)||(w=e.tagValueProcessor(l,w),w=o_(w,e)),s&&(i+=r),i+=w,s=!1;continue}else if(l===e.cdataPropName){s&&(i+=r),i+=`<![CDATA[${c[l][0][e.textNodeName]}]]>`,s=!1;continue}else if(l===e.commentPropName){i+=r+`<!--${c[l][0][e.textNodeName]}-->`,s=!0;continue}else if(l[0]==="?"){const w=Pf(c[":@"],e),k=l==="?xml"?"":r;let z=c[l][0][e.textNodeName];z=z.length!==0?" "+z:"",i+=k+`<${l}${z}${w}?>`,s=!0;continue}let u=r;u!==""&&(u+=e.indentBy);const f=Pf(c[":@"],e),g=r+`<${l}${f}`,_=i_(c[l],e,d,u);e.unpairedTags.indexOf(l)!==-1?e.suppressUnpairedNode?i+=g+">":i+=g+"/>":(!_||_.length===0)&&e.suppressEmptyNode?i+=g+"/>":_&&_.endsWith(">")?i+=g+`>${_}${r}</${l}>`:(i+=g+">",_&&r!==""&&(_.includes("/>")||_.includes("</"))?i+=r+e.indentBy+_+r:i+=_,i+=`</${l}>`),s=!0}return i}function $v(t){const e=Object.keys(t);for(let n=0;n<e.length;n++){const r=e[n];if(t.hasOwnProperty(r)&&r!==":@")return r}}function Pf(t,e){let n="";if(t&&!e.ignoreAttributes)for(let r in t){if(!t.hasOwnProperty(r))continue;let i=e.attributeValueProcessor(r,t[r]);i=o_(i,e),i===!0&&e.suppressBooleanAttributes?n+=` ${r.substr(e.attributeNamePrefix.length)}`:n+=` ${r.substr(e.attributeNamePrefix.length)}="${i}"`}return n}function kv(t,e){t=t.substr(0,t.length-e.textNodeName.length-1);let n=t.substr(t.lastIndexOf(".")+1);for(let r in e.stopNodes)if(e.stopNodes[r]===t||e.stopNodes[r]==="*."+n)return!0;return!1}function o_(t,e){if(t&&t.length>0&&e.processEntities)for(let n=0;n<e.entities.length;n++){const r=e.entities[n];t=t.replace(r.regex,r.val)}return t}var xv=vv;const Sv=xv,zv=wv,Av={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function Dn(t){this.options=Object.assign({},Av,t),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=zv(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Nv),this.processTextOrObjNode=Ev,this.options.format?(this.indentate=Cv,this.tagEndChar=`>
3
3
  `,this.newLine=`
4
4
  `):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}Dn.prototype.build=function(t){return this.options.preserveOrder?Sv(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0,[]).val)};Dn.prototype.j2x=function(t,e,n){let r="",i="";const s=n.join(".");for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a))if(typeof t[a]>"u")this.isAttribute(a)&&(i+="");else if(t[a]===null)this.isAttribute(a)||a===this.options.cdataPropName?i+="":a[0]==="?"?i+=this.indentate(e)+"<"+a+"?"+this.tagEndChar:i+=this.indentate(e)+"<"+a+"/"+this.tagEndChar;else if(t[a]instanceof Date)i+=this.buildTextValNode(t[a],a,"",e);else if(typeof t[a]!="object"){const c=this.isAttribute(a);if(c&&!this.ignoreAttributesFn(c,s))r+=this.buildAttrPairStr(c,""+t[a]);else if(!c)if(a===this.options.textNodeName){let l=this.options.tagValueProcessor(a,""+t[a]);i+=this.replaceEntitiesValue(l)}else i+=this.buildTextValNode(t[a],a,"",e)}else if(Array.isArray(t[a])){const c=t[a].length;let l="",d="";for(let u=0;u<c;u++){const f=t[a][u];if(!(typeof f>"u"))if(f===null)a[0]==="?"?i+=this.indentate(e)+"<"+a+"?"+this.tagEndChar:i+=this.indentate(e)+"<"+a+"/"+this.tagEndChar;else if(typeof f=="object")if(this.options.oneListGroup){const g=this.j2x(f,e+1,n.concat(a));l+=g.val,this.options.attributesGroupName&&f.hasOwnProperty(this.options.attributesGroupName)&&(d+=g.attrStr)}else l+=this.processTextOrObjNode(f,a,e,n);else if(this.options.oneListGroup){let g=this.options.tagValueProcessor(a,f);g=this.replaceEntitiesValue(g),l+=g}else l+=this.buildTextValNode(f,a,"",e)}this.options.oneListGroup&&(l=this.buildObjectNode(l,a,d,e)),i+=l}else if(this.options.attributesGroupName&&a===this.options.attributesGroupName){const c=Object.keys(t[a]),l=c.length;for(let d=0;d<l;d++)r+=this.buildAttrPairStr(c[d],""+t[a][c[d]])}else i+=this.processTextOrObjNode(t[a],a,e,n);return{attrStr:r,val:i}};Dn.prototype.buildAttrPairStr=function(t,e){return e=this.options.attributeValueProcessor(t,""+e),e=this.replaceEntitiesValue(e),this.options.suppressBooleanAttributes&&e==="true"?" "+t:" "+t+'="'+e+'"'};function Ev(t,e,n,r){const i=this.j2x(t,n+1,r.concat(e));return t[this.options.textNodeName]!==void 0&&Object.keys(t).length===1?this.buildTextValNode(t[this.options.textNodeName],e,i.attrStr,n):this.buildObjectNode(i.val,e,i.attrStr,n)}Dn.prototype.buildObjectNode=function(t,e,n,r){if(t==="")return e[0]==="?"?this.indentate(r)+"<"+e+n+"?"+this.tagEndChar:this.indentate(r)+"<"+e+n+this.closeTag(e)+this.tagEndChar;{let i="</"+e+this.tagEndChar,s="";return e[0]==="?"&&(s="?",i=""),(n||n==="")&&t.indexOf("<")===-1?this.indentate(r)+"<"+e+n+s+">"+t+i:this.options.commentPropName!==!1&&e===this.options.commentPropName&&s.length===0?this.indentate(r)+`<!--${t}-->`+this.newLine:this.indentate(r)+"<"+e+n+s+this.tagEndChar+t+this.indentate(r)+i}};Dn.prototype.closeTag=function(t){let e="";return this.options.unpairedTags.indexOf(t)!==-1?this.options.suppressUnpairedNode||(e="/"):this.options.suppressEmptyNode?e="/":e=`></${t}`,e};Dn.prototype.buildTextValNode=function(t,e,n,r){if(this.options.cdataPropName!==!1&&e===this.options.cdataPropName)return this.indentate(r)+`<![CDATA[${t}]]>`+this.newLine;if(this.options.commentPropName!==!1&&e===this.options.commentPropName)return this.indentate(r)+`<!--${t}-->`+this.newLine;if(e[0]==="?")return this.indentate(r)+"<"+e+n+"?"+this.tagEndChar;{let i=this.options.tagValueProcessor(e,t);return i=this.replaceEntitiesValue(i),i===""?this.indentate(r)+"<"+e+n+this.closeTag(e)+this.tagEndChar:this.indentate(r)+"<"+e+n+">"+i+"</"+e+this.tagEndChar}};Dn.prototype.replaceEntitiesValue=function(t){if(t&&t.length>0&&this.options.processEntities)for(let e=0;e<this.options.entities.length;e++){const n=this.options.entities[e];t=t.replace(n.regex,n.val)}return t};function Cv(t){return this.options.indentBy.repeat(t)}function Nv(t){return t.startsWith(this.options.attributeNamePrefix)&&t!==this.options.textNodeName?t.substr(this.attrPrefixLen):!1}var Iv=Dn;const jv=Iv;var Pv={XMLBuilder:jv};let s_=class{constructor(e,n){if(Mr(this,"alphabet"),Mr(this,"padding"),Mr(this,"decodeMap",new Map),e.length!==32)throw new Error("Invalid alphabet");if(this.alphabet=e,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<e.length;r++)this.decodeMap.set(e[r],r)}encode(e,n){let r="",i=0,s=0;for(let a=0;a<e.length;a++)for(i=i<<8|e[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(e,n){const r=n?.strict??!0,i=Math.ceil(e.length/8),s=[];for(let a=0;a<i;a++){let c=0;const l=[];for(let u=0;u<8;u++){const f=e[a*8+u];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 g=this.decodeMap.get(f)??null;if(g===null)throw new Error(`Invalid character: ${f}`);l.push(g)}if(c===8||c===7||c===5||c===2)throw new Error("Invalid padding");const d=(l[0]<<3)+(l[1]>>2);if(s.push(d),c<6){const u=((l[1]&3)<<6)+(l[2]<<1)+(l[3]>>4);s.push(u)}if(c<4){const u=((l[3]&255)<<4)+(l[4]>>1);s.push(u)}if(c<3){const u=((l[4]&1)<<7)+(l[5]<<2)+(l[6]>>3);s.push(u)}if(c<1){const u=((l[6]&7)<<5)+l[7];s.push(u)}}return Uint8Array.from(s)}};new s_("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");new s_("0123456789ABCDEFGHIJKLMNOPQRSTUV");let a_=class{constructor(e,n){if(Mr(this,"alphabet"),Mr(this,"padding"),Mr(this,"decodeMap",new Map),e.length!==64)throw new Error("Invalid alphabet");if(this.alphabet=e,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<e.length;r++)this.decodeMap.set(e[r],r)}encode(e,n){let r="",i=0,s=0;for(let a=0;a<e.length;a++)for(i=i<<8|e[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(e,n){const r=n?.strict??!0,i=Math.ceil(e.length/4),s=[];for(let a=0;a<i;a++){let c=0,l=0;for(let d=0;d<4;d++){const u=e[a*4+d];if(u==="="){if(a+1!==i)throw new Error(`Invalid character: ${u}`);c+=1;continue}if(u===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const f=this.decodeMap.get(u)??null;if(f===null)throw new Error(`Invalid character: ${u}`);l+=f<<6*(3-d)}s.push(l>>16&255),c<2&&s.push(l>>8&255),c<1&&s.push(l&255)}return Uint8Array.from(s)}};new a_("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");new a_("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");const Ov="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let Of=(t=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)e+=Ov[n[t]&63];return e};async function Tv(t,e){const n=t.notBefore||new Date().toISOString(),r=t.notAfter||new Date(new Date(n).getTime()+600*1e3).toISOString(),i=t.issueInstant||n,s=t.sessionNotOnOrAfter||r,a=t.responseId||`_${Of()}`,c=t.assertionId||`_${Of()}`,l=[{"samlp:Response":[{"saml:Issuer":[{"#text":t.issuer}]},{"samlp:Status":[{"samlp:StatusCode":[],":@":{"@_Value":"urn:oasis:names:tc:SAML:2.0:status:Success"}}]},{"saml:Assertion":[{"saml:Issuer":[{"#text":t.issuer}]},{"saml:Subject":[{"saml:NameID":[{"#text":t.email}],":@":{"@_Format":"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"}},{"saml:SubjectConfirmation":[{"saml:SubjectConfirmationData":[],":@":{"@_InResponseTo":t.inResponseTo,"@_NotOnOrAfter":r,"@_Recipient":t.destination}}],":@":{"@_Method":"urn:oasis:names:tc:SAML:2.0:cm:bearer"}}]},{"saml:Conditions":[{"saml:AudienceRestriction":[{"saml:Audience":[{"#text":t.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":t.sessionIndex,"@_SessionNotOnOrAfter":s}},{"saml:AttributeStatement":[{"saml:Attribute":[{"saml:AttributeValue":[{"#text":t.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":t.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":t.destination,"@_ID":a,"@_InResponseTo":t.inResponseTo,"@_IssueInstant":i,"@_Version":"2.0"}}];let d=new Pv.XMLBuilder({ignoreAttributes:!1,suppressEmptyNode:!0,preserveOrder:!0}).build(l);return t.signature&&e&&(d=await e.signSAML(d,t.signature.privateKeyPem,t.signature.cert)),t.encode===!1?d:btoa(d)}let c_=class{constructor(e){this.signUrl=e}async signSAML(e,n,r){const i=await fetch(this.signUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({xmlContent:e,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 Rv(t,e,n){const r=n?`<input type="hidden" name="RelayState" value="${n}" />`:"",i=`
@@ -62,34 +62,34 @@
62
62
  <\/script>
63
63
  </body>
64
64
 
65
- </html>`;return t.html(s,{headers:i})}const Kl=["openid","profile","email","address","phone"];async function Lv(t,e){const{tenantId:n,clientId:r,audience:i,requestedScopes:s}=e,a=s.filter(S=>Kl.includes(S)),l=(await t.env.data.resourceServers.list(n)).resource_servers.filter(S=>S.identifier===i);if(l.length===0)return{scopes:a,permissions:[]};const d=l[0];if(!d)return{scopes:a,permissions:[]};const u=d.options?.enforce_policies===!0,f=d.options?.token_dialect||"access_token",_=(await t.env.data.clientGrants.list(n,{q:`client_id:"${r}"`})).client_grants.find(S=>S.audience===i);if(!_)return{scopes:a,permissions:[]};const w=_.scope||[],k=(d.scopes||[]).map(S=>S.value);if(!u){let S;return s.length===0?S=w.filter(P=>k.includes(P)):S=s.filter(P=>k.includes(P)&&w.includes(P)),{scopes:[...new Set([...a,...S])],permissions:[]}}const z=w.filter(S=>k.includes(S));if(f==="access_token_authz")return{scopes:a,permissions:z};let N;return s.length===0?N=w.filter(S=>k.includes(S)):N=s.filter(S=>k.includes(S)&&w.includes(S)),{scopes:[...new Set([...a,...N])],permissions:z}}async function na(t,e){if(e.grantType===St.ClientCredential)return await Lv(t,{tenantId:e.tenantId,clientId:e.clientId,audience:e.audience,requestedScopes:e.requestedScopes});const{tenantId:n,userId:r,audience:i,requestedScopes:s,organizationId:a}=e;if(a&&!(await t.env.data.userOrganizations.list(n,{q:`user_id:${r}`,per_page:1e3})).userOrganizations.some(le=>le.organization_id===a))throw new B(403,{error:"access_denied",error_description:"User is not a member of the specified organization"});const c=s.filter(M=>Kl.includes(M)),d=(await t.env.data.resourceServers.list(n)).resource_servers.filter(M=>M.identifier===i);if(d.length===0)return{scopes:s,permissions:[]};const u=d[0];if(!u)return{scopes:s,permissions:[]};const f=(u.scopes||[]).map(M=>M.value),g=u.options?.enforce_policies===!0,_=u.options?.token_dialect||"access_token";if(!g)return{scopes:s,permissions:[]};const w=await t.env.data.userPermissions.list(n,r,void 0,a),k=await t.env.data.userRoles.list(n,r,void 0,""),z=a?await t.env.data.userRoles.list(n,r,void 0,a):[],N=[...k,...z],I=[];for(const M of N)(await t.env.data.rolePermissions.list(n,M.id)).forEach(le=>{le.resource_server_identifier===i&&I.push(le.permission_name)});const S=new Set;w.forEach(M=>{M.resource_server_identifier===i&&S.add(M.permission_name)}),I.forEach(M=>{S.add(M)});const E=Array.from(S),P=E.filter(M=>f.includes(M)),G=s.filter(M=>!f.includes(M)&&!Kl.includes(M));if(_==="access_token_authz")return{scopes:[...new Set([...c,...G])],permissions:P};const Z=s.filter(M=>f.includes(M)&&E.includes(M));return{scopes:[...new Set([...c,...Z,...G])],permissions:P}}const Tf=["sub","iss","aud","exp","nbf","iat","jti"];async function Ya(t,e){const{authParams:n,user:r,client:i,session_id:s,organization:a,permissions:c,impersonatingUser:l}=e,{signingKeys:d}=await t.env.data.keys.list({q:"type:jwt_signing"}),u=d.filter(E=>!E.revoked_at||new Date(E.revoked_at)>new Date),f=u[u.length-1];if(!f?.pkcs7)throw new B(500,{message:"No signing key available"});const g=rv(f.pkcs7),_=t.var.custom_domain?`https://${t.var.custom_domain}/`:t.env.ISSUER,w=n.audience||i.tenant.audience;if(!w)throw new B(400,{error:"invalid_request",error_description:"An audience must be specified in the request or configured as the tenant default_audience"});const k={aud:w,scope:n.scope||"",sub:r?.user_id||n.client_id,iss:_,tenant_id:t.var.tenant_id,sid:s,act:l?{sub:l.user_id}:void 0,org_id:a?a.id:void 0,permissions:c},z=r&&n.scope?.split(" ").includes("openid")?{aud:n.client_id,sub:r.user_id,iss:_,sid:s,nonce:n.nonce,given_name:r.given_name,family_name:r.family_name,nickname:r.nickname,picture:r.picture,locale:r.locale,name:r.name,email:r.email,email_verified:r.email_verified,act:l?{sub:l.user_id}:void 0,org_id:a?.id,org_name:a?.name}:void 0;t.env.hooks?.onExecuteCredentialsExchange&&await t.env.hooks.onExecuteCredentialsExchange({ctx:t,client:i,user:r,request:{ip:t.var.ip||"",user_agent:t.var.useragent||"",method:t.req.method,url:t.req.url},scope:n.scope||"",grant_type:""},{accessToken:{setCustomClaim:(E,P)=>{if(Tf.includes(E))throw new Error(`Cannot overwrite reserved claim '${E}'`);k[E]=P}},idToken:{setCustomClaim:(E,P)=>{if(Tf.includes(E))throw new Error(`Cannot overwrite reserved claim '${E}'`);z&&(z[E]=P)}},access:{deny:E=>{throw new B(400,{message:`Access denied: ${E}`})}},token:{createServiceToken:async E=>{const{createServiceToken:P}=await Promise.resolve().then(()=>Dv);return(await P(t,t.var.tenant_id,E.scope,E.expiresInSeconds)).access_token}}});const N={expiresIn:l?new ea(1,"h"):new ea(1,"d"),headers:{kid:f.kid}},I=await If("RS256",g,k,N),S=z?await If("RS256",g,z,N):void 0;return{access_token:I,refresh_token:e.refresh_token,id_token:S,token_type:"Bearer",expires_in:l?3600:86400}}async function l_(t,e){return{code:(await t.env.data.codes.create(e.client.tenant.id,{code_id:pe(),user_id:e.user.user_id,code_type:"authorization_code",login_id:e.login_id,expires_at:new Date(Date.now()+sv*1e3).toISOString(),code_challenge:e.authParams.code_challenge,code_challenge_method:e.authParams.code_challenge_method,redirect_uri:e.authParams.redirect_uri,state:e.authParams.state,nonce:e.authParams.nonce})).code_id,state:e.authParams.state}}async function d_(t,e){const{client:n,scope:r,audience:i=n.tenant.audience,session_id:s}=e;return await t.env.data.refreshTokens.create(n.tenant.id,{id:pe(),session_id:s,client_id:n.client_id,idle_expires_at:new Date(Date.now()+Za*1e3).toISOString(),user_id:e.user.user_id,device:{last_ip:t.var.ip,initial_ip:t.var.ip,last_user_agent:t.var.useragent||"",initial_user_agent:t.var.useragent||"",initial_asn:"",last_asn:""},resource_servers:[{audience:i,scopes:r}],rotating:!1})}async function u_(t,{user:e,client:n,loginSession:r}){const i=await t.env.data.sessions.create(n.tenant.id,{id:pe(),user_id:e.user_id,login_session_id:r.id,idle_expires_at:new Date(Date.now()+Za*1e3).toISOString(),device:{last_ip:t.var.ip||"",initial_ip:t.var.ip||"",last_user_agent:t.var.useragent||"",initial_user_agent:t.var.useragent||"",initial_asn:"",last_asn:""},clients:[n.client_id]});return await t.env.data.loginSessions.update(n.tenant.id,r.id,{session_id:i.id}),i}async function Gt(t,e){const{authParams:n,client:r,ticketAuth:i}=e;let{user:s}=e;const a=n.response_type||mt.CODE,c=n.response_mode||Ct.QUERY;if(i){if(!e.loginSession)throw new B(500,{message:"Login session not found for ticket auth."});s&&!e.skipHooks&&(e.authStrategy&&s.app_metadata?.strategy!==e.authStrategy.strategy&&(s.app_metadata={...s.app_metadata,strategy:e.authStrategy.strategy},await t.env.data.users.update(r.tenant.id,s.user_id,{app_metadata:{...s.app_metadata||{},strategy:e.authStrategy.strategy}})),await f_(t,t.env.data,r.tenant.id,s,e.loginSession,{client:r,authParams:n,authStrategy:e.authStrategy}));const _=nv(),w=pe(12),k=await t.env.data.codes.create(r.tenant.id,{code_id:pe(),code_type:"ticket",login_id:e.loginSession.id,expires_at:new Date(Date.now()+cv).toISOString(),code_verifier:[w,_].join("|"),redirect_uri:n.redirect_uri,state:n.state,nonce:n.nonce});return t.json({login_ticket:k.code_id,co_verifier:_,co_id:w})}let l=e.refreshToken,d=e.sessionId;if(!d&&e.loginSession?.session_id){d=e.loginSession.session_id;const _=await t.env.data.sessions.get(r.tenant.id,d);_&&!_.clients.includes(r.client_id)&&await t.env.data.sessions.update(r.tenant.id,d,{clients:[..._.clients,r.client_id]})}else if(!d){if(!e.loginSession)throw new B(500,{message:"Login session not found for creating a new session."});d=(await u_(t,{user:s,client:r,loginSession:e.loginSession})).id}if(!l&&n.scope?.split(" ").includes("offline_access")&&![mt.TOKEN,mt.CODE].includes(a)&&!e.impersonatingUser&&(l=(await d_(t,{user:s,client:r,session_id:d,scope:n.scope,audience:n.audience})).id),c===Ct.SAML_POST){if(!d)throw new v(500,{message:"Session ID not available for SAML response"});return Bv(t,e.client,e.authParams,s,d)}const u=await Uv(t,{authParams:n,user:s,client:r,session_id:d,refresh_token:l,authStrategy:e.authStrategy,loginSession:e.loginSession,responseType:a,skipHooks:e.skipHooks,organization:e.organization,impersonatingUser:e.impersonatingUser});if(u instanceof Response)return u;if(c===Ct.WEB_MESSAGE){if(!n.redirect_uri)throw new B(400,{message:"Redirect URI not allowed for WEB_MESSAGE response mode."});const _=new Headers;if(d){const z=ta(r.tenant.id,d,t.var.host||"");z&&_.set("set-cookie",z)}else console.warn("Session ID not available for WEB_MESSAGE, cookie will not be set.");const w=new URL(n.redirect_uri),k=`${w.protocol}//${w.host}`;return Vl(t,k,JSON.stringify({...u,state:n.state}),_)}if(!n.redirect_uri)throw new B(400,{message:"Redirect uri not found for this response mode."});const f=new Headers;if(d){const _=ta(r.tenant.id,d,t.var.custom_domain||t.req.header("host")||"");_&&f.set("set-cookie",_)}const g=new URL(n.redirect_uri);if("code"in u)g.searchParams.set("code",u.code),u.state&&g.searchParams.set("state",u.state);else if("access_token"in u)g.hash=new URLSearchParams({access_token:u.access_token,...u.id_token&&{id_token:u.id_token},token_type:u.token_type,expires_in:u.expires_in.toString(),...n.state&&{state:n.state},...n.scope&&{scope:n.scope}}).toString();else throw new B(500,{message:"Invalid token response for implicit flow."});return f.set("location",g.toString()),new Response("Redirecting",{status:302,headers:f})}async function Uv(t,e){let{user:n}=e;const r=e.responseType||mt.TOKEN;if(n&&e.organization&&!(await t.env.data.userOrganizations.list(e.client.tenant.id,{q:`user_id:${n.user_id}`,per_page:1e3})).userOrganizations.some(d=>d.organization_id===e.organization.id))throw new B(403,{error:"access_denied",error_description:"User is not a member of the specified organization"});let i=e.authParams.scope||"",s=[];if(e.authParams.audience)try{let c;if(e.grantType===St.ClientCredential||!n&&!e.user)c=await na(t,{grantType:St.ClientCredential,tenantId:e.client.tenant.id,clientId:e.client.client_id,audience:e.authParams.audience,requestedScopes:e.authParams.scope?.split(" ")||[],organizationId:e.organization?.id});else{const l=n?.user_id||e.user?.user_id;if(!l)throw new B(400,{error:"invalid_request",error_description:"User ID is required for user-based grants"});c=await na(t,{grantType:e.grantType,tenantId:e.client.tenant.id,userId:l,clientId:e.client.client_id,audience:e.authParams.audience,requestedScopes:e.authParams.scope?.split(" ")||[],organizationId:e.organization?.id})}i=c.scopes.join(" "),s=c.permissions}catch(c){if(c instanceof v)throw c}const a={...e.authParams,scope:i};if(e.loginSession&&n&&!e.skipHooks){e.authStrategy&&n.app_metadata?.strategy!==e.authStrategy.strategy&&(n.app_metadata={...n.app_metadata,strategy:e.authStrategy.strategy},await t.env.data.users.update(e.client.tenant.id,n.user_id,{app_metadata:{...n.app_metadata||{},strategy:e.authStrategy.strategy}}));const c=await f_(t,t.env.data,e.client.tenant.id,n,e.loginSession,{client:e.client,authParams:a,authStrategy:e.authStrategy});if(c instanceof Response)return c;n=c}if(r===mt.CODE){if(!n||!e.loginSession)throw new B(500,{message:"User and loginSession is required for code flow"});return await l_(t,{user:n,client:e.client,authParams:a,login_id:e.loginSession.id})}else return Ya(t,{...e,user:n,authParams:a,permissions:s})}const Rf="auth-service";async function Qa(t,e,n,r){const i=await t.env.data.tenants.get(e);if(!i)throw new Error(`Tenant not found: ${e}`);const s={client_id:Rf,tenant:i,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),name:"Auth Service",global:!1,is_first_party:!0,oidc_conformant:!1,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 Ya(t,{client:s,authParams:{client_id:Rf,response_type:mt.TOKEN,scope:n}});return{access_token:a.access_token,token_type:a.token_type,expires_in:r||3600}}const Dv=Object.freeze(Object.defineProperty({__proto__:null,createServiceToken:Qa},Symbol.toStringTag,{value:"Module"}));async function ec(t,e,n){const r=await Qa(t,n.tenant_id,"webhook");for await(const i of e.filter(s=>"url"in s))(await fetch(i.url,{method:"POST",headers:{Authorization:`Bearer ${r.access_token}`,"Content-Type":"application/json"},body:JSON.stringify(n)})).ok||ie(t,n.tenant_id,{type:te.FAILED_HOOK,description:`Failed to invoke hook ${i.hook_id}`})}function Mv(t){return async(e,n)=>{const{hooks:r}=await t.env.data.hooks.list(e);return await ec(t,r,{tenant_id:e,user:n,trigger_id:"post-user-registration"}),n}}function qv(t){return async(e,n)=>{const{hooks:r}=await t.env.data.hooks.list(e,{q:"trigger_id:pre-user-registration",page:0,per_page:100,include_totals:!1});await ec(t,r,{tenant_id:e,email:n,trigger_id:"pre-user-registration"})}}async function Fv(t,e){const{hooks:n}=await t.env.data.hooks.list(e,{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 Hv(t){return async(e,n)=>{const{hooks:r}=await t.env.data.hooks.list(e,{q:"trigger_id:pre-user-deletion",page:0,per_page:100,include_totals:!1});return await ec(t,r,{tenant_id:e,user:n,trigger_id:"pre-user-deletion"}),n}}function Vv(t){return async(e,n)=>{const{hooks:r}=await t.env.data.hooks.list(e,{q:"trigger_id:post-user-deletion",page:0,per_page:100,include_totals:!1});return await ec(t,r,{tenant_id:e,user:n,trigger_id:"post-user-deletion"}),n}}function Bf(t){return typeof t.form_id=="string"}function Lf(t,e){const n=t.match(/^\{\{context\.user\.(\w+)\}\}$/);if(n){const r=n[1],i=e.user[r];return typeof i=="string"?i:""}return t}function Kv(t,e){const n=t.operator?.toLowerCase(),r=t.field?Lf(t.field,e):"",i=t.value||"";switch(n){case"ends_with":return r.endsWith(i);case"starts_with":return r.startsWith(i);case"contains":return r.includes(i);case"equals":case"eq":return r===i;case"not_equals":case"neq":return r!==i;default:if(t.operands&&Array.isArray(t.operands)){for(const s of t.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&&Lf(`{{context.user.${a}}}`,e).endsWith(c))return!0}}return!1}}function Gv(t,e,n,r=10){let i=e,s=0;for(;s<r;){if(i==="$ending")return null;const a=t.find(c=>c.id===i);if(!a)return null;if(a.type==="STEP")return a.id;if(a.type==="ROUTER"){const c=a;let l=null;for(const d of c.config.rules)if(Kv(d.condition,n)){l=d.next_node;break}if(l||(l=c.config.fallback),!l)return null;i=l,s++;continue}return null}return null}async function Wv(t,e,n,r){const i=t.env.data,s=t.var.tenant_id||t.req.header("tenant-id");if(!s)throw new v(400,{message:"Missing tenant_id in context"});const a=await i.forms.get(s,e);if(!a)throw new v(404,{message:"Form not found for post-user-login hook"});let c=a.start?.next_node;if(!c&&a.nodes&&a.nodes.length>0&&(c=a.nodes.find(u=>u.type==="STEP")?.id),!c)throw new v(400,{message:"No start node found in form"});if(r&&a.nodes){const d=Gv(a.nodes,c,{user:r});if(!d)return new Response(null,{status:302,headers:{location:`/u/login/identifier?state=${encodeURIComponent(n.id)}`}});c=d}let l=`/u/forms/${a.id}/nodes/${c}?state=${encodeURIComponent(n.id)}`;return new Response(null,{status:302,headers:{location:l}})}function Uf(t){return typeof t.page_id=="string"&&typeof t.enabled=="boolean"}async function Jv(t,e,n,r,i){const s=t.env.data,a=t.var.tenant_id||t.req.header("tenant-id");if(!a)throw new v(400,{message:"Missing tenant_id in context"});if(i&&!(await s.userPermissions.list(a,r.user_id)).some(u=>u.permission_name===i))return r;let c=`/u/${e}?state=${encodeURIComponent(n.id)}`;return new Response(null,{status:302,headers:{location:c}})}function sr(t,e){return{createServiceToken:async n=>(await Qa(t,e,n.scope,n.expiresInSeconds)).access_token}}function Df(t){return typeof t.url=="string"}function Xv(t,e){return async(n,r)=>{if(t.var.client_id){const a=await e.legacyClients.get(t.var.client_id);if(!a)throw new B(400,{message:"Client not found"});r.email&&await Yv(t,a,e,r.email)}const i={method:t.req.method,ip:t.req.query("x-real-ip")||"",user_agent:t.req.query("user-agent"),url:t.var.loginSession?.authorization_url||t.req.url};if(t.env.hooks?.onExecutePreUserRegistration)try{await t.env.hooks.onExecutePreUserRegistration({ctx:t,user:r,request:i},{user:{setUserMetadata:async(a,c)=>{r[a]=c}},token:sr(t,n)})}catch{ie(t,n,{type:te.FAILED_SIGNUP,description:"Pre user registration hook failed"})}let s=await Kb(e)(n,r);if(t.env.hooks?.onExecutePostUserRegistration)try{await t.env.hooks.onExecutePostUserRegistration({ctx:t,user:r,request:i},{user:{},token:sr(t,n)})}catch{ie(t,n,{type:te.FAILED_SIGNUP,description:"Post user registration hook failed"})}return await Mv(t)(n,s),s}}function Zv(t,e){return async(n,r,i)=>{if(Object.keys(i).length===1&&"linked_to"in i)return e.users.update(n,r,i);const s=await e.users.get(n,r);if(!s)throw new B(404,{message:"User not found"});const a={method:t.req.method,ip:t.var.ip||t.get("ip")||"",user_agent:t.var.useragent||t.get("useragent")||"",url:t.req.url};if(t.env.hooks?.onExecutePreUserUpdate)try{await t.env.hooks.onExecutePreUserUpdate({ctx:t,tenant:{id:n},user_id:r,user:s,updates:i,request:a},{user:{setUserMetadata:async(c,l)=>{i[c]=l}},cancel:()=>{throw new B(400,{message:"User update cancelled by pre-update hook"})},token:sr(t,n)})}catch{throw new B(400,{message:"Pre user update hook failed"})}if(await e.users.update(n,r,i),i.email||i.email_verified){const c=await e.users.get(n,r);if(c&&c.email&&c.email_verified){const{users:l}=await e.users.list(n,{page:0,per_page:10,include_totals:!1,q:`email:${c.email}`}),d=l.filter(u=>u.email_verified&&u.user_id!==r&&!u.linked_to);d.length>0&&await e.users.update(n,r,{linked_to:d[0].user_id})}}return i.email&&ie(t,n,{type:te.SUCCESS_CHANGE_EMAIL,description:`Email updated to ${i.email}`,userId:r}),!0}}async function p_(t,e,n,r,i="email"){if(e.client_metadata?.disable_sign_ups==="true"){const a=t.var.loginSession?.authorization_url;if(a&&new URL(a).searchParams.get("screen_hint")==="signup")return{allowed:!0};if(!await tc({userAdapter:n.users,tenant_id:e.tenant.id,email:r}))return{allowed:!1,reason:"Public signup is disabled for this client"}}if(t.env.hooks?.onExecuteValidateSignupEmail){const a={method:t.req.method,ip:t.var.ip||t.get("ip")||"",user_agent:t.var.useragent||t.get("useragent")||"",url:t.req.url};let c=!1,l;try{if(await t.env.hooks.onExecuteValidateSignupEmail({ctx:t,client:e,request:a,tenant:{id:e.tenant.id},user:{email:r,connection:i}},{deny:d=>{c=!0,l=d},token:sr(t,e.tenant.id)}),c)return{allowed:!1,reason:l}}catch{return{allowed:!1,reason:"Signup validation hook failed"}}}const s=await Fv(t,e.tenant.id);if(s&&"url"in s)try{const a=await Qa(t,e.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:e.tenant.id,email:r,connection:i,client_id:e.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{ie(t,e.tenant.id,{type:te.FAILED_HOOK,description:"Validate signup email webhook failed"})}return{allowed:!0}}async function Yv(t,e,n,r){const i=await p_(t,e,n,r);if(!i.allowed)throw ie(t,e.tenant.id,{type:te.FAILED_SIGNUP,description:i.reason||"Signup not allowed"}),new B(400,{message:i.reason||"Signups are disabled for this client"});await qv(t)(e.tenant.id,r)}function Qv(t,e){return async(n,r)=>{const i=await e.users.get(n,r);if(!i)return!1;const s={method:t.req.method,ip:t.var.ip||t.get("ip")||"",user_agent:t.var.useragent||t.get("useragent")||"",url:t.req.url};if(t.env.hooks?.onExecutePreUserDeletion)try{await t.env.hooks.onExecutePreUserDeletion({ctx:t,user:i,user_id:r,request:s,tenant:{id:n}},{cancel:()=>{throw new B(400,{message:"User deletion cancelled by pre-deletion hook"})},token:sr(t,n)})}catch(c){throw c instanceof v?c:(ie(t,n,{type:te.FAILED_HOOK,description:`Pre user deletion hook failed: ${c instanceof Error?c.message:String(c)}`}),new B(400,{message:"Pre user deletion hook failed"}))}try{await Hv(t)(n,i)}catch(c){throw ie(t,n,{type:te.FAILED_HOOK,description:`Pre user deletion webhook failed: ${c instanceof Error?c.message:String(c)}`}),new B(400,{message:"Pre user deletion webhook failed"})}const a=await e.users.remove(n,r);if(a){ie(t,n,{type:te.SUCCESS_USER_DELETION,description:`user_id: ${r}`,strategy:i.provider||"auth0",strategy_type:i.is_social?"social":"database",connection:i.connection||"",body:{tenant:n,connection:i.connection||""}});try{await Vv(t)(n,i)}catch(c){ie(t,n,{type:te.FAILED_HOOK,description:`Post user deletion webhook failed: ${c instanceof Error?c.message:String(c)}`})}}if(a&&t.env.hooks?.onExecutePostUserDeletion)try{await t.env.hooks.onExecutePostUserDeletion({ctx:t,user:i,user_id:r,request:s,tenant:{id:n}},{token:sr(t,n)})}catch(c){ie(t,n,{type:te.FAILED_HOOK,description:`Post user deletion hook failed: ${c instanceof Error?c.message:String(c)}`})}return a}}function qo(t,e){const n=e;return{...e,users:{...e.users,create:Xv(t,n),update:Zv(t,n),remove:Qv(t,n)}}}async function e2(t,e,n,r,i,s){let a=[];try{a=(await e.userRoles.list(n,r.user_id,void 0,"")).map(g=>g.name||g.id)}catch(u){console.error("Error fetching user roles:",u)}let c={};if(r.connection)try{const f=(await e.connections.list(n,{page:0,per_page:100,include_totals:!1})).connections.find(g=>g.name===r.connection);f&&(c={id:f.id,name:f.name,strategy:f.strategy||r.provider,metadata:f.options||{}})}catch(u){console.error("Error fetching connection info:",u)}let l;try{if(i.authParams?.organization){const u=await e.organizations.get(n,i.authParams.organization);u&&(l={id:u.id,name:u.name,display_name:u.display_name||u.name,metadata:u.metadata||{}})}}catch(u){console.error("Error fetching organization info:",u)}const d=t.get("countryCode");return{ctx:t,client:s.client,user:r,request:{asn:void 0,ip:t.get("ip")||"",user_agent:t.get("useragent"),method:t.req.method,url:t.req.url,geoip:{cityName:void 0,continentCode:void 0,countryCode:d||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:t.get("ip"),initial_user_agent:t.get("useragent"),last_ip:r.last_ip||t.get("ip"),last_user_agent:t.get("useragent")}}}}async function f_(t,e,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(ie(t,n,{type:te.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 e.users.update(n,r.user_id,{last_login:new Date().toISOString(),last_ip:t.var.ip||"",login_count:r.login_count+1}),t.env.hooks?.onExecutePostLogin&&s?.client&&s?.authParams&&i){let u=null;const f=await e2(t,e,n,r,i,{client:s.client,authParams:s.authParams});if(await t.env.hooks.onExecutePostLogin(f,{prompt:{render:g=>{}},redirect:{sendUserTo:(g,_)=>{const w=new URL(g,t.req.url);w.searchParams.set("state",i.id),_?.query&&Object.entries(_.query).forEach(([k,z])=>{w.searchParams.set(k,z)}),u=w.toString()},encodeToken:g=>JSON.stringify({payload:g.payload,exp:Date.now()+(g.expiresInSeconds||900)*1e3}),validateToken:g=>null},token:sr(t,n)}),u)return new Response(null,{status:302,headers:{location:u}})}const{hooks:l}=await e.hooks.list(n,{q:"trigger_id:post-user-login",page:0,per_page:100,include_totals:!1});if(i){const u=l.find(g=>g.enabled&&Bf(g));if(u&&Bf(u))return Wv(t,u.form_id,i,r);const f=l.find(g=>g.enabled&&Uf(g));if(f&&Uf(f))return Jv(t,f.page_id,i,r,f.permission_required)}const d=l.filter(u=>u.enabled&&Df(u));for(const u of d)if(Df(u))try{await fetch(u.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tenant_id:n,user:r,trigger_id:"post-user-login"})})}catch{ie(t,n,{type:te.FAILED_HOOK,description:`Failed to invoke post-user-login webhook: ${u.url}`})}return r}function t2(t){return qo(t,t.env.data)}async function Ru(t,e,n){return(await t.list(e,{page:0,per_page:10,include_totals:!1,q:`email:${n}`})).users}async function pi({userAdapter:t,tenant_id:e,username:n,provider:r}){const i=r==="sms"?`phone_number:${n}`:`email:${n}`,{users:s}=await t.list(e,{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 email and provider"),s[0]||null}async function tc({userAdapter:t,tenant_id:e,email:n}){const{users:r}=await t.list(e,{page:0,per_page:10,include_totals:!1,q:`email:${n}`}),i=r.filter(c=>!(c.provider==="auth2"&&!c.email_verified));if(i.length===0)return;const s=i.filter(c=>!c.linked_to);if(s.length>0)return s.length>1&&console.error("More than one primary user found for same email"),s[0];const a=await t.get(e,i[0]?.linked_to);if(!a)throw new Error("Primary account not found");return a}async function yo({userAdapter:t,tenant_id:e,username:n,provider:r}){const i=await pi({userAdapter:t,tenant_id:e,username:n,provider:r});return i?i.linked_to?t.get(e,i.linked_to):i:null}async function nc(t,e){const{username:n,provider:r,connection:i,client:s,userId:a,isSocial:c,profileData:l={},ip:d=""}=e;let u=await yo({userAdapter:t.env.data.users,tenant_id:e.client.tenant.id,username:n,provider:r});if(!u){const f={user_id:`${r}|${a||Xa()}`,email:i!=="sms"?n:void 0,phone_number:i==="sms"?n:void 0,name:n,provider:r,connection:i,email_verified:!0,last_ip:d,is_social:c,last_login:new Date().toISOString(),profileData:JSON.stringify(l)};u=await t2(t).users.create(s.tenant.id,f),t.set("user_id",u.user_id)}return u}const Te=o.z.object({page:o.z.string().min(0).optional().default("0").transform(t=>parseInt(t,10)).openapi({description:"The page number where 0 is the first page"}),per_page:o.z.string().min(1).optional().default("10").transform(t=>parseInt(t,10)).openapi({description:"The number of items per page"}),include_totals:o.z.string().optional().default("false").transform(t=>t==="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"})});function Ke(t){if(!t)return;const[e,n]=t.split(":"),r=n==="1"?"asc":"desc";if(!(!e||!r))return{sort_by:e,sort_order:r}}var n2={Stringify:1},On=(t,e)=>{const n=new String(t);return n.isEscaped=!0,n.callbacks=e,n},r2=/[&<>'"]/,i2=async(t,e)=>{let n="";e||=[];const r=await Promise.all(t);for(let i=r.length-1;n+=r[i],i--,!(i<0);i--){let s=r[i];typeof s=="object"&&e.push(...s.callbacks||[]);const a=s.isEscaped;if(s=await(typeof s=="object"?s.toString():s),typeof s=="object"&&e.push(...s.callbacks||[]),s.isEscaped??a)n+=s;else{const c=[n];qr(s,c),n=c[0]}}return On(n,e)},qr=(t,e)=>{const n=t.search(r2);if(n===-1){e[0]+=t;return}let r,i,s=0;for(i=n;i<t.length;i++){switch(t.charCodeAt(i)){case 34:r="&quot;";break;case 39:r="&#39;";break;case 38:r="&amp;";break;case 60:r="&lt;";break;case 62:r="&gt;";break;default:continue}e[0]+=t.substring(s,i)+r,s=i+1}e[0]+=t.substring(s,i)},o2=t=>{const e=t.callbacks;if(!e?.length)return t;const n=[t],r={};return e.forEach(i=>i({phase:n2.Stringify,buffer:n,context:r})),n[0]},Bu=Symbol("RENDERER"),Gl=Symbol("ERROR_HANDLER"),ke=Symbol("STASH"),h_=Symbol("INTERNAL"),s2=Symbol("MEMO"),ra=Symbol("PERMALINK"),Mf=t=>(t[h_]=!0,t),g_=t=>({value:e,children:n})=>{if(!n)return;const r={children:[{tag:Mf(()=>{t.push(e)}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:Mf(()=>{t.pop()}),props:{}});const i={tag:"",props:r,type:""};return i[Gl]=s=>{throw t.pop(),s},i},m_=t=>{const e=[t],n=g_(e);return n.values=e,n.Provider=n,Jr.push(n),n},Jr=[],__=t=>{const e=[t],n=(r=>{e.push(r.value);let i;try{i=r.children?(Array.isArray(r.children)?new v_("",{},r.children):r.children).toString():""}finally{e.pop()}return i instanceof Promise?i.then(s=>On(s,s.callbacks)):On(i)});return n.values=e,n.Provider=n,n[Bu]=g_(e),Jr.push(n),n},fi=t=>t.values.at(-1),Es={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},Wl={},Cs="data-precedence",Fo=t=>Array.isArray(t)?t:[t],qf=new WeakMap,Ff=(t,e,n,r)=>({buffer:i,context:s})=>{if(!i)return;const a=qf.get(s)||{};qf.set(s,a);const c=a[t]||=[];let l=!1;const d=Es[t];if(d.length>0){e:for(const[,u]of c)for(const f of d)if((u?.[f]??null)===n?.[f]){l=!0;break e}}if(l?i[0]=i[0].replaceAll(e,""):d.length>0?c.push([e,n,r]):c.unshift([e,n,r]),i[0].indexOf("</head>")!==-1){let u;if(r===void 0)u=c.map(([f])=>f);else{const f=[];u=c.map(([g,,_])=>{let w=f.indexOf(_);return w===-1&&(f.push(_),w=f.length-1),[g,w]}).sort((g,_)=>g[1]-_[1]).map(([g])=>g)}u.forEach(f=>{i[0]=i[0].replaceAll(f,"")}),i[0]=i[0].replace(/(?=<\/head>)/,u.join(""))}},Ho=(t,e,n)=>On(new Nt(t,n,Fo(e??[])).toString()),Vo=(t,e,n,r)=>{if("itemProp"in n)return Ho(t,e,n);let{precedence:i,blocking:s,...a}=n;i=r?i??"":void 0,r&&(a[Cs]=i);const c=new Nt(t,a,Fo(e||[])).toString();return c instanceof Promise?c.then(l=>On(c,[...l.callbacks||[],Ff(t,l,a,i)])):On(c,[Ff(t,c,a,i)])},a2=({children:t,...e})=>{const n=Lu();if(n){const r=fi(n);if(r==="svg"||r==="head")return new Nt("title",e,Fo(t??[]))}return Vo("title",t,e,!1)},c2=({children:t,...e})=>{const n=Lu();return["src","async"].some(r=>!e[r])||n&&fi(n)==="head"?Ho("script",t,e):Vo("script",t,e,!1)},l2=({children:t,...e})=>["href","precedence"].every(n=>n in e)?(e["data-href"]=e.href,delete e.href,Vo("style",t,e,!0)):Ho("style",t,e),d2=({children:t,...e})=>["onLoad","onError"].some(n=>n in e)||e.rel==="stylesheet"&&(!("precedence"in e)||"disabled"in e)?Ho("link",t,e):Vo("link",t,e,"precedence"in e),u2=({children:t,...e})=>{const n=Lu();return n&&fi(n)==="head"?Ho("meta",t,e):Vo("meta",t,e,!1)},y_=(t,{children:e,...n})=>new Nt(t,n,Fo(e??[])),p2=t=>(typeof t.action=="function"&&(t.action=ra in t.action?t.action[ra]:void 0),y_("form",t)),w_=(t,e)=>(typeof e.formAction=="function"&&(e.formAction=ra in e.formAction?e.formAction[ra]:void 0),y_(t,e)),f2=t=>w_("input",t),h2=t=>w_("button",t);const dl=Object.freeze(Object.defineProperty({__proto__:null,button:h2,form:p2,input:f2,link:d2,meta:u2,script:c2,style:l2,title:a2},Symbol.toStringTag,{value:"Module"}));var g2=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),ia=t=>g2.get(t)||t,b_=(t,e)=>{for(const[n,r]of Object.entries(t)){const i=n[0]==="-"||!/[A-Z]/.test(n)?n:n.replace(/[A-Z]/g,s=>`-${s.toLowerCase()}`);e(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)}},wo=void 0,Lu=()=>wo,m2=t=>/[A-Z]/.test(t)&&t.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)/)?t.replace(/([A-Z])/g,"-$1").toLowerCase():t,_2=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],y2=["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"],Uu=(t,e)=>{for(let n=0,r=t.length;n<r;n++){const i=t[n];if(typeof i=="string")qr(i,e);else{if(typeof i=="boolean"||i===null||i===void 0)continue;i instanceof Nt?i.toStringToBuffer(e):typeof i=="number"||i.isEscaped?e[0]+=i:i instanceof Promise?e.unshift("",i):Uu(i,e)}}},Nt=class{tag;props;key;children;isEscaped=!0;localContexts;constructor(t,e,n){this.tag=t,this.props=e,this.children=n}get type(){return this.tag}get ref(){return this.props.ref||null}toString(){const t=[""];this.localContexts?.forEach(([e,n])=>{e.values.push(n)});try{this.toStringToBuffer(t)}finally{this.localContexts?.forEach(([e])=>{e.values.pop()})}return t.length===1?"callbacks"in t?o2(On(t[0],t.callbacks)).toString():t[0]:i2(t,t.callbacks)}toStringToBuffer(t){const e=this.tag,n=this.props;let{children:r}=this;t[0]+=`<${e}`;const i=wo&&fi(wo)==="svg"?s=>m2(ia(s)):s=>ia(s);for(let[s,a]of Object.entries(n))if(s=i(s),s!=="children"){if(s==="style"&&typeof a=="object"){let c="";b_(a,(l,d)=>{d!=null&&(c+=`${c?";":""}${l}:${d}`)}),t[0]+=' style="',qr(c,t),t[0]+='"'}else if(typeof a=="string")t[0]+=` ${s}="`,qr(a,t),t[0]+='"';else if(a!=null)if(typeof a=="number"||a.isEscaped)t[0]+=` ${s}="${a}"`;else if(typeof a=="boolean"&&y2.includes(s))a&&(t[0]+=` ${s}=""`);else if(s==="dangerouslySetInnerHTML"){if(r.length>0)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");r=[On(a.__html)]}else if(a instanceof Promise)t[0]+=` ${s}="`,t.unshift('"',a);else if(typeof a=="function"){if(!s.startsWith("on")&&s!=="ref")throw new Error(`Invalid prop '${s}' of type 'function' supplied to '${e}'.`)}else t[0]+=` ${s}="`,qr(a.toString(),t),t[0]+='"'}if(_2.includes(e)&&r.length===0){t[0]+="/>";return}t[0]+=">",Uu(r,t),t[0]+=`</${e}>`}},ul=class extends Nt{toStringToBuffer(t){const{children:e}=this,n={...this.props};e.length&&(n.children=e.length===1?e[0]:e);const r=this.tag.call(null,n);if(!(typeof r=="boolean"||r==null))if(r instanceof Promise)if(Jr.length===0)t.unshift("",r);else{const i=Jr.map(s=>[s,s.values.at(-1)]);t.unshift("",r.then(s=>(s instanceof Nt&&(s.localContexts=i),s)))}else r instanceof Nt?r.toStringToBuffer(t):typeof r=="number"||r.isEscaped?(t[0]+=r,r.callbacks&&(t.callbacks||=[],t.callbacks.push(...r.callbacks))):qr(r,t)}},v_=class extends Nt{toStringToBuffer(t){Uu(this.children,t)}},w2=(t,e,...n)=>{e??={},n.length&&(e.children=n.length===1?n[0]:n);const r=e.key;delete e.key;const i=Ns(t,e,n);return i.key=r,i},Hf=!1,Ns=(t,e,n)=>{if(!Hf){for(const r in Wl)dl[r][Bu]=Wl[r];Hf=!0}return typeof t=="function"?new ul(t,e,n):dl[t]?new ul(dl[t],e,n):t==="svg"||t==="head"?(wo||=__(""),new Nt(t,e,[new ul(wo,{value:t},n)])):new Nt(t,e,n)},bo=({children:t})=>new v_("",{children:t},Array.isArray(t)?t:t?[t]:[]),b2=(t,e,...n)=>{let r;if(n.length>0)r=n;else{const i=t.props.children;r=Array.isArray(i)?i:[i]}return w2(t.tag,{...t.props,...e},...r)};function p(t,e,n){let r;if(!e||!("children"in e))r=Ns(t,e,[]);else{const i=e.children;r=Array.isArray(i)?Ns(t,e,i):Ns(t,e,[i])}return r.key=n,r}var Vf;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Vf||(Vf={}));var Kf;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Kf||(Kf={}));function v2(t){return $_(t,$2,vo.Include)}function Du(t){return $_(t,k2,vo.None)}function $_(t,e,n){let r="";for(let i=0;i<t.byteLength;i+=3){let s=0,a=0;for(let c=0;c<3&&i+c<t.byteLength;c++)s=s<<8|t[i+c],a+=8;for(let c=0;c<4;c++)a>=6?(r+=e[s>>a-6&63],a-=6):a>0?(r+=e[s<<6-a&63],a=0):n===vo.Include&&(r+="=")}return r}const $2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",k2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var vo;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(vo||(vo={}));var Gf;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Gf||(Gf={}));class x2{uint8(e,n){if(e.byteLength<n+1)throw new TypeError("Insufficient bytes");return e[n]}uint16(e,n){if(e.byteLength<n+2)throw new TypeError("Insufficient bytes");return e[n]<<8|e[n+1]}uint32(e,n){if(e.byteLength<n+4)throw new TypeError("Insufficient bytes");let r=0;for(let i=0;i<4;i++)r|=e[n+i]<<24-i*8;return r}uint64(e,n){if(e.byteLength<n+8)throw new TypeError("Insufficient bytes");let r=0n;for(let i=0;i<8;i++)r|=BigInt(e[n+i])<<BigInt(56-i*8);return r}putUint8(e,n,r){if(e.length<r+1)throw new TypeError("Not enough space");if(n<0||n>255)throw new TypeError("Invalid uint8 value");e[r]=n}putUint16(e,n,r){if(e.length<r+2)throw new TypeError("Not enough space");if(n<0||n>65535)throw new TypeError("Invalid uint16 value");e[r]=n>>8,e[r+1]=n&255}putUint32(e,n,r){if(e.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++)e[r+i]=n>>(3-i)*8&255}putUint64(e,n,r){if(e.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++)e[r+i]=Number(n>>BigInt((7-i)*8)&0xffn)}}const Wf=new x2;function Mt(t,e){return(t<<32-e|t>>>e)>>>0}function S2(t){const e=new z2;return e.update(t),e.digest()}class z2{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(e){if(this.l+=BigInt(e.byteLength)*8n,this.currentBlockSize+e.byteLength<64){this.blocks.set(e,this.currentBlockSize),this.currentBlockSize+=e.byteLength;return}let n=0;if(this.currentBlockSize>0){const r=e.slice(0,64-this.currentBlockSize);this.blocks.set(r,this.currentBlockSize),this.process(),n+=r.byteLength,this.currentBlockSize=0}for(;n+64<=e.byteLength;){const r=e.slice(n,n+64);this.blocks.set(r),this.process(),n+=64}if(e.byteLength-n>0){const r=e.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),Wf.putUint64(this.blocks,this.l,this.blockSize-8),this.process();const e=new Uint8Array(32);for(let n=0;n<8;n++)Wf.putUint32(e,this.H[n],n*4);return e}process(){for(let d=0;d<16;d++)this.w[d]=(this.blocks[d*4]<<24|this.blocks[d*4+1]<<16|this.blocks[d*4+2]<<8|this.blocks[d*4+3])>>>0;for(let d=16;d<64;d++){const u=(Mt(this.w[d-2],17)^Mt(this.w[d-2],19)^this.w[d-2]>>>10)>>>0,f=(Mt(this.w[d-15],7)^Mt(this.w[d-15],18)^this.w[d-15]>>>3)>>>0;this.w[d]=u+this.w[d-7]+f+this.w[d-16]|0}let e=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 d=0;d<64;d++){const u=(Mt(s,6)^Mt(s,11)^Mt(s,25))>>>0,f=(s&a^~s&c)>>>0,g=l+u+f+A2[d]+this.w[d]|0,_=(Mt(e,2)^Mt(e,13)^Mt(e,22))>>>0,w=(e&n^e&r^n&r)>>>0,k=_+w|0;l=c,c=a,a=s,s=i+g|0,i=r,r=n,n=e,e=g+k|0}this.H[0]=e+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 A2=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 k_{data;constructor(e){this.data=e}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 x_(t){const e=S2(new TextEncoder().encode(t));return Du(e)}function rc(){const t=new Uint8Array(32);return crypto.getRandomValues(t),Du(t)}function S_(){const t=new Uint8Array(32);return crypto.getRandomValues(t),Du(t)}function E2(t,e){if(e.length!==1)throw new TypeError("Invalid character string");let n=0;for(;n<t.length&&t[n]===e;)n++;return t.slice(n)}function Jf(t,e){if(e.length!==1)throw new TypeError("Invalid character string");let n=t.length;for(;n>0&&t[n-1]===e;)n--;return t.slice(0,n)}function Xf(t,...e){let n=Jf(t,"/");for(const r of e)n=Jf(n,"/")+"/"+E2(r,"/");return n}function dn(t,e){const n=new TextEncoder().encode(e.toString()),r=new Request(t,{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 nr(t,e){const n=new TextEncoder().encode(`${t}:${e}`);return v2(n)}async function Xr(t){let e;try{e=await fetch(t)}catch(n){throw new qu(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Fr(e.status)}if(typeof n!="object"||n===null)throw new Nn(e.status,n);let r;try{r=Mu(n)}catch{throw new Nn(e.status,n)}throw r}if(e.status===200){let n;try{n=await e.json()}catch{throw new Fr(e.status)}if(typeof n!="object"||n===null)throw new Nn(e.status,n);return new k_(n)}throw e.body!==null&&await e.body.cancel(),new Fr(e.status)}async function C2(t){let e;try{e=await fetch(t)}catch(n){throw new qu(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Nn(e.status,null)}if(typeof n!="object"||n===null)throw new Nn(e.status,n);let r;try{r=Mu(n)}catch{throw new Nn(e.status,n)}throw r}if(e.status===200){e.body!==null&&await e.body.cancel();return}throw e.body!==null&&await e.body.cancel(),new Fr(e.status)}function Mu(t){let e;if("error"in t&&typeof t.error=="string")e=t.error;else throw new Error("Invalid error response");let n=null,r=null,i=null;if("error_description"in t){if(typeof t.error_description!="string")throw new Error("Invalid data");n=t.error_description}if("error_uri"in t){if(typeof t.error_uri!="string")throw new Error("Invalid data");r=t.error_uri}if("state"in t){if(typeof t.state!="string")throw new Error("Invalid data");i=t.state}return new N2(e,n,r,i)}class qu extends Error{constructor(e){super("Failed to send request",{cause:e})}}class N2 extends Error{code;description;uri;state;constructor(e,n,r,i){super(`OAuth request error: ${e}`),this.code=e,this.description=n,this.uri=r,this.state=i}}class Fr extends Error{status;constructor(e){super("Unexpected error response"),this.status=e}}class Nn extends Error{status;data;constructor(e,n){super("Unexpected error response body"),this.status=e,this.data=n}}class kr{clientId;clientPassword;redirectURI;constructor(e,n,r){this.clientId=e,this.clientPassword=n,this.redirectURI=r}createAuthorizationURL(e,n,r){const i=new URL(e);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(e,n,r,i,s){const a=new URL(e);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===ar.S256){const c=x_(i);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",c)}else r===ar.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(e,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=dn(e,i);if(this.clientPassword!==null){const c=nr(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Xr(s)}async refreshAccessToken(e,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=dn(e,i);if(this.clientPassword!==null){const c=nr(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Xr(s)}async revokeToken(e,n){const r=new URLSearchParams;r.set("token",n),this.clientPassword===null&&r.set("client_id",this.clientId);const i=dn(e,r);if(this.clientPassword!==null){const s=nr(this.clientId,this.clientPassword);i.headers.set("Authorization",`Basic ${s}`)}await C2(i)}}var ar;(function(t){t[t.S256=0]="S256",t[t.Plain=1]="Plain"})(ar||(ar={}));var Zf;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Zf||(Zf={}));var Yf;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Yf||(Yf={}));function oo(t){return I2(t,j2,oa.None)}function I2(t,e,n){let r="";for(let i=0;i<t.byteLength;i+=3){let s=0,a=0;for(let c=0;c<3&&i+c<t.byteLength;c++)s=s<<8|t[i+c],a+=8;for(let c=0;c<4;c++)a>=6?(r+=e[s>>a-6&63],a-=6):a>0?(r+=e[s<<6-a&63],a=0):n===oa.Include&&(r+="=")}return r}const j2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var oa;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(oa||(oa={}));var Qf;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Qf||(Qf={}));function P2(t,e,n){const r=oo(new TextEncoder().encode(t)),i=oo(new TextEncoder().encode(e)),s=oo(n);return r+"."+i+"."+s}function O2(t,e){const n=oo(new TextEncoder().encode(t)),r=oo(new TextEncoder().encode(e)),i=n+"."+r;return new TextEncoder().encode(i)}const T2="https://appleid.apple.com/auth/authorize",R2="https://appleid.apple.com/auth/token";class z_{clientId;teamId;keyId;pkcs8PrivateKey;redirectURI;constructor(e,n,r,i,s){this.clientId=e,this.teamId=n,this.keyId=r,this.pkcs8PrivateKey=i,this.redirectURI=s}createAuthorizationURL(e,n){const r=new URL(T2);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",e),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(e){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId);const r=await this.createClientSecret();n.set("client_secret",r);const i=dn(R2,n);return await Xr(i)}async createClientSecret(){const e=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"},e,O2(r,i)));return P2(r,i,s)}}const B2="https://www.facebook.com/v16.0/dialog/oauth",L2="https://graph.facebook.com/v16.0/oauth/access_token";class A_{clientId;clientSecret;redirectURI;constructor(e,n,r){this.clientId=e,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(e,n){const r=new URL(B2);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",e),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(e){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId),n.set("client_secret",this.clientSecret);const r=dn(L2,n);return await Xr(r)}}const U2="https://github.com/login/oauth/authorize",eh="https://github.com/login/oauth/access_token";class E_{clientId;clientSecret;redirectURI;constructor(e,n,r){this.clientId=e,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(e,n){const r=new URL(U2);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",e),n.length>0&&r.searchParams.set("scope",n.join(" ")),this.redirectURI!==null&&r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(e){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),this.redirectURI!==null&&n.set("redirect_uri",this.redirectURI);const r=dn(eh,n),i=nr(this.clientId,this.clientSecret);return r.headers.set("Authorization",`Basic ${i}`),await th(r)}async refreshAccessToken(e){const n=new URLSearchParams;n.set("grant_type","refresh_token"),n.set("refresh_token",e);const r=dn(eh,n),i=nr(this.clientId,this.clientSecret);return r.headers.set("Authorization",`Basic ${i}`),await th(r)}}async function th(t){let e;try{e=await fetch(t)}catch(i){throw new qu(i)}if(e.status!==200)throw e.body!==null&&await e.body.cancel(),new Fr(e.status);let n;try{n=await e.json()}catch{throw new Fr(e.status)}if(typeof n!="object"||n===null)throw new Nn(e.status,n);if("error"in n&&typeof n.error=="string"){let i;try{i=Mu(n)}catch{throw new Nn(e.status,n)}throw i}return new k_(n)}const D2="https://accounts.google.com/o/oauth2/v2/auth",nh="https://oauth2.googleapis.com/token",M2="https://oauth2.googleapis.com/revoke";let C_=class{client;constructor(e,n,r){this.client=new kr(e,n,r)}createAuthorizationURL(e,n,r){return this.client.createAuthorizationURLWithPKCE(D2,e,ar.S256,n,r)}async validateAuthorizationCode(e,n){return await this.client.validateAuthorizationCode(nh,e,n)}async refreshAccessToken(e){return await this.client.refreshAccessToken(nh,e,[])}async revokeToken(e){await this.client.revokeToken(M2,e)}};class N_{authorizationEndpoint;tokenEndpoint;clientId;clientSecret;redirectURI;constructor(e,n,r,i){this.authorizationEndpoint=Xf("https://login.microsoftonline.com",e,"/oauth2/v2.0/authorize"),this.tokenEndpoint=Xf("https://login.microsoftonline.com",e,"/oauth2/v2.0/token"),this.clientId=n,this.clientSecret=r,this.redirectURI=i}createAuthorizationURL(e,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",e);const s=x_(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(e,n){const r=new URLSearchParams;r.set("grant_type","authorization_code"),r.set("code",e),r.set("redirect_uri",this.redirectURI),r.set("code_verifier",n),this.clientSecret===null&&r.set("client_id",this.clientId);const i=dn(this.tokenEndpoint,r);if(this.clientSecret!==null){const a=nr(this.clientId,this.clientSecret);i.headers.set("Authorization",`Basic ${a}`)}else i.headers.set("Origin","arctic");return await Xr(i)}async refreshAccessToken(e,n){const r=new URLSearchParams;r.set("grant_type","refresh_token"),r.set("refresh_token",e),this.clientSecret===null&&r.set("client_id",this.clientId),n.length>0&&r.set("scope",n.join(" "));const i=dn(this.tokenEndpoint,r);if(this.clientSecret!==null){const a=nr(this.clientId,this.clientSecret);i.headers.set("Authorization",`Basic ${a}`)}else i.headers.set("Origin","arctic");return await Xr(i)}}const hi=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();hi.omit({iat:!0,auth_time:!0,nonce:!0,acr:!0,amr:!0,azp:!0,at_hash:!0,c_hash:!0});function ic(t){return t.ISSUER}function De(t){return t.UNIVERSAL_LOGIN_URL||`${t.ISSUER}u/`}function me(t){return t.OAUTH_API_URL||t.ISSUER}const q2="Apple",F2=({className:t=""})=>p("svg",{width:"45",height:"45",viewBox:"0 0 45 45",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,children:[p("path",{d:"M45 0H0V45H45V0Z",fill:"white"}),p("path",{d:"M23.5344 10.3846C25.5313 10.3846 28.0344 9.01144 29.525 7.18055C30.875 5.5213 31.8594 3.20407 31.8594 0.886839C31.8594 0.572154 31.8313 0.25747 31.775 0C29.5531 0.0858233 26.8813 1.51621 25.2781 3.43293C24.0125 4.89193 22.8594 7.18055 22.8594 9.52638C22.8594 9.86968 22.9156 10.213 22.9438 10.3274C23.0844 10.356 23.3094 10.3846 23.5344 10.3846ZM16.5031 45C19.2313 45 20.4406 43.1405 23.8438 43.1405C27.3031 43.1405 28.0625 44.9428 31.1 44.9428C34.0813 44.9428 36.0781 42.1392 37.9625 39.3929C40.0719 36.246 40.9438 33.1564 41 33.0134C40.8031 32.9561 35.0938 30.5817 35.0938 23.9161C35.0938 18.1373 39.5938 15.534 39.8469 15.3338C36.8656 10.9854 32.3375 10.8709 31.1 10.8709C27.7531 10.8709 25.025 12.9307 23.3094 12.9307C21.4531 12.9307 19.0063 10.9854 16.1094 10.9854C10.5969 10.9854 5 15.6198 5 24.3738C5 29.8093 7.08125 35.5594 9.64063 39.2784C11.8344 42.4253 13.7469 45 16.5031 45Z",fill:"black"})]});function I_(t){const{options:e}=t;if(!e||!e.client_id||!e.team_id||!e.kid||!e.app_secret)throw new Error("Missing required Apple authentication parameters");const n=Buffer.from(e.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:e,keyArray:i}}async function H2(t,e){const{options:n,keyArray:r}=I_(e),i=`${me(t.env)}callback`,s=new z_(n.client_id,n.team_id,n.kid,r,i),a=pe(),c=await s.createAuthorizationURL(a,n.scope?.split(" ")||["name","email"]);return(n.scope?.split(" ")||["name","email"]).some(d=>["email","name"].includes(d))&&c.searchParams.set("response_mode","form_post"),{redirectUrl:c.href,code:a}}async function V2(t,e,n){const{options:r,keyArray:i}=I_(e),a=await new z_(r.client_id,r.team_id,r.kid,i,`${me(t.env)}callback`).validateAuthorizationCode(n),c=Mo(a.idToken());if(!c)throw new Error("Invalid ID token");const l=hi.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 K2=Object.freeze(Object.defineProperty({__proto__:null,displayName:q2,getRedirect:H2,logo:F2,validateAuthorizationCodeAndGetUser:V2},Symbol.toStringTag,{value:"Module"})),G2="Facebook",W2=({className:t=""})=>p("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:t,children:[p("path",{d:"M45 22.5C45 10.0736 34.9264 0 22.5 0C10.0736 0 0 10.0736 0 22.5C0 33.7031 8.23242 42.9785 19.0039 44.6953V28.9746H13.2861V22.5H19.0039V17.5391C19.0039 11.8945 22.3828 8.75977 27.5391 8.75977C29.9658 8.75977 32.5049 9.19922 32.5049 9.19922V14.7656H29.7012C26.9414 14.7656 26.0156 16.4824 26.0156 18.2432V22.5H32.2412L31.2012 28.9746H26.0156V44.6953C36.7871 42.9785 45 33.7031 45 22.5Z",fill:"#1877F2"}),p("path",{d:"M31.2012 28.9746L32.2412 22.5H26.0156V18.2432C26.0156 16.4824 26.9414 14.7656 29.7012 14.7656H32.5049V9.19922C32.5049 9.19922 29.9658 8.75977 27.5391 8.75977C22.3828 8.75977 19.0039 11.8945 19.0039 17.5391V22.5H13.2861V28.9746H19.0039V44.6953C20.1562 44.8984 21.3203 45 22.5 45C23.6797 45 24.8438 44.8984 26.0156 44.6953V28.9746H31.2012Z",fill:"white"})]});async function J2(t,e){const{options:n}=e;if(!n?.client_id||!n.client_secret)throw new Error("Missing required authentication parameters");const r=`${me(t.env)}callback`,i=new A_(n.client_id,n.client_secret,r),s=pe();return{redirectUrl:i.createAuthorizationURL(s,n.scope?.split(" ")||["email"]).href,code:s}}async function X2(t,e,n){const{options:r}=e;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new A_(r.client_id,r.client_secret,`${me(t.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 t.set("log",`Userinfo: ${JSON.stringify(c)}`),{sub:c.id,email:c.email,name:c.name}}const Z2=Object.freeze(Object.defineProperty({__proto__:null,displayName:G2,getRedirect:J2,logo:W2,validateAuthorizationCodeAndGetUser:X2},Symbol.toStringTag,{value:"Module"})),Y2="Google",Q2=!0,e3=({className:t=""})=>p("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:t,children:[p("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"}),p("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"}),p("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"}),p("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"})]});async function t3(t,e){const{options:n}=e;if(!n?.client_id||!n.client_secret)throw new Error("Missing required Google authentication parameters");const r=`${me(t.env)}callback`,i=new C_(n.client_id,n.client_secret,r),s=pe(),a=rc();return{redirectUrl:i.createAuthorizationURL(s,a,n.scope?.split(" ")??["email","profile"]).href,code:s,codeVerifier:a}}async function n3(t,e,n,r){const{options:i}=e;if(!i?.client_id||!i.client_secret||!r)throw new Error("Missing required authentication parameters");const a=await new C_(i.client_id,i.client_secret,`${me(t.env)}callback`).validateAuthorizationCode(n,r),c=Mo(a.idToken());if(!c)throw new Error("Invalid ID token");const l=hi.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 r3=Object.freeze(Object.defineProperty({__proto__:null,disableEmbeddedBrowsers:Q2,displayName:Y2,getRedirect:t3,logo:e3,validateAuthorizationCodeAndGetUser:n3},Symbol.toStringTag,{value:"Module"})),i3="Vipps",o3=({className:t=""})=>p("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 48 48",width:"45",height:"45",className:t,children:[p("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"}),p("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
65
+ </html>`;return t.html(s,{headers:i})}const Kl=["openid","profile","email","address","phone"];async function Lv(t,e){const{tenantId:n,clientId:r,audience:i,requestedScopes:s}=e,a=s.filter(S=>Kl.includes(S)),l=(await t.env.data.resourceServers.list(n)).resource_servers.filter(S=>S.identifier===i);if(l.length===0)return{scopes:a,permissions:[]};const d=l[0];if(!d)return{scopes:a,permissions:[]};const u=d.options?.enforce_policies===!0,f=d.options?.token_dialect||"access_token",_=(await t.env.data.clientGrants.list(n,{q:`client_id:"${r}"`})).client_grants.find(S=>S.audience===i);if(!_)return{scopes:a,permissions:[]};const w=_.scope||[],k=(d.scopes||[]).map(S=>S.value);if(!u){let S;return s.length===0?S=w.filter(P=>k.includes(P)):S=s.filter(P=>k.includes(P)&&w.includes(P)),{scopes:[...new Set([...a,...S])],permissions:[]}}const z=w.filter(S=>k.includes(S));if(f==="access_token_authz")return{scopes:a,permissions:z};let N;return s.length===0?N=w.filter(S=>k.includes(S)):N=s.filter(S=>k.includes(S)&&w.includes(S)),{scopes:[...new Set([...a,...N])],permissions:z}}async function na(t,e){if(e.grantType===St.ClientCredential)return await Lv(t,{tenantId:e.tenantId,clientId:e.clientId,audience:e.audience,requestedScopes:e.requestedScopes});const{tenantId:n,userId:r,audience:i,requestedScopes:s,organizationId:a}=e;if(a&&!(await t.env.data.userOrganizations.list(n,{q:`user_id:${r}`,per_page:1e3})).userOrganizations.some(le=>le.organization_id===a))throw new B(403,{error:"access_denied",error_description:"User is not a member of the specified organization"});const c=s.filter(M=>Kl.includes(M)),d=(await t.env.data.resourceServers.list(n)).resource_servers.filter(M=>M.identifier===i);if(d.length===0)return{scopes:s,permissions:[]};const u=d[0];if(!u)return{scopes:s,permissions:[]};const f=(u.scopes||[]).map(M=>M.value),g=u.options?.enforce_policies===!0,_=u.options?.token_dialect||"access_token";if(!g)return{scopes:s,permissions:[]};const w=await t.env.data.userPermissions.list(n,r,void 0,a),k=await t.env.data.userRoles.list(n,r,void 0,""),z=a?await t.env.data.userRoles.list(n,r,void 0,a):[],N=[...k,...z],I=[];for(const M of N)(await t.env.data.rolePermissions.list(n,M.id)).forEach(le=>{le.resource_server_identifier===i&&I.push(le.permission_name)});const S=new Set;w.forEach(M=>{M.resource_server_identifier===i&&S.add(M.permission_name)}),I.forEach(M=>{S.add(M)});const E=Array.from(S),P=E.filter(M=>f.includes(M)),G=s.filter(M=>!f.includes(M)&&!Kl.includes(M));if(_==="access_token_authz")return{scopes:[...new Set([...c,...G])],permissions:P};const Z=s.filter(M=>f.includes(M)&&E.includes(M));return{scopes:[...new Set([...c,...Z,...G])],permissions:P}}const Tf=["sub","iss","aud","exp","nbf","iat","jti"];async function Ya(t,e){const{authParams:n,user:r,client:i,session_id:s,organization:a,permissions:c,impersonatingUser:l}=e,{signingKeys:d}=await t.env.data.keys.list({q:"type:jwt_signing"}),u=d.filter(E=>!E.revoked_at||new Date(E.revoked_at)>new Date),f=u[u.length-1];if(!f?.pkcs7)throw new B(500,{message:"No signing key available"});const g=rv(f.pkcs7),_=t.var.custom_domain?`https://${t.var.custom_domain}/`:t.env.ISSUER,w=n.audience||i.tenant.audience;if(!w)throw new B(400,{error:"invalid_request",error_description:"An audience must be specified in the request or configured as the tenant default_audience"});const k={aud:w,scope:n.scope||"",sub:r?.user_id||n.client_id,iss:_,tenant_id:t.var.tenant_id,sid:s,act:l?{sub:l.user_id}:void 0,org_id:a?a.id:void 0,permissions:c},z=r&&n.scope?.split(" ").includes("openid")?{aud:n.client_id,sub:r.user_id,iss:_,sid:s,nonce:n.nonce,given_name:r.given_name,family_name:r.family_name,nickname:r.nickname,picture:r.picture,locale:r.locale,name:r.name,email:r.email,email_verified:r.email_verified,act:l?{sub:l.user_id}:void 0,org_id:a?.id,org_name:a?.name}:void 0;t.env.hooks?.onExecuteCredentialsExchange&&await t.env.hooks.onExecuteCredentialsExchange({ctx:t,client:i,user:r,request:{ip:t.var.ip||"",user_agent:t.var.useragent||"",method:t.req.method,url:t.req.url},scope:n.scope||"",grant_type:""},{accessToken:{setCustomClaim:(E,P)=>{if(Tf.includes(E))throw new Error(`Cannot overwrite reserved claim '${E}'`);k[E]=P}},idToken:{setCustomClaim:(E,P)=>{if(Tf.includes(E))throw new Error(`Cannot overwrite reserved claim '${E}'`);z&&(z[E]=P)}},access:{deny:E=>{throw new B(400,{message:`Access denied: ${E}`})}},token:{createServiceToken:async E=>{const{createServiceToken:P}=await Promise.resolve().then(()=>Dv);return(await P(t,t.var.tenant_id,E.scope,E.expiresInSeconds)).access_token}}});const N={expiresIn:l?new ea(1,"h"):new ea(1,"d"),headers:{kid:f.kid}},I=await If("RS256",g,k,N),S=z?await If("RS256",g,z,N):void 0;return{access_token:I,refresh_token:e.refresh_token,id_token:S,token_type:"Bearer",expires_in:l?3600:86400}}async function l_(t,e){return{code:(await t.env.data.codes.create(e.client.tenant.id,{code_id:pe(),user_id:e.user.user_id,code_type:"authorization_code",login_id:e.login_id,expires_at:new Date(Date.now()+sv*1e3).toISOString(),code_challenge:e.authParams.code_challenge,code_challenge_method:e.authParams.code_challenge_method,redirect_uri:e.authParams.redirect_uri,state:e.authParams.state,nonce:e.authParams.nonce})).code_id,state:e.authParams.state}}async function d_(t,e){const{client:n,scope:r,audience:i=n.tenant.audience,session_id:s}=e;return await t.env.data.refreshTokens.create(n.tenant.id,{id:pe(),session_id:s,client_id:n.client_id,idle_expires_at:new Date(Date.now()+Za*1e3).toISOString(),user_id:e.user.user_id,device:{last_ip:t.var.ip,initial_ip:t.var.ip,last_user_agent:t.var.useragent||"",initial_user_agent:t.var.useragent||"",initial_asn:"",last_asn:""},resource_servers:[{audience:i,scopes:r}],rotating:!1})}async function u_(t,{user:e,client:n,loginSession:r}){const i=await t.env.data.sessions.create(n.tenant.id,{id:pe(),user_id:e.user_id,login_session_id:r.id,idle_expires_at:new Date(Date.now()+Za*1e3).toISOString(),device:{last_ip:t.var.ip||"",initial_ip:t.var.ip||"",last_user_agent:t.var.useragent||"",initial_user_agent:t.var.useragent||"",initial_asn:"",last_asn:""},clients:[n.client_id]});return await t.env.data.loginSessions.update(n.tenant.id,r.id,{session_id:i.id}),i}async function Gt(t,e){const{authParams:n,client:r,ticketAuth:i}=e;let{user:s}=e;const a=n.response_type||mt.CODE,c=n.response_mode||Ct.QUERY;if(i){if(!e.loginSession)throw new B(500,{message:"Login session not found for ticket auth."});s&&!e.skipHooks&&(e.authStrategy&&s.app_metadata?.strategy!==e.authStrategy.strategy&&(s.app_metadata={...s.app_metadata,strategy:e.authStrategy.strategy},await t.env.data.users.update(r.tenant.id,s.user_id,{app_metadata:{...s.app_metadata||{},strategy:e.authStrategy.strategy}})),await f_(t,t.env.data,r.tenant.id,s,e.loginSession,{client:r,authParams:n,authStrategy:e.authStrategy}));const _=nv(),w=pe(12),k=await t.env.data.codes.create(r.tenant.id,{code_id:pe(),code_type:"ticket",login_id:e.loginSession.id,expires_at:new Date(Date.now()+cv).toISOString(),code_verifier:[w,_].join("|"),redirect_uri:n.redirect_uri,state:n.state,nonce:n.nonce});return t.json({login_ticket:k.code_id,co_verifier:_,co_id:w})}let l=e.refreshToken,d=e.sessionId;if(!d&&e.loginSession?.session_id){d=e.loginSession.session_id;const _=await t.env.data.sessions.get(r.tenant.id,d);_&&!_.clients.includes(r.client_id)&&await t.env.data.sessions.update(r.tenant.id,d,{clients:[..._.clients,r.client_id]})}else if(!d){if(!e.loginSession)throw new B(500,{message:"Login session not found for creating a new session."});d=(await u_(t,{user:s,client:r,loginSession:e.loginSession})).id}if(!l&&n.scope?.split(" ").includes("offline_access")&&![mt.TOKEN,mt.CODE].includes(a)&&!e.impersonatingUser&&(l=(await d_(t,{user:s,client:r,session_id:d,scope:n.scope,audience:n.audience})).id),c===Ct.SAML_POST){if(!d)throw new v(500,{message:"Session ID not available for SAML response"});return Bv(t,e.client,e.authParams,s,d)}const u=await Uv(t,{authParams:n,user:s,client:r,session_id:d,refresh_token:l,authStrategy:e.authStrategy,loginSession:e.loginSession,responseType:a,skipHooks:e.skipHooks,organization:e.organization,impersonatingUser:e.impersonatingUser});if(u instanceof Response)return u;if(c===Ct.WEB_MESSAGE){if(!n.redirect_uri)throw new B(400,{message:"Redirect URI not allowed for WEB_MESSAGE response mode."});const _=new Headers;if(d){const z=ta(r.tenant.id,d,t.var.host||"");z&&_.set("set-cookie",z)}else console.warn("Session ID not available for WEB_MESSAGE, cookie will not be set.");const w=new URL(n.redirect_uri),k=`${w.protocol}//${w.host}`;return Vl(t,k,JSON.stringify({...u,state:n.state}),_)}if(!n.redirect_uri)throw new B(400,{message:"Redirect uri not found for this response mode."});const f=new Headers;if(d){const _=ta(r.tenant.id,d,t.var.custom_domain||t.req.header("host")||"");_&&f.set("set-cookie",_)}const g=new URL(n.redirect_uri);if("code"in u)g.searchParams.set("code",u.code),u.state&&g.searchParams.set("state",u.state);else if("access_token"in u)g.hash=new URLSearchParams({access_token:u.access_token,...u.id_token&&{id_token:u.id_token},token_type:u.token_type,expires_in:u.expires_in.toString(),...n.state&&{state:n.state},...n.scope&&{scope:n.scope}}).toString();else throw new B(500,{message:"Invalid token response for implicit flow."});return f.set("location",g.toString()),new Response("Redirecting",{status:302,headers:f})}async function Uv(t,e){let{user:n}=e;const r=e.responseType||mt.TOKEN;if(n&&e.organization&&!(await t.env.data.userOrganizations.list(e.client.tenant.id,{q:`user_id:${n.user_id}`,per_page:1e3})).userOrganizations.some(d=>d.organization_id===e.organization.id))throw new B(403,{error:"access_denied",error_description:"User is not a member of the specified organization"});let i=e.authParams.scope||"",s=[];if(e.authParams.audience)try{let c;if(e.grantType===St.ClientCredential||!n&&!e.user)c=await na(t,{grantType:St.ClientCredential,tenantId:e.client.tenant.id,clientId:e.client.client_id,audience:e.authParams.audience,requestedScopes:e.authParams.scope?.split(" ")||[],organizationId:e.organization?.id});else{const l=n?.user_id||e.user?.user_id;if(!l)throw new B(400,{error:"invalid_request",error_description:"User ID is required for user-based grants"});c=await na(t,{grantType:e.grantType,tenantId:e.client.tenant.id,userId:l,clientId:e.client.client_id,audience:e.authParams.audience,requestedScopes:e.authParams.scope?.split(" ")||[],organizationId:e.organization?.id})}i=c.scopes.join(" "),s=c.permissions}catch(c){if(c instanceof v)throw c}const a={...e.authParams,scope:i};if(e.loginSession&&n&&!e.skipHooks){e.authStrategy&&n.app_metadata?.strategy!==e.authStrategy.strategy&&(n.app_metadata={...n.app_metadata,strategy:e.authStrategy.strategy},await t.env.data.users.update(e.client.tenant.id,n.user_id,{app_metadata:{...n.app_metadata||{},strategy:e.authStrategy.strategy}}));const c=await f_(t,t.env.data,e.client.tenant.id,n,e.loginSession,{client:e.client,authParams:a,authStrategy:e.authStrategy});if(c instanceof Response)return c;n=c}if(r===mt.CODE){if(!n||!e.loginSession)throw new B(500,{message:"User and loginSession is required for code flow"});return await l_(t,{user:n,client:e.client,authParams:a,login_id:e.loginSession.id})}else return Ya(t,{...e,user:n,authParams:a,permissions:s})}const Rf="auth-service";async function Qa(t,e,n,r){const i=await t.env.data.tenants.get(e);if(!i)throw new Error(`Tenant not found: ${e}`);const s={client_id:Rf,tenant:i,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),name:"Auth Service",global:!1,is_first_party:!0,oidc_conformant:!1,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 Ya(t,{client:s,authParams:{client_id:Rf,response_type:mt.TOKEN,scope:n}});return{access_token:a.access_token,token_type:a.token_type,expires_in:r||3600}}const Dv=Object.freeze(Object.defineProperty({__proto__:null,createServiceToken:Qa},Symbol.toStringTag,{value:"Module"}));async function ec(t,e,n){const r=await Qa(t,n.tenant_id,"webhook");for await(const i of e.filter(s=>"url"in s))(await fetch(i.url,{method:"POST",headers:{Authorization:`Bearer ${r.access_token}`,"Content-Type":"application/json"},body:JSON.stringify(n)})).ok||ie(t,n.tenant_id,{type:te.FAILED_HOOK,description:`Failed to invoke hook ${i.hook_id}`})}function Mv(t){return async(e,n)=>{const{hooks:r}=await t.env.data.hooks.list(e);return await ec(t,r,{tenant_id:e,user:n,trigger_id:"post-user-registration"}),n}}function qv(t){return async(e,n)=>{const{hooks:r}=await t.env.data.hooks.list(e,{q:"trigger_id:pre-user-registration",page:0,per_page:100,include_totals:!1});await ec(t,r,{tenant_id:e,email:n,trigger_id:"pre-user-registration"})}}async function Fv(t,e){const{hooks:n}=await t.env.data.hooks.list(e,{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 Hv(t){return async(e,n)=>{const{hooks:r}=await t.env.data.hooks.list(e,{q:"trigger_id:pre-user-deletion",page:0,per_page:100,include_totals:!1});return await ec(t,r,{tenant_id:e,user:n,trigger_id:"pre-user-deletion"}),n}}function Vv(t){return async(e,n)=>{const{hooks:r}=await t.env.data.hooks.list(e,{q:"trigger_id:post-user-deletion",page:0,per_page:100,include_totals:!1});return await ec(t,r,{tenant_id:e,user:n,trigger_id:"post-user-deletion"}),n}}function Bf(t){return typeof t.form_id=="string"}function Lf(t,e){const n=t.match(/^\{\{context\.user\.(\w+)\}\}$/);if(n){const r=n[1],i=e.user[r];return typeof i=="string"?i:""}return t}function Kv(t,e){const n=t.operator?.toLowerCase(),r=t.field?Lf(t.field,e):"",i=t.value||"";switch(n){case"ends_with":return r.endsWith(i);case"starts_with":return r.startsWith(i);case"contains":return r.includes(i);case"equals":case"eq":return r===i;case"not_equals":case"neq":return r!==i;default:if(t.operands&&Array.isArray(t.operands)){for(const s of t.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&&Lf(`{{context.user.${a}}}`,e).endsWith(c))return!0}}return!1}}function Gv(t,e,n,r=10){let i=e,s=0;for(;s<r;){if(i==="$ending")return null;const a=t.find(c=>c.id===i);if(!a)return null;if(a.type==="STEP")return a.id;if(a.type==="ROUTER"){const c=a;let l=null;for(const d of c.config.rules)if(Kv(d.condition,n)){l=d.next_node;break}if(l||(l=c.config.fallback),!l)return null;i=l,s++;continue}return null}return null}async function Wv(t,e,n,r){const i=t.env.data,s=t.var.tenant_id||t.req.header("tenant-id");if(!s)throw new v(400,{message:"Missing tenant_id in context"});const a=await i.forms.get(s,e);if(!a)throw new v(404,{message:"Form not found for post-user-login hook"});let c=a.start?.next_node;if(!c&&a.nodes&&a.nodes.length>0&&(c=a.nodes.find(u=>u.type==="STEP")?.id),!c)throw new v(400,{message:"No start node found in form"});if(r&&a.nodes){const d=Gv(a.nodes,c,{user:r});if(!d)return new Response(null,{status:302,headers:{location:`/u/login/identifier?state=${encodeURIComponent(n.id)}`}});c=d}let l=`/u/forms/${a.id}/nodes/${c}?state=${encodeURIComponent(n.id)}`;return new Response(null,{status:302,headers:{location:l}})}function Uf(t){return typeof t.page_id=="string"&&typeof t.enabled=="boolean"}async function Jv(t,e,n,r,i){const s=t.env.data,a=t.var.tenant_id||t.req.header("tenant-id");if(!a)throw new v(400,{message:"Missing tenant_id in context"});if(i&&!(await s.userPermissions.list(a,r.user_id)).some(u=>u.permission_name===i))return r;let c=`/u/${e}?state=${encodeURIComponent(n.id)}`;return new Response(null,{status:302,headers:{location:c}})}function sr(t,e){return{createServiceToken:async n=>(await Qa(t,e,n.scope,n.expiresInSeconds)).access_token}}function Df(t){return typeof t.url=="string"}function Xv(t,e){return async(n,r)=>{if(t.var.client_id){const a=await e.legacyClients.get(t.var.client_id);if(!a)throw new B(400,{message:"Client not found"});r.email&&await Yv(t,a,e,r.email)}const i={method:t.req.method,ip:t.req.query("x-real-ip")||"",user_agent:t.req.query("user-agent"),url:t.var.loginSession?.authorization_url||t.req.url};if(t.env.hooks?.onExecutePreUserRegistration)try{await t.env.hooks.onExecutePreUserRegistration({ctx:t,user:r,request:i},{user:{setUserMetadata:async(a,c)=>{r[a]=c}},token:sr(t,n)})}catch{ie(t,n,{type:te.FAILED_SIGNUP,description:"Pre user registration hook failed"})}let s=await Kb(e)(n,r);if(t.env.hooks?.onExecutePostUserRegistration)try{await t.env.hooks.onExecutePostUserRegistration({ctx:t,user:r,request:i},{user:{},token:sr(t,n)})}catch{ie(t,n,{type:te.FAILED_SIGNUP,description:"Post user registration hook failed"})}return await Mv(t)(n,s),s}}function Zv(t,e){return async(n,r,i)=>{if(Object.keys(i).length===1&&"linked_to"in i)return e.users.update(n,r,i);const s=await e.users.get(n,r);if(!s)throw new B(404,{message:"User not found"});const a={method:t.req.method,ip:t.var.ip||t.get("ip")||"",user_agent:t.var.useragent||t.get("useragent")||"",url:t.req.url};if(t.env.hooks?.onExecutePreUserUpdate)try{await t.env.hooks.onExecutePreUserUpdate({ctx:t,tenant:{id:n},user_id:r,user:s,updates:i,request:a},{user:{setUserMetadata:async(c,l)=>{i[c]=l}},cancel:()=>{throw new B(400,{message:"User update cancelled by pre-update hook"})},token:sr(t,n)})}catch{throw new B(400,{message:"Pre user update hook failed"})}if(await e.users.update(n,r,i),i.email||i.email_verified){const c=await e.users.get(n,r);if(c&&c.email&&c.email_verified){const{users:l}=await e.users.list(n,{page:0,per_page:10,include_totals:!1,q:`email:${c.email}`}),d=l.filter(u=>u.email_verified&&u.user_id!==r&&!u.linked_to);d.length>0&&await e.users.update(n,r,{linked_to:d[0].user_id})}}return i.email&&ie(t,n,{type:te.SUCCESS_CHANGE_EMAIL,description:`Email updated to ${i.email}`,userId:r}),!0}}async function p_(t,e,n,r,i="email"){if(e.client_metadata?.disable_sign_ups==="true"){const a=t.var.loginSession?.authorization_url;if(a&&new URL(a).searchParams.get("screen_hint")==="signup")return{allowed:!0};if(!await tc({userAdapter:n.users,tenant_id:e.tenant.id,email:r}))return{allowed:!1,reason:"Public signup is disabled for this client"}}if(t.env.hooks?.onExecuteValidateSignupEmail){const a={method:t.req.method,ip:t.var.ip||t.get("ip")||"",user_agent:t.var.useragent||t.get("useragent")||"",url:t.req.url};let c=!1,l;try{if(await t.env.hooks.onExecuteValidateSignupEmail({ctx:t,client:e,request:a,tenant:{id:e.tenant.id},user:{email:r,connection:i}},{deny:d=>{c=!0,l=d},token:sr(t,e.tenant.id)}),c)return{allowed:!1,reason:l}}catch{return{allowed:!1,reason:"Signup validation hook failed"}}}const s=await Fv(t,e.tenant.id);if(s&&"url"in s)try{const a=await Qa(t,e.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:e.tenant.id,email:r,connection:i,client_id:e.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{ie(t,e.tenant.id,{type:te.FAILED_HOOK,description:"Validate signup email webhook failed"})}return{allowed:!0}}async function Yv(t,e,n,r){const i=await p_(t,e,n,r);if(!i.allowed)throw ie(t,e.tenant.id,{type:te.FAILED_SIGNUP,description:i.reason||"Signup not allowed"}),new B(400,{message:i.reason||"Signups are disabled for this client"});await qv(t)(e.tenant.id,r)}function Qv(t,e){return async(n,r)=>{const i=await e.users.get(n,r);if(!i)return!1;const s={method:t.req.method,ip:t.var.ip||t.get("ip")||"",user_agent:t.var.useragent||t.get("useragent")||"",url:t.req.url};if(t.env.hooks?.onExecutePreUserDeletion)try{await t.env.hooks.onExecutePreUserDeletion({ctx:t,user:i,user_id:r,request:s,tenant:{id:n}},{cancel:()=>{throw new B(400,{message:"User deletion cancelled by pre-deletion hook"})},token:sr(t,n)})}catch(c){throw c instanceof v?c:(ie(t,n,{type:te.FAILED_HOOK,description:`Pre user deletion hook failed: ${c instanceof Error?c.message:String(c)}`}),new B(400,{message:"Pre user deletion hook failed"}))}try{await Hv(t)(n,i)}catch(c){throw ie(t,n,{type:te.FAILED_HOOK,description:`Pre user deletion webhook failed: ${c instanceof Error?c.message:String(c)}`}),new B(400,{message:"Pre user deletion webhook failed"})}const a=await e.users.remove(n,r);if(a){ie(t,n,{type:te.SUCCESS_USER_DELETION,description:`user_id: ${r}`,strategy:i.provider||"auth0",strategy_type:i.is_social?"social":"database",connection:i.connection||"",body:{tenant:n,connection:i.connection||""}});try{await Vv(t)(n,i)}catch(c){ie(t,n,{type:te.FAILED_HOOK,description:`Post user deletion webhook failed: ${c instanceof Error?c.message:String(c)}`})}}if(a&&t.env.hooks?.onExecutePostUserDeletion)try{await t.env.hooks.onExecutePostUserDeletion({ctx:t,user:i,user_id:r,request:s,tenant:{id:n}},{token:sr(t,n)})}catch(c){ie(t,n,{type:te.FAILED_HOOK,description:`Post user deletion hook failed: ${c instanceof Error?c.message:String(c)}`})}return a}}function qo(t,e){const n=e;return{...e,users:{...e.users,create:Xv(t,n),update:Zv(t,n),remove:Qv(t,n)}}}async function e2(t,e,n,r,i,s){let a=[];try{a=(await e.userRoles.list(n,r.user_id,void 0,"")).map(g=>g.name||g.id)}catch(u){console.error("Error fetching user roles:",u)}let c={};if(r.connection)try{const f=(await e.connections.list(n,{page:0,per_page:100,include_totals:!1})).connections.find(g=>g.name===r.connection);f&&(c={id:f.id,name:f.name,strategy:f.strategy||r.provider,metadata:f.options||{}})}catch(u){console.error("Error fetching connection info:",u)}let l;try{if(i.authParams?.organization){const u=await e.organizations.get(n,i.authParams.organization);u&&(l={id:u.id,name:u.name,display_name:u.display_name||u.name,metadata:u.metadata||{}})}}catch(u){console.error("Error fetching organization info:",u)}const d=t.get("countryCode");return{ctx:t,client:s.client,user:r,request:{asn:void 0,ip:t.get("ip")||"",user_agent:t.get("useragent"),method:t.req.method,url:t.req.url,geoip:{cityName:void 0,continentCode:void 0,countryCode:d||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:t.get("ip"),initial_user_agent:t.get("useragent"),last_ip:r.last_ip||t.get("ip"),last_user_agent:t.get("useragent")}}}}async function f_(t,e,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(ie(t,n,{type:te.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 e.users.update(n,r.user_id,{last_login:new Date().toISOString(),last_ip:t.var.ip||"",login_count:r.login_count+1}),t.env.hooks?.onExecutePostLogin&&s?.client&&s?.authParams&&i){let u=null;const f=await e2(t,e,n,r,i,{client:s.client,authParams:s.authParams});if(await t.env.hooks.onExecutePostLogin(f,{prompt:{render:g=>{}},redirect:{sendUserTo:(g,_)=>{const w=new URL(g,t.req.url);w.searchParams.set("state",i.id),_?.query&&Object.entries(_.query).forEach(([k,z])=>{w.searchParams.set(k,z)}),u=w.toString()},encodeToken:g=>JSON.stringify({payload:g.payload,exp:Date.now()+(g.expiresInSeconds||900)*1e3}),validateToken:g=>null},token:sr(t,n)}),u)return new Response(null,{status:302,headers:{location:u}})}const{hooks:l}=await e.hooks.list(n,{q:"trigger_id:post-user-login",page:0,per_page:100,include_totals:!1});if(i){const u=l.find(g=>g.enabled&&Bf(g));if(u&&Bf(u))return Wv(t,u.form_id,i,r);const f=l.find(g=>g.enabled&&Uf(g));if(f&&Uf(f))return Jv(t,f.page_id,i,r,f.permission_required)}const d=l.filter(u=>u.enabled&&Df(u));for(const u of d)if(Df(u))try{await fetch(u.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tenant_id:n,user:r,trigger_id:"post-user-login"})})}catch{ie(t,n,{type:te.FAILED_HOOK,description:`Failed to invoke post-user-login webhook: ${u.url}`})}return r}function t2(t){return qo(t,t.env.data)}async function Ru(t,e,n){return(await t.list(e,{page:0,per_page:10,include_totals:!1,q:`email:${n}`})).users}async function fi({userAdapter:t,tenant_id:e,username:n,provider:r}){const i=r==="sms"?`phone_number:${n}`:`email:${n}`,{users:s}=await t.list(e,{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 email and provider"),s[0]||null}async function tc({userAdapter:t,tenant_id:e,email:n}){const{users:r}=await t.list(e,{page:0,per_page:10,include_totals:!1,q:`email:${n}`}),i=r.filter(c=>!(c.provider==="auth2"&&!c.email_verified));if(i.length===0)return;const s=i.filter(c=>!c.linked_to);if(s.length>0)return s.length>1&&console.error("More than one primary user found for same email"),s[0];const a=await t.get(e,i[0]?.linked_to);if(!a)throw new Error("Primary account not found");return a}async function Jr({userAdapter:t,tenant_id:e,username:n,provider:r}){const i=await fi({userAdapter:t,tenant_id:e,username:n,provider:r});return i?i.linked_to?t.get(e,i.linked_to):i:null}async function nc(t,e){const{username:n,provider:r,connection:i,client:s,userId:a,isSocial:c,profileData:l={},ip:d=""}=e;let u=await Jr({userAdapter:t.env.data.users,tenant_id:e.client.tenant.id,username:n,provider:r});if(!u){const f={user_id:`${r}|${a||Xa()}`,email:i!=="sms"?n:void 0,phone_number:i==="sms"?n:void 0,name:n,provider:r,connection:i,email_verified:!0,last_ip:d,is_social:c,last_login:new Date().toISOString(),profileData:JSON.stringify(l)};u=await t2(t).users.create(s.tenant.id,f),t.set("user_id",u.user_id)}return u}const Te=o.z.object({page:o.z.string().min(0).optional().default("0").transform(t=>parseInt(t,10)).openapi({description:"The page number where 0 is the first page"}),per_page:o.z.string().min(1).optional().default("10").transform(t=>parseInt(t,10)).openapi({description:"The number of items per page"}),include_totals:o.z.string().optional().default("false").transform(t=>t==="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"})});function Ke(t){if(!t)return;const[e,n]=t.split(":"),r=n==="1"?"asc":"desc";if(!(!e||!r))return{sort_by:e,sort_order:r}}var n2={Stringify:1},On=(t,e)=>{const n=new String(t);return n.isEscaped=!0,n.callbacks=e,n},r2=/[&<>'"]/,i2=async(t,e)=>{let n="";e||=[];const r=await Promise.all(t);for(let i=r.length-1;n+=r[i],i--,!(i<0);i--){let s=r[i];typeof s=="object"&&e.push(...s.callbacks||[]);const a=s.isEscaped;if(s=await(typeof s=="object"?s.toString():s),typeof s=="object"&&e.push(...s.callbacks||[]),s.isEscaped??a)n+=s;else{const c=[n];qr(s,c),n=c[0]}}return On(n,e)},qr=(t,e)=>{const n=t.search(r2);if(n===-1){e[0]+=t;return}let r,i,s=0;for(i=n;i<t.length;i++){switch(t.charCodeAt(i)){case 34:r="&quot;";break;case 39:r="&#39;";break;case 38:r="&amp;";break;case 60:r="&lt;";break;case 62:r="&gt;";break;default:continue}e[0]+=t.substring(s,i)+r,s=i+1}e[0]+=t.substring(s,i)},o2=t=>{const e=t.callbacks;if(!e?.length)return t;const n=[t],r={};return e.forEach(i=>i({phase:n2.Stringify,buffer:n,context:r})),n[0]},Bu=Symbol("RENDERER"),Gl=Symbol("ERROR_HANDLER"),ke=Symbol("STASH"),h_=Symbol("INTERNAL"),s2=Symbol("MEMO"),ra=Symbol("PERMALINK"),Mf=t=>(t[h_]=!0,t),g_=t=>({value:e,children:n})=>{if(!n)return;const r={children:[{tag:Mf(()=>{t.push(e)}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:Mf(()=>{t.pop()}),props:{}});const i={tag:"",props:r,type:""};return i[Gl]=s=>{throw t.pop(),s},i},m_=t=>{const e=[t],n=g_(e);return n.values=e,n.Provider=n,Xr.push(n),n},Xr=[],__=t=>{const e=[t],n=(r=>{e.push(r.value);let i;try{i=r.children?(Array.isArray(r.children)?new v_("",{},r.children):r.children).toString():""}finally{e.pop()}return i instanceof Promise?i.then(s=>On(s,s.callbacks)):On(i)});return n.values=e,n.Provider=n,n[Bu]=g_(e),Xr.push(n),n},hi=t=>t.values.at(-1),Es={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},Wl={},Cs="data-precedence",Fo=t=>Array.isArray(t)?t:[t],qf=new WeakMap,Ff=(t,e,n,r)=>({buffer:i,context:s})=>{if(!i)return;const a=qf.get(s)||{};qf.set(s,a);const c=a[t]||=[];let l=!1;const d=Es[t];if(d.length>0){e:for(const[,u]of c)for(const f of d)if((u?.[f]??null)===n?.[f]){l=!0;break e}}if(l?i[0]=i[0].replaceAll(e,""):d.length>0?c.push([e,n,r]):c.unshift([e,n,r]),i[0].indexOf("</head>")!==-1){let u;if(r===void 0)u=c.map(([f])=>f);else{const f=[];u=c.map(([g,,_])=>{let w=f.indexOf(_);return w===-1&&(f.push(_),w=f.length-1),[g,w]}).sort((g,_)=>g[1]-_[1]).map(([g])=>g)}u.forEach(f=>{i[0]=i[0].replaceAll(f,"")}),i[0]=i[0].replace(/(?=<\/head>)/,u.join(""))}},Ho=(t,e,n)=>On(new Nt(t,n,Fo(e??[])).toString()),Vo=(t,e,n,r)=>{if("itemProp"in n)return Ho(t,e,n);let{precedence:i,blocking:s,...a}=n;i=r?i??"":void 0,r&&(a[Cs]=i);const c=new Nt(t,a,Fo(e||[])).toString();return c instanceof Promise?c.then(l=>On(c,[...l.callbacks||[],Ff(t,l,a,i)])):On(c,[Ff(t,c,a,i)])},a2=({children:t,...e})=>{const n=Lu();if(n){const r=hi(n);if(r==="svg"||r==="head")return new Nt("title",e,Fo(t??[]))}return Vo("title",t,e,!1)},c2=({children:t,...e})=>{const n=Lu();return["src","async"].some(r=>!e[r])||n&&hi(n)==="head"?Ho("script",t,e):Vo("script",t,e,!1)},l2=({children:t,...e})=>["href","precedence"].every(n=>n in e)?(e["data-href"]=e.href,delete e.href,Vo("style",t,e,!0)):Ho("style",t,e),d2=({children:t,...e})=>["onLoad","onError"].some(n=>n in e)||e.rel==="stylesheet"&&(!("precedence"in e)||"disabled"in e)?Ho("link",t,e):Vo("link",t,e,"precedence"in e),u2=({children:t,...e})=>{const n=Lu();return n&&hi(n)==="head"?Ho("meta",t,e):Vo("meta",t,e,!1)},y_=(t,{children:e,...n})=>new Nt(t,n,Fo(e??[])),p2=t=>(typeof t.action=="function"&&(t.action=ra in t.action?t.action[ra]:void 0),y_("form",t)),w_=(t,e)=>(typeof e.formAction=="function"&&(e.formAction=ra in e.formAction?e.formAction[ra]:void 0),y_(t,e)),f2=t=>w_("input",t),h2=t=>w_("button",t);const dl=Object.freeze(Object.defineProperty({__proto__:null,button:h2,form:p2,input:f2,link:d2,meta:u2,script:c2,style:l2,title:a2},Symbol.toStringTag,{value:"Module"}));var g2=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),ia=t=>g2.get(t)||t,b_=(t,e)=>{for(const[n,r]of Object.entries(t)){const i=n[0]==="-"||!/[A-Z]/.test(n)?n:n.replace(/[A-Z]/g,s=>`-${s.toLowerCase()}`);e(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)}},wo=void 0,Lu=()=>wo,m2=t=>/[A-Z]/.test(t)&&t.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)/)?t.replace(/([A-Z])/g,"-$1").toLowerCase():t,_2=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],y2=["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"],Uu=(t,e)=>{for(let n=0,r=t.length;n<r;n++){const i=t[n];if(typeof i=="string")qr(i,e);else{if(typeof i=="boolean"||i===null||i===void 0)continue;i instanceof Nt?i.toStringToBuffer(e):typeof i=="number"||i.isEscaped?e[0]+=i:i instanceof Promise?e.unshift("",i):Uu(i,e)}}},Nt=class{tag;props;key;children;isEscaped=!0;localContexts;constructor(t,e,n){this.tag=t,this.props=e,this.children=n}get type(){return this.tag}get ref(){return this.props.ref||null}toString(){const t=[""];this.localContexts?.forEach(([e,n])=>{e.values.push(n)});try{this.toStringToBuffer(t)}finally{this.localContexts?.forEach(([e])=>{e.values.pop()})}return t.length===1?"callbacks"in t?o2(On(t[0],t.callbacks)).toString():t[0]:i2(t,t.callbacks)}toStringToBuffer(t){const e=this.tag,n=this.props;let{children:r}=this;t[0]+=`<${e}`;const i=wo&&hi(wo)==="svg"?s=>m2(ia(s)):s=>ia(s);for(let[s,a]of Object.entries(n))if(s=i(s),s!=="children"){if(s==="style"&&typeof a=="object"){let c="";b_(a,(l,d)=>{d!=null&&(c+=`${c?";":""}${l}:${d}`)}),t[0]+=' style="',qr(c,t),t[0]+='"'}else if(typeof a=="string")t[0]+=` ${s}="`,qr(a,t),t[0]+='"';else if(a!=null)if(typeof a=="number"||a.isEscaped)t[0]+=` ${s}="${a}"`;else if(typeof a=="boolean"&&y2.includes(s))a&&(t[0]+=` ${s}=""`);else if(s==="dangerouslySetInnerHTML"){if(r.length>0)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");r=[On(a.__html)]}else if(a instanceof Promise)t[0]+=` ${s}="`,t.unshift('"',a);else if(typeof a=="function"){if(!s.startsWith("on")&&s!=="ref")throw new Error(`Invalid prop '${s}' of type 'function' supplied to '${e}'.`)}else t[0]+=` ${s}="`,qr(a.toString(),t),t[0]+='"'}if(_2.includes(e)&&r.length===0){t[0]+="/>";return}t[0]+=">",Uu(r,t),t[0]+=`</${e}>`}},ul=class extends Nt{toStringToBuffer(t){const{children:e}=this,n={...this.props};e.length&&(n.children=e.length===1?e[0]:e);const r=this.tag.call(null,n);if(!(typeof r=="boolean"||r==null))if(r instanceof Promise)if(Xr.length===0)t.unshift("",r);else{const i=Xr.map(s=>[s,s.values.at(-1)]);t.unshift("",r.then(s=>(s instanceof Nt&&(s.localContexts=i),s)))}else r instanceof Nt?r.toStringToBuffer(t):typeof r=="number"||r.isEscaped?(t[0]+=r,r.callbacks&&(t.callbacks||=[],t.callbacks.push(...r.callbacks))):qr(r,t)}},v_=class extends Nt{toStringToBuffer(t){Uu(this.children,t)}},w2=(t,e,...n)=>{e??={},n.length&&(e.children=n.length===1?n[0]:n);const r=e.key;delete e.key;const i=Ns(t,e,n);return i.key=r,i},Hf=!1,Ns=(t,e,n)=>{if(!Hf){for(const r in Wl)dl[r][Bu]=Wl[r];Hf=!0}return typeof t=="function"?new ul(t,e,n):dl[t]?new ul(dl[t],e,n):t==="svg"||t==="head"?(wo||=__(""),new Nt(t,e,[new ul(wo,{value:t},n)])):new Nt(t,e,n)},bo=({children:t})=>new v_("",{children:t},Array.isArray(t)?t:t?[t]:[]),b2=(t,e,...n)=>{let r;if(n.length>0)r=n;else{const i=t.props.children;r=Array.isArray(i)?i:[i]}return w2(t.tag,{...t.props,...e},...r)};function p(t,e,n){let r;if(!e||!("children"in e))r=Ns(t,e,[]);else{const i=e.children;r=Array.isArray(i)?Ns(t,e,i):Ns(t,e,[i])}return r.key=n,r}var Vf;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Vf||(Vf={}));var Kf;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Kf||(Kf={}));function v2(t){return $_(t,$2,vo.Include)}function Du(t){return $_(t,k2,vo.None)}function $_(t,e,n){let r="";for(let i=0;i<t.byteLength;i+=3){let s=0,a=0;for(let c=0;c<3&&i+c<t.byteLength;c++)s=s<<8|t[i+c],a+=8;for(let c=0;c<4;c++)a>=6?(r+=e[s>>a-6&63],a-=6):a>0?(r+=e[s<<6-a&63],a=0):n===vo.Include&&(r+="=")}return r}const $2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",k2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var vo;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(vo||(vo={}));var Gf;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Gf||(Gf={}));class x2{uint8(e,n){if(e.byteLength<n+1)throw new TypeError("Insufficient bytes");return e[n]}uint16(e,n){if(e.byteLength<n+2)throw new TypeError("Insufficient bytes");return e[n]<<8|e[n+1]}uint32(e,n){if(e.byteLength<n+4)throw new TypeError("Insufficient bytes");let r=0;for(let i=0;i<4;i++)r|=e[n+i]<<24-i*8;return r}uint64(e,n){if(e.byteLength<n+8)throw new TypeError("Insufficient bytes");let r=0n;for(let i=0;i<8;i++)r|=BigInt(e[n+i])<<BigInt(56-i*8);return r}putUint8(e,n,r){if(e.length<r+1)throw new TypeError("Not enough space");if(n<0||n>255)throw new TypeError("Invalid uint8 value");e[r]=n}putUint16(e,n,r){if(e.length<r+2)throw new TypeError("Not enough space");if(n<0||n>65535)throw new TypeError("Invalid uint16 value");e[r]=n>>8,e[r+1]=n&255}putUint32(e,n,r){if(e.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++)e[r+i]=n>>(3-i)*8&255}putUint64(e,n,r){if(e.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++)e[r+i]=Number(n>>BigInt((7-i)*8)&0xffn)}}const Wf=new x2;function Mt(t,e){return(t<<32-e|t>>>e)>>>0}function S2(t){const e=new z2;return e.update(t),e.digest()}class z2{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(e){if(this.l+=BigInt(e.byteLength)*8n,this.currentBlockSize+e.byteLength<64){this.blocks.set(e,this.currentBlockSize),this.currentBlockSize+=e.byteLength;return}let n=0;if(this.currentBlockSize>0){const r=e.slice(0,64-this.currentBlockSize);this.blocks.set(r,this.currentBlockSize),this.process(),n+=r.byteLength,this.currentBlockSize=0}for(;n+64<=e.byteLength;){const r=e.slice(n,n+64);this.blocks.set(r),this.process(),n+=64}if(e.byteLength-n>0){const r=e.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),Wf.putUint64(this.blocks,this.l,this.blockSize-8),this.process();const e=new Uint8Array(32);for(let n=0;n<8;n++)Wf.putUint32(e,this.H[n],n*4);return e}process(){for(let d=0;d<16;d++)this.w[d]=(this.blocks[d*4]<<24|this.blocks[d*4+1]<<16|this.blocks[d*4+2]<<8|this.blocks[d*4+3])>>>0;for(let d=16;d<64;d++){const u=(Mt(this.w[d-2],17)^Mt(this.w[d-2],19)^this.w[d-2]>>>10)>>>0,f=(Mt(this.w[d-15],7)^Mt(this.w[d-15],18)^this.w[d-15]>>>3)>>>0;this.w[d]=u+this.w[d-7]+f+this.w[d-16]|0}let e=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 d=0;d<64;d++){const u=(Mt(s,6)^Mt(s,11)^Mt(s,25))>>>0,f=(s&a^~s&c)>>>0,g=l+u+f+A2[d]+this.w[d]|0,_=(Mt(e,2)^Mt(e,13)^Mt(e,22))>>>0,w=(e&n^e&r^n&r)>>>0,k=_+w|0;l=c,c=a,a=s,s=i+g|0,i=r,r=n,n=e,e=g+k|0}this.H[0]=e+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 A2=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 k_{data;constructor(e){this.data=e}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 x_(t){const e=S2(new TextEncoder().encode(t));return Du(e)}function rc(){const t=new Uint8Array(32);return crypto.getRandomValues(t),Du(t)}function S_(){const t=new Uint8Array(32);return crypto.getRandomValues(t),Du(t)}function E2(t,e){if(e.length!==1)throw new TypeError("Invalid character string");let n=0;for(;n<t.length&&t[n]===e;)n++;return t.slice(n)}function Jf(t,e){if(e.length!==1)throw new TypeError("Invalid character string");let n=t.length;for(;n>0&&t[n-1]===e;)n--;return t.slice(0,n)}function Xf(t,...e){let n=Jf(t,"/");for(const r of e)n=Jf(n,"/")+"/"+E2(r,"/");return n}function dn(t,e){const n=new TextEncoder().encode(e.toString()),r=new Request(t,{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 nr(t,e){const n=new TextEncoder().encode(`${t}:${e}`);return v2(n)}async function Zr(t){let e;try{e=await fetch(t)}catch(n){throw new qu(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Fr(e.status)}if(typeof n!="object"||n===null)throw new Nn(e.status,n);let r;try{r=Mu(n)}catch{throw new Nn(e.status,n)}throw r}if(e.status===200){let n;try{n=await e.json()}catch{throw new Fr(e.status)}if(typeof n!="object"||n===null)throw new Nn(e.status,n);return new k_(n)}throw e.body!==null&&await e.body.cancel(),new Fr(e.status)}async function C2(t){let e;try{e=await fetch(t)}catch(n){throw new qu(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Nn(e.status,null)}if(typeof n!="object"||n===null)throw new Nn(e.status,n);let r;try{r=Mu(n)}catch{throw new Nn(e.status,n)}throw r}if(e.status===200){e.body!==null&&await e.body.cancel();return}throw e.body!==null&&await e.body.cancel(),new Fr(e.status)}function Mu(t){let e;if("error"in t&&typeof t.error=="string")e=t.error;else throw new Error("Invalid error response");let n=null,r=null,i=null;if("error_description"in t){if(typeof t.error_description!="string")throw new Error("Invalid data");n=t.error_description}if("error_uri"in t){if(typeof t.error_uri!="string")throw new Error("Invalid data");r=t.error_uri}if("state"in t){if(typeof t.state!="string")throw new Error("Invalid data");i=t.state}return new N2(e,n,r,i)}class qu extends Error{constructor(e){super("Failed to send request",{cause:e})}}class N2 extends Error{code;description;uri;state;constructor(e,n,r,i){super(`OAuth request error: ${e}`),this.code=e,this.description=n,this.uri=r,this.state=i}}class Fr extends Error{status;constructor(e){super("Unexpected error response"),this.status=e}}class Nn extends Error{status;data;constructor(e,n){super("Unexpected error response body"),this.status=e,this.data=n}}class kr{clientId;clientPassword;redirectURI;constructor(e,n,r){this.clientId=e,this.clientPassword=n,this.redirectURI=r}createAuthorizationURL(e,n,r){const i=new URL(e);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(e,n,r,i,s){const a=new URL(e);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===ar.S256){const c=x_(i);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",c)}else r===ar.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(e,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=dn(e,i);if(this.clientPassword!==null){const c=nr(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Zr(s)}async refreshAccessToken(e,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=dn(e,i);if(this.clientPassword!==null){const c=nr(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Zr(s)}async revokeToken(e,n){const r=new URLSearchParams;r.set("token",n),this.clientPassword===null&&r.set("client_id",this.clientId);const i=dn(e,r);if(this.clientPassword!==null){const s=nr(this.clientId,this.clientPassword);i.headers.set("Authorization",`Basic ${s}`)}await C2(i)}}var ar;(function(t){t[t.S256=0]="S256",t[t.Plain=1]="Plain"})(ar||(ar={}));var Zf;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Zf||(Zf={}));var Yf;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Yf||(Yf={}));function so(t){return I2(t,j2,oa.None)}function I2(t,e,n){let r="";for(let i=0;i<t.byteLength;i+=3){let s=0,a=0;for(let c=0;c<3&&i+c<t.byteLength;c++)s=s<<8|t[i+c],a+=8;for(let c=0;c<4;c++)a>=6?(r+=e[s>>a-6&63],a-=6):a>0?(r+=e[s<<6-a&63],a=0):n===oa.Include&&(r+="=")}return r}const j2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var oa;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(oa||(oa={}));var Qf;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Qf||(Qf={}));function P2(t,e,n){const r=so(new TextEncoder().encode(t)),i=so(new TextEncoder().encode(e)),s=so(n);return r+"."+i+"."+s}function O2(t,e){const n=so(new TextEncoder().encode(t)),r=so(new TextEncoder().encode(e)),i=n+"."+r;return new TextEncoder().encode(i)}const T2="https://appleid.apple.com/auth/authorize",R2="https://appleid.apple.com/auth/token";class z_{clientId;teamId;keyId;pkcs8PrivateKey;redirectURI;constructor(e,n,r,i,s){this.clientId=e,this.teamId=n,this.keyId=r,this.pkcs8PrivateKey=i,this.redirectURI=s}createAuthorizationURL(e,n){const r=new URL(T2);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",e),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(e){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId);const r=await this.createClientSecret();n.set("client_secret",r);const i=dn(R2,n);return await Zr(i)}async createClientSecret(){const e=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"},e,O2(r,i)));return P2(r,i,s)}}const B2="https://www.facebook.com/v16.0/dialog/oauth",L2="https://graph.facebook.com/v16.0/oauth/access_token";class A_{clientId;clientSecret;redirectURI;constructor(e,n,r){this.clientId=e,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(e,n){const r=new URL(B2);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",e),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(e){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId),n.set("client_secret",this.clientSecret);const r=dn(L2,n);return await Zr(r)}}const U2="https://github.com/login/oauth/authorize",eh="https://github.com/login/oauth/access_token";class E_{clientId;clientSecret;redirectURI;constructor(e,n,r){this.clientId=e,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(e,n){const r=new URL(U2);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",e),n.length>0&&r.searchParams.set("scope",n.join(" ")),this.redirectURI!==null&&r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(e){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),this.redirectURI!==null&&n.set("redirect_uri",this.redirectURI);const r=dn(eh,n),i=nr(this.clientId,this.clientSecret);return r.headers.set("Authorization",`Basic ${i}`),await th(r)}async refreshAccessToken(e){const n=new URLSearchParams;n.set("grant_type","refresh_token"),n.set("refresh_token",e);const r=dn(eh,n),i=nr(this.clientId,this.clientSecret);return r.headers.set("Authorization",`Basic ${i}`),await th(r)}}async function th(t){let e;try{e=await fetch(t)}catch(i){throw new qu(i)}if(e.status!==200)throw e.body!==null&&await e.body.cancel(),new Fr(e.status);let n;try{n=await e.json()}catch{throw new Fr(e.status)}if(typeof n!="object"||n===null)throw new Nn(e.status,n);if("error"in n&&typeof n.error=="string"){let i;try{i=Mu(n)}catch{throw new Nn(e.status,n)}throw i}return new k_(n)}const D2="https://accounts.google.com/o/oauth2/v2/auth",nh="https://oauth2.googleapis.com/token",M2="https://oauth2.googleapis.com/revoke";let C_=class{client;constructor(e,n,r){this.client=new kr(e,n,r)}createAuthorizationURL(e,n,r){return this.client.createAuthorizationURLWithPKCE(D2,e,ar.S256,n,r)}async validateAuthorizationCode(e,n){return await this.client.validateAuthorizationCode(nh,e,n)}async refreshAccessToken(e){return await this.client.refreshAccessToken(nh,e,[])}async revokeToken(e){await this.client.revokeToken(M2,e)}};class N_{authorizationEndpoint;tokenEndpoint;clientId;clientSecret;redirectURI;constructor(e,n,r,i){this.authorizationEndpoint=Xf("https://login.microsoftonline.com",e,"/oauth2/v2.0/authorize"),this.tokenEndpoint=Xf("https://login.microsoftonline.com",e,"/oauth2/v2.0/token"),this.clientId=n,this.clientSecret=r,this.redirectURI=i}createAuthorizationURL(e,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",e);const s=x_(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(e,n){const r=new URLSearchParams;r.set("grant_type","authorization_code"),r.set("code",e),r.set("redirect_uri",this.redirectURI),r.set("code_verifier",n),this.clientSecret===null&&r.set("client_id",this.clientId);const i=dn(this.tokenEndpoint,r);if(this.clientSecret!==null){const a=nr(this.clientId,this.clientSecret);i.headers.set("Authorization",`Basic ${a}`)}else i.headers.set("Origin","arctic");return await Zr(i)}async refreshAccessToken(e,n){const r=new URLSearchParams;r.set("grant_type","refresh_token"),r.set("refresh_token",e),this.clientSecret===null&&r.set("client_id",this.clientId),n.length>0&&r.set("scope",n.join(" "));const i=dn(this.tokenEndpoint,r);if(this.clientSecret!==null){const a=nr(this.clientId,this.clientSecret);i.headers.set("Authorization",`Basic ${a}`)}else i.headers.set("Origin","arctic");return await Zr(i)}}const gi=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();gi.omit({iat:!0,auth_time:!0,nonce:!0,acr:!0,amr:!0,azp:!0,at_hash:!0,c_hash:!0});function ic(t){return t.ISSUER}function De(t){return t.UNIVERSAL_LOGIN_URL||`${t.ISSUER}u/`}function me(t){return t.OAUTH_API_URL||t.ISSUER}const q2="Apple",F2=({className:t=""})=>p("svg",{width:"45",height:"45",viewBox:"0 0 45 45",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,children:[p("path",{d:"M45 0H0V45H45V0Z",fill:"white"}),p("path",{d:"M23.5344 10.3846C25.5313 10.3846 28.0344 9.01144 29.525 7.18055C30.875 5.5213 31.8594 3.20407 31.8594 0.886839C31.8594 0.572154 31.8313 0.25747 31.775 0C29.5531 0.0858233 26.8813 1.51621 25.2781 3.43293C24.0125 4.89193 22.8594 7.18055 22.8594 9.52638C22.8594 9.86968 22.9156 10.213 22.9438 10.3274C23.0844 10.356 23.3094 10.3846 23.5344 10.3846ZM16.5031 45C19.2313 45 20.4406 43.1405 23.8438 43.1405C27.3031 43.1405 28.0625 44.9428 31.1 44.9428C34.0813 44.9428 36.0781 42.1392 37.9625 39.3929C40.0719 36.246 40.9438 33.1564 41 33.0134C40.8031 32.9561 35.0938 30.5817 35.0938 23.9161C35.0938 18.1373 39.5938 15.534 39.8469 15.3338C36.8656 10.9854 32.3375 10.8709 31.1 10.8709C27.7531 10.8709 25.025 12.9307 23.3094 12.9307C21.4531 12.9307 19.0063 10.9854 16.1094 10.9854C10.5969 10.9854 5 15.6198 5 24.3738C5 29.8093 7.08125 35.5594 9.64063 39.2784C11.8344 42.4253 13.7469 45 16.5031 45Z",fill:"black"})]});function I_(t){const{options:e}=t;if(!e||!e.client_id||!e.team_id||!e.kid||!e.app_secret)throw new Error("Missing required Apple authentication parameters");const n=Buffer.from(e.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:e,keyArray:i}}async function H2(t,e){const{options:n,keyArray:r}=I_(e),i=`${me(t.env)}callback`,s=new z_(n.client_id,n.team_id,n.kid,r,i),a=pe(),c=await s.createAuthorizationURL(a,n.scope?.split(" ")||["name","email"]);return(n.scope?.split(" ")||["name","email"]).some(d=>["email","name"].includes(d))&&c.searchParams.set("response_mode","form_post"),{redirectUrl:c.href,code:a}}async function V2(t,e,n){const{options:r,keyArray:i}=I_(e),a=await new z_(r.client_id,r.team_id,r.kid,i,`${me(t.env)}callback`).validateAuthorizationCode(n),c=Mo(a.idToken());if(!c)throw new Error("Invalid ID token");const l=gi.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 K2=Object.freeze(Object.defineProperty({__proto__:null,displayName:q2,getRedirect:H2,logo:F2,validateAuthorizationCodeAndGetUser:V2},Symbol.toStringTag,{value:"Module"})),G2="Facebook",W2=({className:t=""})=>p("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:t,children:[p("path",{d:"M45 22.5C45 10.0736 34.9264 0 22.5 0C10.0736 0 0 10.0736 0 22.5C0 33.7031 8.23242 42.9785 19.0039 44.6953V28.9746H13.2861V22.5H19.0039V17.5391C19.0039 11.8945 22.3828 8.75977 27.5391 8.75977C29.9658 8.75977 32.5049 9.19922 32.5049 9.19922V14.7656H29.7012C26.9414 14.7656 26.0156 16.4824 26.0156 18.2432V22.5H32.2412L31.2012 28.9746H26.0156V44.6953C36.7871 42.9785 45 33.7031 45 22.5Z",fill:"#1877F2"}),p("path",{d:"M31.2012 28.9746L32.2412 22.5H26.0156V18.2432C26.0156 16.4824 26.9414 14.7656 29.7012 14.7656H32.5049V9.19922C32.5049 9.19922 29.9658 8.75977 27.5391 8.75977C22.3828 8.75977 19.0039 11.8945 19.0039 17.5391V22.5H13.2861V28.9746H19.0039V44.6953C20.1562 44.8984 21.3203 45 22.5 45C23.6797 45 24.8438 44.8984 26.0156 44.6953V28.9746H31.2012Z",fill:"white"})]});async function J2(t,e){const{options:n}=e;if(!n?.client_id||!n.client_secret)throw new Error("Missing required authentication parameters");const r=`${me(t.env)}callback`,i=new A_(n.client_id,n.client_secret,r),s=pe();return{redirectUrl:i.createAuthorizationURL(s,n.scope?.split(" ")||["email"]).href,code:s}}async function X2(t,e,n){const{options:r}=e;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new A_(r.client_id,r.client_secret,`${me(t.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 t.set("log",`Userinfo: ${JSON.stringify(c)}`),{sub:c.id,email:c.email,name:c.name}}const Z2=Object.freeze(Object.defineProperty({__proto__:null,displayName:G2,getRedirect:J2,logo:W2,validateAuthorizationCodeAndGetUser:X2},Symbol.toStringTag,{value:"Module"})),Y2="Google",Q2=!0,e3=({className:t=""})=>p("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:t,children:[p("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"}),p("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"}),p("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"}),p("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"})]});async function t3(t,e){const{options:n}=e;if(!n?.client_id||!n.client_secret)throw new Error("Missing required Google authentication parameters");const r=`${me(t.env)}callback`,i=new C_(n.client_id,n.client_secret,r),s=pe(),a=rc();return{redirectUrl:i.createAuthorizationURL(s,a,n.scope?.split(" ")??["email","profile"]).href,code:s,codeVerifier:a}}async function n3(t,e,n,r){const{options:i}=e;if(!i?.client_id||!i.client_secret||!r)throw new Error("Missing required authentication parameters");const a=await new C_(i.client_id,i.client_secret,`${me(t.env)}callback`).validateAuthorizationCode(n,r),c=Mo(a.idToken());if(!c)throw new Error("Invalid ID token");const l=gi.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 r3=Object.freeze(Object.defineProperty({__proto__:null,disableEmbeddedBrowsers:Q2,displayName:Y2,getRedirect:t3,logo:e3,validateAuthorizationCodeAndGetUser:n3},Symbol.toStringTag,{value:"Module"})),i3="Vipps",o3=({className:t=""})=>p("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 48 48",width:"45",height:"45",className:t,children:[p("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"}),p("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
66
66
  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
67
- 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 s3(t,e){const{options:n}=e;if(!n?.client_id||!n.client_secret)throw new Error("Missing required authentication parameters");const r=new kr(n.client_id,n.client_secret,`${me(t.env)}callback`),i=pe(),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 a3(t,e,n){const{options:r}=e;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new kr(r.client_id,r.client_secret,`${me(t.env)}callback`).validateAuthorizationCode("https://api.vipps.no/access-management-1.0/access/oauth2/token",n,null),a=Mo(s.idToken());if(!a)throw new Error("Invalid ID token");const c=hi.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 B(400,{message:"Failed to get user from vipps"});return await l.json()}const c3=Object.freeze(Object.defineProperty({__proto__:null,displayName:i3,getRedirect:s3,logo:o3,validateAuthorizationCodeAndGetUser:a3},Symbol.toStringTag,{value:"Module"})),l3="GitHub",d3=({className:t=""})=>p("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:t,children:p("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M22.5 0C10.074 0 0 10.335 0 23.077C0 33.266 6.444 41.895 15.39 44.955C16.515 45.165 16.935 44.46 16.935 43.857C16.935 43.32 16.92 41.865 16.905 39.99C10.65 41.355 9.33 36.99 9.33 36.99C8.31 34.32 6.825 33.615 6.825 33.615C4.77 32.205 6.975 32.235 6.975 32.235C9.24 32.385 10.425 34.59 10.425 34.59C12.45 38.13 15.75 37.125 17.01 36.555C17.22 35.07 17.82 34.065 18.48 33.51C13.455 32.94 8.19 30.93 8.19 22.035C8.19 19.5 9.075 17.43 10.47 15.81C10.23 15.24 9.435 12.87 10.695 9.66C10.695 9.66 12.585 9.045 16.875 12.06C18.675 11.565 20.595 11.31 22.5 11.31C24.405 11.31 26.325 11.565 28.125 12.06C32.415 9.045 34.305 9.66 34.305 9.66C35.565 12.87 34.77 15.24 34.53 15.81C35.925 17.43 36.81 19.5 36.81 22.035C36.81 30.96 31.53 32.925 26.49 33.48C27.33 34.2 28.095 35.625 28.095 37.815C28.095 40.95 28.065 43.47 28.065 43.857C28.065 44.46 28.485 45.18 29.625 44.955C38.571 41.88 45 33.252 45 23.077C45 10.335 34.926 0 22.5 0Z",fill:"currentColor"})});async function u3(t,e){const{options:n}=e;if(!n?.client_id||!n.client_secret)throw new Error("Missing required GitHub authentication parameters");const r=`${me(t.env)}callback`,i=new E_(n.client_id,n.client_secret,r),s=pe();return{redirectUrl:i.createAuthorizationURL(s,n.scope?.split(" ")||["user:email"]).href,code:s}}async function p3(t,e,n){const{options:r}=e;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new E_(r.client_id,r.client_secret,`${me(t.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 d=c.email;if(l.ok){const u=await l.json(),f=u.find(g=>g.primary&&g.verified)||u.find(g=>g.verified);f&&(d=f.email)}return t.set("log",`GitHub user: ${JSON.stringify(c)}`),{sub:c.id.toString(),email:d,name:c.name,given_name:c.name?.split(" ")[0],family_name:c.name?.split(" ").slice(1).join(" "),picture:c.avatar_url}}const f3=Object.freeze(Object.defineProperty({__proto__:null,displayName:l3,getRedirect:u3,logo:d3,validateAuthorizationCodeAndGetUser:p3},Symbol.toStringTag,{value:"Module"})),h3="Microsoft",g3=({className:t=""})=>p("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:t,children:[p("path",{fill:"#F25022",d:"M0 0H21.43V21.43H0V0Z"}),p("path",{fill:"#7FBA00",d:"M23.57 0H45V21.43H23.57V0Z"}),p("path",{fill:"#00A4EF",d:"M0 23.57H21.43V45H0V23.57Z"}),p("path",{fill:"#FFB900",d:"M23.57 23.57H45V45H23.57V23.57Z"})]});async function m3(t,e){const{options:n}=e;if(!n?.client_id||!n.client_secret)throw new Error("Missing required Microsoft authentication parameters");const r=`${me(t.env)}callback`,i=n.realms||"common",s=new N_(i,n.client_id,n.client_secret,r),a=pe(),c=rc();return{redirectUrl:s.createAuthorizationURL(a,c,n.scope?.split(" ")||["openid","profile","email"]).href,code:a,codeVerifier:c}}async function _3(t,e,n,r){const{options:i}=e;if(!i?.client_id||!i.client_secret||!r)throw new Error("Missing required authentication parameters");const s=i.realms||"common",c=await new N_(s,i.client_id,i.client_secret,`${me(t.env)}callback`).validateAuthorizationCode(n,r),l=Mo(c.idToken());if(!l)throw new Error("Invalid ID token");const d=hi.parse(l.payload);return t.set("log",`Microsoft user: ${JSON.stringify(d)}`),{sub:d.sub,email:d.email,given_name:d.given_name,family_name:d.family_name,name:d.name,picture:d.picture}}const y3=Object.freeze(Object.defineProperty({__proto__:null,displayName:h3,getRedirect:m3,logo:g3,validateAuthorizationCodeAndGetUser:_3},Symbol.toStringTag,{value:"Module"})),w3="OpenID Connect",b3=({className:t="",iconUrl:e})=>e?p("img",{src:e,alt:"OIDC Provider",className:t}):p("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:t,children:[p("path",{d:"M22.5 0C10.074 0 0 10.074 0 22.5S10.074 45 22.5 45 45 34.926 45 22.5 34.926 0 22.5 0zm0 40.5c-9.941 0-18-8.059-18-18s8.059-18 18-18 18 8.059 18 18-8.059 18-18 18z",fill:"currentColor"}),p("path",{d:"M22.5 9c-7.456 0-13.5 6.044-13.5 13.5S15.044 36 22.5 36 36 29.956 36 22.5 29.956 9 22.5 9zm0 22.5c-4.971 0-9-4.029-9-9s4.029-9 9-9 9 4.029 9 9-4.029 9-9 9z",fill:"currentColor"})]});async function v3(t,e){const{options:n}=e;if(!n?.client_id||!n.authorization_endpoint)throw new Error("Missing required OIDC authentication parameters");const r=`${me(t.env)}callback`,i=new kr(n.client_id,n.client_secret||null,r),s=S_(),a=rc(),c=n.scope?.split(" ")??["openid","profile","email"];return{redirectUrl:i.createAuthorizationURLWithPKCE(n.authorization_endpoint,s,ar.S256,a,c).href,code:s,codeVerifier:a}}async function $3(t,e,n,r){const{options:i}=e;if(!i?.client_id||!i.token_endpoint)throw new Error("Missing required authentication parameters");const s=`${me(t.env)}callback`,c=await new kr(i.client_id,i.client_secret||null,s).validateAuthorizationCode(i.token_endpoint,n,r||null);if(c.data.id_token){const d=Mo(c.idToken());if(d?.payload){const u=hi.passthrough().parse(d.payload);return{sub:u.sub,email:u.email,given_name:u.given_name,family_name:u.family_name,name:u.name}}}if(i.userinfo_endpoint){const d=await fetch(i.userinfo_endpoint,{headers:{Authorization:`Bearer ${c.accessToken()}`}});if(!d.ok)throw new Error("Failed to fetch user info");const u=await d.json();if(!u.sub)throw new Error("Unable to get user identifier: userinfo response missing sub");return{sub:u.sub,email:u.email,given_name:u.given_name,family_name:u.family_name,name:u.name}}throw new Error("Unable to get user information: no ID token or userinfo endpoint")}const k3=Object.freeze(Object.defineProperty({__proto__:null,displayName:w3,getRedirect:v3,logo:b3,validateAuthorizationCodeAndGetUser:$3},Symbol.toStringTag,{value:"Module"})),x3="OAuth 2.0",S3=({className:t="",iconUrl:e})=>e?p("img",{src:e,alt:"OAuth Provider",className:t}):p("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:t,children:p("path",{d:"M31.5 18h-1.5v-4.5c0-4.136-3.364-7.5-7.5-7.5s-7.5 3.364-7.5 7.5v4.5h-1.5c-1.657 0-3 1.343-3 3v15c0 1.657 1.343 3 3 3h18c1.657 0 3-1.343 3-3v-15c0-1.657-1.343-3-3-3zm-12-4.5c0-2.481 2.019-4.5 4.5-4.5s4.5 2.019 4.5 4.5v4.5h-9v-4.5zm12 22.5h-18v-15h18v15zm-9-6c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3z",fill:"currentColor"})});async function z3(t,e){const{options:n}=e;if(!n?.client_id||!n.authorization_endpoint)throw new Error("Missing required OAuth2 authentication parameters");const r=`${me(t.env)}callback`,i=new kr(n.client_id,n.client_secret||null,r),s=S_(),a=rc(),c=n.scope?.split(" ")??[];return{redirectUrl:i.createAuthorizationURLWithPKCE(n.authorization_endpoint,s,ar.S256,a,c).href,code:s,codeVerifier:a}}async function A3(t,e,n,r){const{options:i}=e;if(!i?.client_id||!i.token_endpoint)throw new Error("Missing required authentication parameters");const s=`${me(t.env)}callback`,c=await new kr(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 d=await l.json(),u=d.sub||d.id||d.user_id;if(!u)throw new Error("Unable to get user identifier: response missing sub, id, or user_id");return{sub:u,email:d.email,given_name:d.given_name||d.first_name,family_name:d.family_name||d.last_name,name:d.name||`${d.given_name||d.first_name||""} ${d.family_name||d.last_name||""}`.trim()}}const E3=Object.freeze(Object.defineProperty({__proto__:null,displayName:x3,getRedirect:z3,logo:S3,validateAuthorizationCodeAndGetUser:A3},Symbol.toStringTag,{value:"Module"})),Fu={apple:K2,facebook:Z2,"google-oauth2":r3,vipps:c3,github:f3,microsoft:y3,oidc:k3,oauth2:E3};function j_(t,e){const n=t.env.STRATEGIES||{},i={...Fu,...n}[e];if(!i)throw new Error(`Strategy ${e} not found`);return i}const C3=new Set(["oidc","samlp","waad","adfs","oauth2"]);function N3(t){return C3.has(t.strategy)?t.name:t.strategy}const rh=it.extend({users:o.z.array(Ft)}),I3=it.extend({sessions:o.z.array(Ja)}),j3=it.extend({organizations:o.z.array(zn)}),P3=new o.OpenAPIHono().openapi(o.createRoute({tags:["users"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Ft),rh])}},description:"List of users"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query");if(s?.includes("identities.profileData.email")){const d=s.split("=")[1],f=(await t.env.data.users.list(t.var.tenant_id,{page:e,per_page:n,include_totals:r,q:`email:${d}`})).users.filter(w=>w.linked_to),[g]=f;if(!g)return t.json([]);const _=await t.env.data.users.get(t.var.tenant_id,g.linked_to);if(!_)throw new v(500,{message:"Primary account not found"});return t.json([Ft.parse(_)])}const a=["-_exists_:linked_to"];s&&a.push(s);const c=await t.env.data.users.list(t.var.tenant_id,{page:e,per_page:n,include_totals:r,sort:Ke(i),q:a.join(" ")}),l=c.users.filter(d=>!d.linked_to);return r?t.json(rh.parse({users:l,length:c.length,start:c.start,limit:c.limit})):t.json(o.z.array(Ft).parse(l))}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ft}},description:"List of users"}}}),async t=>{const{user_id:e}=t.req.valid("param"),n=await t.env.data.users.get(t.var.tenant_id,e);if(!n)throw new v(404);if(n.linked_to)throw new v(404,{message:"User is linked to another user"});return t.json(n)}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{user_id:e}=t.req.valid("param");if(!await t.env.data.users.remove(t.var.tenant_id,e))throw new v(404);return await ie(t,t.var.tenant_id,{type:te.SUCCESS_API_OPERATION,description:"Delete a User",response:{statusCode:204,body:{}}}),t.text("OK")}).openapi(o.createRoute({tags:["users"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object({...Fs.shape,password:o.z.string().optional()})}}}},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Ft}},description:"Status"}}}),async t=>{const e=t.req.valid("json");t.set("body",e);const{email:n,phone_number:r,name:i,linked_to:s,email_verified:a,provider:c,connection:l,password:d}=e,u=await t.env.data.connections.get(t.var.tenant_id,l),f=u?N3(u):c||l,g=e.user_id,_=g?gs(g):Xa(),w=`${f}|${_}`;try{const k={email:n,user_id:w,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()},z=await t.env.data.users.create(t.var.tenant_id,k);if(d){const I={user_id:w,password:await Pn.hash(d,10),algorithm:"bcrypt",is_current:!0};await t.env.data.passwords.create(t.var.tenant_id,I)}t.set("user_id",z.user_id),await ie(t,t.var.tenant_id,{type:te.SUCCESS_API_OPERATION,description:"User created"});const N=z.identities?z:{...z,identities:[{connection:z.connection,provider:z.provider,user_id:gs(z.user_id),isSocial:z.is_social}]};return t.json(Ft.parse(N),{status:201})}catch(k){throw k.message==="User already exists"?new v(409,{message:"User already exists"}):k}}).openapi(o.createRoute({tags:["users"],method:"patch",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object({...Fs.shape,verify_email:o.z.boolean(),password:o.z.string()}).partial()}}},params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{data:e}=t.env,n=t.req.valid("json"),{user_id:r}=t.req.valid("param"),{verify_email:i,password:s,connection:a,...c}=n,l=await e.users.get(t.var.tenant_id,r);if(!l)throw new v(404);if(l.linked_to)throw new v(404,{message:"User is linked to another user"});let d=r,u=l;if(a)if(l.connection===a)d=r,u=l;else{const _=(await e.users.list(t.var.tenant_id,{page:0,per_page:100,include_totals:!1,q:`linked_to:${r}`})).users.find(w=>w.connection===a);if(!_)throw new v(404,{message:`No identity found with connection: ${a}`});d=_.user_id,u=_}if(c.email&&c.email!==u.email){const g=await Ru(t.env.data.users,t.var.tenant_id,c.email);if(g.length&&g.some(_=>_.user_id!==d))throw new v(409,{message:"Another user with the same email address already exists."})}if(await t.env.data.users.update(t.var.tenant_id,d,c),s){let g;if(a)if(a==="Username-Password-Authentication")g={provider:u.provider,user_id:gs(d)};else throw new v(400,{message:`Cannot set password for connection: ${a}`});else if(g=l.identities?.find(k=>k.connection==="Username-Password-Authentication"),!g)throw new v(400,{message:"User does not have a password identity"});const _=`${g.provider}|${g.user_id}`,w=await e.passwords.get(t.var.tenant_id,_);w&&await e.passwords.update(t.var.tenant_id,{id:w.id,user_id:_,password:w.password,algorithm:w.algorithm,is_current:!1}),await e.passwords.create(t.var.tenant_id,{user_id:_,password:await Pn.hash(s,10),algorithm:"bcrypt",is_current:!0})}const f=await t.env.data.users.get(t.var.tenant_id,r);if(!f)throw new v(500);return await ie(t,t.var.tenant_id,{type:te.SUCCESS_API_OPERATION,description:"Update a User",body:n,response:{statusCode:200,body:f}}),t.json(f)}).openapi(o.createRoute({tags:["users"],method:"post",path:"/{user_id}/identities",request:{headers:o.z.object({"tenant-id":o.z.string()}),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(o.z.object({connection:o.z.string(),provider:o.z.string(),user_id:o.z.string(),isSocial:o.z.boolean()}))}},description:"Status"}}}),async t=>{const e=t.req.valid("json"),{user_id:n}=t.req.valid("param"),r="link_with"in e?e.link_with:e.user_id,i=await t.env.data.users.get(t.var.tenant_id,n);if(!i)throw new v(400,{message:"Linking an inexistent identity is not allowed."});await t.env.data.users.update(t.var.tenant_id,r,{linked_to:n});const s=await t.env.data.users.list(t.var.tenant_id,{page:0,per_page:10,include_totals:!1,q:`linked_to:${n}`}),a=[i,...s.users].map(c=>({connection:c.connection,provider:c.provider,user_id:gs(c.user_id),isSocial:c.is_social}));return t.json(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()}),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(Ft)}},description:"Status"}}}),async t=>{const{user_id:e,provider:n,linked_user_id:r}=t.req.valid("param");await t.env.data.users.unlink(t.var.tenant_id,e,n,r);const i=await t.env.data.users.get(t.var.tenant_id,e);if(!i)throw new v(404);return t.json([Ft.parse(i)])}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/sessions",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Ja),I3])}},description:"List of sessions"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{include_totals:n,page:r,per_page:i}=t.req.valid("query"),s=await t.env.data.sessions.list(t.var.tenant_id,{page:r,per_page:i,include_totals:n,q:`user_id:${e}`});return n?t.json(s):t.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()}),query:Te},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Tm}},description:"User permissions"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{page:n,per_page:r,sort:i,q:s}=t.req.valid("query");if(!await t.env.data.users.get(t.var.tenant_id,e))throw new v(404,{message:"User not found"});const c=await t.env.data.userPermissions.list(t.var.tenant_id,e,{page:n,per_page:r,include_totals:!1,sort:Ke(i),q:s});return t.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()}),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:["auth:write"]}],responses:{201:{description:"Permissions assigned to user"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{permissions:n}=t.req.valid("json");if(!await t.env.data.users.get(t.var.tenant_id,e))throw new v(404,{message:"User not found"});for(const i of n)if(!await t.env.data.userPermissions.create(t.var.tenant_id,e,{user_id:e,resource_server_identifier:i.resource_server_identifier,permission_name:i.permission_name}))throw new v(500,{message:"Failed to assign permissions to user"});return t.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()}),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:["auth:write"]}],responses:{200:{description:"Permissions removed from user"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{permissions:n}=t.req.valid("json");if(!await t.env.data.users.get(t.var.tenant_id,e))throw new v(404,{message:"User not found"});for(const i of n)if(!await t.env.data.userPermissions.remove(t.var.tenant_id,e,i))throw new v(500,{message:"Failed to remove permissions from user"});return t.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:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Zs}},description:"User roles"}}}),async t=>{const{user_id:e}=t.req.valid("param");if(!await t.env.data.users.get(t.var.tenant_id,e))throw new v(404,{message:"User not found"});const r=await t.env.data.userRoles.list(t.var.tenant_id,e,void 0,"");return t.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:["auth:write"]}],responses:{201:{description:"Roles assigned to user"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{roles:n}=t.req.valid("json");if(!await t.env.data.users.get(t.var.tenant_id,e))throw new v(404,{message:"User not found"});for(const i of n)if(!await t.env.data.userRoles.create(t.var.tenant_id,e,i,""))throw new v(500,{message:"Failed to assign roles to user"});return t.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:["auth:write"]}],responses:{200:{description:"Roles removed from user"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{roles:n}=t.req.valid("json");if(!await t.env.data.users.get(t.var.tenant_id,e))throw new v(404,{message:"User not found"});for(const i of n)if(!await t.env.data.userRoles.remove(t.var.tenant_id,e,i,""))throw new v(500,{message:"Failed to remove roles from user"});return t.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:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([j3,o.z.array(zn)])}},description:"List of user organizations"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{page:n,per_page:r,include_totals:i,sort:s}=t.req.valid("query");if(!await t.env.data.users.get(t.var.tenant_id,e))throw new v(404,{message:"User not found"});const c=await t.env.data.userOrganizations.listUserOrganizations(t.var.tenant_id,e,{page:n,per_page:r,sort:Ke(s)});return i?t.json({organizations:c.organizations,start:c.start,limit:c.limit,length:c.length}):t.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()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"User removed from organization successfully"}}}),async t=>{const{user_id:e,organization_id:n}=t.req.valid("param");if(!await t.env.data.users.get(t.var.tenant_id,e))throw new v(404,{message:"User not found"});const s=(await t.env.data.userOrganizations.list(t.var.tenant_id,{q:`user_id:${e}`,per_page:100})).userOrganizations.find(a=>a.organization_id===n);if(!s)throw new v(404,{message:"User is not a member of this organization"});return await t.env.data.userOrganizations.remove(t.var.tenant_id,s.id),t.json({message:"User removed from organization successfully"})});var ih=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function O3(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var oh={};var sh;function T3(){if(sh)return oh;sh=1;var t;return(function(e){(function(n){var r=typeof globalThis=="object"?globalThis:typeof ih=="object"?ih:typeof self=="object"?self:typeof this=="object"?this:l(),i=s(e);typeof r.Reflect<"u"&&(i=s(r.Reflect,i)),n(i,r),typeof r.Reflect>"u"&&(r.Reflect=e);function s(d,u){return function(f,g){Object.defineProperty(d,f,{configurable:!0,writable:!0,value:g}),u&&u(f,g)}}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",d={__proto__:[]}instanceof Array,u=!l&&!d,f={create:l?function(){return al(Object.create(null))}:d?function(){return al({__proto__:null})}:function(){return al({})},has:u?function($,x){return i.call($,x)}:function($,x){return x in $},get:u?function($,x){return i.call($,x)?$[x]:void 0}:function($,x){return $[x]}},g=Object.getPrototypeOf(Function),_=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Aw(),w=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Ew(),k=typeof WeakMap=="function"?WeakMap:Cw(),z=s?Symbol.for("@reflect-metadata:registry"):void 0,N=xw(),I=Sw(N);function S($,x,A,R){if(K(A)){if(!tf($))throw new TypeError;if(!nf(x))throw new TypeError;return $e($,x)}else{if(!tf($))throw new TypeError;if(!ne(x))throw new TypeError;if(!ne(R)&&!K(R)&&!vt(R))throw new TypeError;return vt(R)&&(R=void 0),A=Dt(A),be($,x,A,R)}}n("decorate",S);function E($,x){function A(R,J){if(!ne(R))throw new TypeError;if(!K(J)&&!$w(J))throw new TypeError;Ut($,x,R,J)}return A}n("metadata",E);function P($,x,A,R){if(!ne(A))throw new TypeError;return K(R)||(R=Dt(R)),Ut($,x,A,R)}n("defineMetadata",P);function G($,x,A){if(!ne(x))throw new TypeError;return K(A)||(A=Dt(A)),sn($,x,A)}n("hasMetadata",G);function Z($,x,A){if(!ne(x))throw new TypeError;return K(A)||(A=Dt(A)),Be($,x,A)}n("hasOwnMetadata",Z);function W($,x,A){if(!ne(x))throw new TypeError;return K(A)||(A=Dt(A)),Qe($,x,A)}n("getMetadata",W);function M($,x,A){if(!ne(x))throw new TypeError;return K(A)||(A=Dt(A)),Lt($,x,A)}n("getOwnMetadata",M);function ce($,x){if(!ne($))throw new TypeError;return K(x)||(x=Dt(x)),Hn($,x)}n("getMetadataKeys",ce);function le($,x){if(!ne($))throw new TypeError;return K(x)||(x=Dt(x)),Pe($,x)}n("getOwnMetadataKeys",le);function fe($,x,A){if(!ne(x))throw new TypeError;if(K(A)||(A=Dt(A)),!ne(x))throw new TypeError;K(A)||(A=Dt(A));var R=Ai(x,A,!1);return K(R)?!1:R.OrdinaryDeleteMetadata($,x,A)}n("deleteMetadata",fe);function $e($,x){for(var A=$.length-1;A>=0;--A){var R=$[A],J=R(x);if(!K(J)&&!vt(J)){if(!nf(J))throw new TypeError;x=J}}return x}function be($,x,A,R){for(var J=$.length-1;J>=0;--J){var ze=$[J],Ie=ze(x,A,R);if(!K(Ie)&&!vt(Ie)){if(!ne(Ie))throw new TypeError;R=Ie}}return R}function sn($,x,A){var R=Be($,x,A);if(R)return!0;var J=sl(x);return vt(J)?!1:sn($,J,A)}function Be($,x,A){var R=Ai(x,A,!1);return K(R)?!1:ef(R.OrdinaryHasOwnMetadata($,x,A))}function Qe($,x,A){var R=Be($,x,A);if(R)return Lt($,x,A);var J=sl(x);if(!vt(J))return Qe($,J,A)}function Lt($,x,A){var R=Ai(x,A,!1);if(!K(R))return R.OrdinaryGetOwnMetadata($,x,A)}function Ut($,x,A,R){var J=Ai(A,R,!0);J.OrdinaryDefineOwnMetadata($,x,A,R)}function Hn($,x){var A=Pe($,x),R=sl($);if(R===null)return A;var J=Hn(R,x);if(J.length<=0)return A;if(A.length<=0)return J;for(var ze=new w,Ie=[],oe=0,L=A;oe<L.length;oe++){var q=L[oe],H=ze.has(q);H||(ze.add(q),Ie.push(q))}for(var V=0,se=J;V<se.length;V++){var q=se[V],H=ze.has(q);H||(ze.add(q),Ie.push(q))}return Ie}function Pe($,x){var A=Ai($,x,!1);return A?A.OrdinaryOwnMetadataKeys($,x):[]}function et($){if($===null)return 1;switch(typeof $){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return $===null?1:6;default:return 6}}function K($){return $===void 0}function vt($){return $===null}function il($){return typeof $=="symbol"}function ne($){return typeof $=="object"?$!==null:typeof $=="function"}function Vn($,x){switch(et($)){case 0:return $;case 1:return $;case 2:return $;case 3:return $;case 4:return $;case 5:return $}var A="string",R=rf($,a);if(R!==void 0){var J=R.call($,A);if(ne(J))throw new TypeError;return J}return bw($)}function bw($,x){var A,R,J;{var ze=$.toString;if(fs(ze)){var R=ze.call($);if(!ne(R))return R}var A=$.valueOf;if(fs(A)){var R=A.call($);if(!ne(R))return R}}throw new TypeError}function ef($){return!!$}function vw($){return""+$}function Dt($){var x=Vn($);return il(x)?x:vw(x)}function tf($){return Array.isArray?Array.isArray($):$ instanceof Object?$ instanceof Array:Object.prototype.toString.call($)==="[object Array]"}function fs($){return typeof $=="function"}function nf($){return typeof $=="function"}function $w($){switch(et($)){case 3:return!0;case 4:return!0;default:return!1}}function ol($,x){return $===x||$!==$&&x!==x}function rf($,x){var A=$[x];if(A!=null){if(!fs(A))throw new TypeError;return A}}function of($){var x=rf($,c);if(!fs(x))throw new TypeError;var A=x.call($);if(!ne(A))throw new TypeError;return A}function sf($){return $.value}function af($){var x=$.next();return x.done?!1:x}function cf($){var x=$.return;x&&x.call($)}function sl($){var x=Object.getPrototypeOf($);if(typeof $!="function"||$===g||x!==g)return x;var A=$.prototype,R=A&&Object.getPrototypeOf(A);if(R==null||R===Object.prototype)return x;var J=R.constructor;return typeof J!="function"||J===$?x:J}function kw(){var $;!K(z)&&typeof r.Reflect<"u"&&!(z in r.Reflect)&&typeof r.Reflect.defineMetadata=="function"&&($=zw(r.Reflect));var x,A,R,J=new k,ze={registerProvider:Ie,getProvider:L,setProvider:H};return ze;function Ie(V){if(!Object.isExtensible(ze))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case $===V:break;case K(x):x=V;break;case x===V:break;case K(A):A=V;break;case A===V:break;default:R===void 0&&(R=new w),R.add(V);break}}function oe(V,se){if(!K(x)){if(x.isProviderFor(V,se))return x;if(!K(A)){if(A.isProviderFor(V,se))return x;if(!K(R))for(var ge=of(R);;){var Ae=af(ge);if(!Ae)return;var $t=sf(Ae);if($t.isProviderFor(V,se))return cf(ge),$t}}}if(!K($)&&$.isProviderFor(V,se))return $}function L(V,se){var ge=J.get(V),Ae;return K(ge)||(Ae=ge.get(se)),K(Ae)&&(Ae=oe(V,se),K(Ae)||(K(ge)&&(ge=new _,J.set(V,ge)),ge.set(se,Ae))),Ae}function q(V){if(K(V))throw new TypeError;return x===V||A===V||!K(R)&&R.has(V)}function H(V,se,ge){if(!q(ge))throw new Error("Metadata provider not registered.");var Ae=L(V,se);if(Ae!==ge){if(!K(Ae))return!1;var $t=J.get(V);K($t)&&($t=new _,J.set(V,$t)),$t.set(se,ge)}return!0}}function xw(){var $;return!K(z)&&ne(r.Reflect)&&Object.isExtensible(r.Reflect)&&($=r.Reflect[z]),K($)&&($=kw()),!K(z)&&ne(r.Reflect)&&Object.isExtensible(r.Reflect)&&Object.defineProperty(r.Reflect,z,{enumerable:!1,configurable:!1,writable:!1,value:$}),$}function Sw($){var x=new k,A={isProviderFor:function(q,H){var V=x.get(q);return K(V)?!1:V.has(H)},OrdinaryDefineOwnMetadata:Ie,OrdinaryHasOwnMetadata:J,OrdinaryGetOwnMetadata:ze,OrdinaryOwnMetadataKeys:oe,OrdinaryDeleteMetadata:L};return N.registerProvider(A),A;function R(q,H,V){var se=x.get(q),ge=!1;if(K(se)){if(!V)return;se=new _,x.set(q,se),ge=!0}var Ae=se.get(H);if(K(Ae)){if(!V)return;if(Ae=new _,se.set(H,Ae),!$.setProvider(q,H,A))throw se.delete(H),ge&&x.delete(q),new Error("Wrong provider for target.")}return Ae}function J(q,H,V){var se=R(H,V,!1);return K(se)?!1:ef(se.has(q))}function ze(q,H,V){var se=R(H,V,!1);if(!K(se))return se.get(q)}function Ie(q,H,V,se){var ge=R(V,se,!0);ge.set(q,H)}function oe(q,H){var V=[],se=R(q,H,!1);if(K(se))return V;for(var ge=se.keys(),Ae=of(ge),$t=0;;){var lf=af(Ae);if(!lf)return V.length=$t,V;var Nw=sf(lf);try{V[$t]=Nw}catch(Iw){try{cf(Ae)}finally{throw Iw}}$t++}}function L(q,H,V){var se=R(H,V,!1);if(K(se)||!se.delete(q))return!1;if(se.size===0){var ge=x.get(H);K(ge)||(ge.delete(V),ge.size===0&&x.delete(ge))}return!0}}function zw($){var x=$.defineMetadata,A=$.hasOwnMetadata,R=$.getOwnMetadata,J=$.getOwnMetadataKeys,ze=$.deleteMetadata,Ie=new k,oe={isProviderFor:function(L,q){var H=Ie.get(L);return!K(H)&&H.has(q)?!0:J(L,q).length?(K(H)&&(H=new w,Ie.set(L,H)),H.add(q),!0):!1},OrdinaryDefineOwnMetadata:x,OrdinaryHasOwnMetadata:A,OrdinaryGetOwnMetadata:R,OrdinaryOwnMetadataKeys:J,OrdinaryDeleteMetadata:ze};return oe}function Ai($,x,A){var R=N.getProvider($,x);if(!K(R))return R;if(A){if(N.setProvider($,x,I))return I;throw new Error("Illegal state.")}}function Aw(){var $={},x=[],A=(function(){function oe(L,q,H){this._index=0,this._keys=L,this._values=q,this._selector=H}return oe.prototype["@@iterator"]=function(){return this},oe.prototype[c]=function(){return this},oe.prototype.next=function(){var L=this._index;if(L>=0&&L<this._keys.length){var q=this._selector(this._keys[L],this._values[L]);return L+1>=this._keys.length?(this._index=-1,this._keys=x,this._values=x):this._index++,{value:q,done:!1}}return{value:void 0,done:!0}},oe.prototype.throw=function(L){throw this._index>=0&&(this._index=-1,this._keys=x,this._values=x),L},oe.prototype.return=function(L){return this._index>=0&&(this._index=-1,this._keys=x,this._values=x),{value:L,done:!0}},oe})(),R=(function(){function oe(){this._keys=[],this._values=[],this._cacheKey=$,this._cacheIndex=-2}return Object.defineProperty(oe.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),oe.prototype.has=function(L){return this._find(L,!1)>=0},oe.prototype.get=function(L){var q=this._find(L,!1);return q>=0?this._values[q]:void 0},oe.prototype.set=function(L,q){var H=this._find(L,!0);return this._values[H]=q,this},oe.prototype.delete=function(L){var q=this._find(L,!1);if(q>=0){for(var H=this._keys.length,V=q+1;V<H;V++)this._keys[V-1]=this._keys[V],this._values[V-1]=this._values[V];return this._keys.length--,this._values.length--,ol(L,this._cacheKey)&&(this._cacheKey=$,this._cacheIndex=-2),!0}return!1},oe.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=$,this._cacheIndex=-2},oe.prototype.keys=function(){return new A(this._keys,this._values,J)},oe.prototype.values=function(){return new A(this._keys,this._values,ze)},oe.prototype.entries=function(){return new A(this._keys,this._values,Ie)},oe.prototype["@@iterator"]=function(){return this.entries()},oe.prototype[c]=function(){return this.entries()},oe.prototype._find=function(L,q){if(!ol(this._cacheKey,L)){this._cacheIndex=-1;for(var H=0;H<this._keys.length;H++)if(ol(this._keys[H],L)){this._cacheIndex=H;break}}return this._cacheIndex<0&&q&&(this._cacheIndex=this._keys.length,this._keys.push(L),this._values.push(void 0)),this._cacheIndex},oe})();return R;function J(oe,L){return oe}function ze(oe,L){return L}function Ie(oe,L){return[oe,L]}}function Ew(){var $=(function(){function x(){this._map=new _}return Object.defineProperty(x.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),x.prototype.has=function(A){return this._map.has(A)},x.prototype.add=function(A){return this._map.set(A,A),this},x.prototype.delete=function(A){return this._map.delete(A)},x.prototype.clear=function(){this._map.clear()},x.prototype.keys=function(){return this._map.keys()},x.prototype.values=function(){return this._map.keys()},x.prototype.entries=function(){return this._map.entries()},x.prototype["@@iterator"]=function(){return this.keys()},x.prototype[c]=function(){return this.keys()},x})();return $}function Cw(){var $=16,x=f.create(),A=R();return(function(){function L(){this._key=R()}return L.prototype.has=function(q){var H=J(q,!1);return H!==void 0?f.has(H,this._key):!1},L.prototype.get=function(q){var H=J(q,!1);return H!==void 0?f.get(H,this._key):void 0},L.prototype.set=function(q,H){var V=J(q,!0);return V[this._key]=H,this},L.prototype.delete=function(q){var H=J(q,!1);return H!==void 0?delete H[this._key]:!1},L.prototype.clear=function(){this._key=R()},L})();function R(){var L;do L="@@WeakMap@@"+oe();while(f.has(x,L));return x[L]=!0,L}function J(L,q){if(!i.call(L,A)){if(!q)return;Object.defineProperty(L,A,{value:f.create()})}return L[A]}function ze(L,q){for(var H=0;H<q;++H)L[H]=Math.random()*255|0;return L}function Ie(L){if(typeof Uint8Array=="function"){var q=new Uint8Array(L);return typeof crypto<"u"?crypto.getRandomValues(q):typeof msCrypto<"u"?msCrypto.getRandomValues(q):ze(q,L),q}return ze(new Array(L),L)}function oe(){var L=Ie($);L[6]=L[6]&79|64,L[8]=L[8]&191|128;for(var q="",H=0;H<$;++H){var V=L[H];(H===4||H===6||H===8)&&(q+="-"),V<16&&(q+="0"),q+=V.toString(16).toLowerCase()}return q}}function al($){return $.__=void 0,delete $.__,$}})})(t||(t={})),oh}T3();const R3="[object ArrayBuffer]";class T{static isArrayBuffer(e){return Object.prototype.toString.call(e)===R3}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,n){if(e.constructor===n)return e;if(this.isArrayBuffer(e))return new n(e);if(this.isArrayBufferView(e))return new n(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,n){const r=T.toUint8Array(e),i=T.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(...e){let n;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?n=e[0]:e[e.length-1]instanceof Function?n=e.slice(0,e.length-1):n=e;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 e[e.length-1]instanceof Function?this.toView(i,e[e.length-1]):i.buffer}}const pl="string",B3=/^[0-9a-f\s]+$/i,L3=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,U3=/^[a-zA-Z0-9-_]+$/;class ah{static fromString(e){const n=unescape(encodeURIComponent(e)),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r.buffer}static toString(e){const n=T.toUint8Array(e);let r="";for(let s=0;s<n.length;s++)r+=String.fromCharCode(n[s]);return decodeURIComponent(escape(r))}}class qt{static toString(e,n=!1){const r=T.toArrayBuffer(e),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(e,n=!1){const r=new ArrayBuffer(e.length*2),i=new DataView(r);for(let s=0;s<e.length;s++)i.setUint16(s*2,e.charCodeAt(s),n);return r}}class F{static isHex(e){return typeof e===pl&&B3.test(e)}static isBase64(e){return typeof e===pl&&L3.test(e)}static isBase64Url(e){return typeof e===pl&&U3.test(e)}static ToString(e,n="utf8"){const r=T.toUint8Array(e);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 qt.toString(r,!0);case"utf16":case"utf16be":return qt.toString(r);default:throw new Error(`Unknown type of encoding '${n}'`)}}static FromString(e,n="utf8"){if(!e)return new ArrayBuffer(0);switch(n.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return qt.fromString(e,!0);case"utf16":case"utf16be":return qt.fromString(e);default:throw new Error(`Unknown type of encoding '${n}'`)}}static ToBase64(e){const n=T.toUint8Array(e);if(typeof btoa<"u"){const r=this.ToString(n,"binary");return btoa(r)}else return Buffer.from(n).toString("base64")}static FromBase64(e){const n=this.formatString(e);if(!n)return new ArrayBuffer(0);if(!F.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(e){const n=this.formatString(e);if(!n)return new ArrayBuffer(0);if(!F.isBase64Url(n))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(n.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,n=F.DEFAULT_UTF8_ENCODING){switch(n){case"ascii":return this.FromBinary(e);case"utf8":return ah.fromString(e);case"utf16":case"utf16be":return qt.fromString(e);case"utf16le":case"usc2":return qt.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${n}'`)}}static ToUtf8String(e,n=F.DEFAULT_UTF8_ENCODING){switch(n){case"ascii":return this.ToBinary(e);case"utf8":return ah.toString(e);case"utf16":case"utf16be":return qt.toString(e);case"utf16le":case"usc2":return qt.toString(e,!0);default:throw new Error(`Unknown type of encoding '${n}'`)}}static FromBinary(e){const n=e.length,r=new Uint8Array(n);for(let i=0;i<n;i++)r[i]=e.charCodeAt(i);return r.buffer}static ToBinary(e){const n=T.toUint8Array(e);let r="";for(let i=0;i<n.length;i++)r+=String.fromCharCode(n[i]);return r}static ToHex(e){const n=T.toUint8Array(e);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(e){let n=this.formatString(e);if(!n)return new ArrayBuffer(0);if(!F.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(e,n=!1){return qt.toString(e,n)}static FromUtf16String(e,n=!1){return qt.fromString(e,n)}static Base64Padding(e){const n=4-e.length%4;if(n<4)for(let r=0;r<n;r++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}}F.DEFAULT_UTF8_ENCODING="utf8";function D3(...t){const e=t.map(i=>i.byteLength).reduce((i,s)=>i+s),n=new Uint8Array(e);let r=0;return t.map(i=>new Uint8Array(i)).forEach(i=>{for(const s of i)n[r++]=s}),n.buffer}function P_(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;const n=new Uint8Array(t),r=new Uint8Array(e);for(let i=0;i<t.byteLength;i++)if(n[i]!==r[i])return!1;return!0}function Zr(t,e){let n=0;if(t.length===1)return t[0];for(let r=t.length-1;r>=0;r--)n+=t[t.length-1-r]*Math.pow(2,e*r);return n}function cr(t,e,n=-1){const r=n;let i=t,s=0,a=Math.pow(2,e);for(let c=1;c<8;c++){if(t<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 d=new Uint8Array(l);for(let u=c-1;u>=0;u--){const f=Math.pow(2,u*e);d[s-u-1]=Math.floor(i/f),i-=d[s-u-1]*f}return l}a*=Math.pow(2,e)}return new ArrayBuffer(0)}function Jl(...t){let e=0,n=0;for(const s of t)e+=s.length;const r=new ArrayBuffer(e),i=new Uint8Array(r);for(const s of t)i.set(s,n),n+=s.length;return i}function O_(){const t=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const c=t[0]===255&&t[1]&128,l=t[0]===0&&(t[1]&128)===0;(c||l)&&this.warnings.push("Needlessly long format")}const e=new ArrayBuffer(this.valueHex.byteLength),n=new Uint8Array(e);for(let c=0;c<this.valueHex.byteLength;c++)n[c]=0;n[0]=t[0]&128;const r=Zr(n,8),i=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(i);for(let c=0;c<this.valueHex.byteLength;c++)s[c]=t[c];return s[0]&=127,Zr(s,8)-r}function M3(t){const e=t<0?t*-1:t;let n=128;for(let r=1;r<8;r++){if(e<=n){if(t<0){const a=n-e,c=cr(a,8,r),l=new Uint8Array(c);return l[0]|=128,c}let i=cr(e,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 q3(t,e){if(t.byteLength!==e.byteLength)return!1;const n=new Uint8Array(t),r=new Uint8Array(e);for(let i=0;i<n.length;i++)if(n[i]!==r[i])return!1;return!0}function at(t,e){const n=t.toString(10);if(e<n.length)return"";const r=e-n.length,i=new Array(r);for(let a=0;a<r;a++)i[a]="0";return i.join("").concat(n)}function sa(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Hu(t){let e=0,n=0;for(let i=0;i<t.length;i++){const s=t[i];e+=s.byteLength}const r=new Uint8Array(e);for(let i=0;i<t.length;i++){const s=t[i];r.set(new Uint8Array(s),n),n+=s.byteLength}return r.buffer}function yn(t,e,n,r){return e instanceof Uint8Array?e.byteLength?n<0?(t.error="Wrong parameter: inputOffset less than zero",!1):r<0?(t.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-n-r<0?(t.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(t.error="Wrong parameter: inputBuffer has zero length",!1):(t.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class oc{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Hu(this.items)}}const Ni=[new Uint8Array([1])],ch="0123456789",fl="name",lh="valueHexView",F3="isHexOnly",H3="idBlock",V3="tagClass",K3="tagNumber",G3="isConstructed",W3="fromBER",J3="toBER",X3="local",nt="",Xt=new ArrayBuffer(0),sc=new Uint8Array(0),$o="EndOfContent",T_="OCTET STRING",R_="BIT STRING";function Zt(t){var e;return e=class extends t{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?T.toUint8Array(s.valueHex):sc}fromBER(r,i,s){const a=r instanceof ArrayBuffer?new Uint8Array(r):r;if(!yn(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",Xt)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:F.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}class xr{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:n=nt,warnings:r=[],valueBeforeDecode:i=sc}={}){this.blockLength=e,this.error=n,this.warnings=r,this.valueBeforeDecodeView=T.toUint8Array(i)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:F.ToHex(this.valueBeforeDecodeView)}}}xr.NAME="baseBlock";class Ye extends xr{fromBER(e,n,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}Ye.NAME="valueBlock";class B_ extends Zt(xr){constructor({idBlock:e={}}={}){var n,r,i,s;super(),e?(this.isHexOnly=(n=e.isHexOnly)!==null&&n!==void 0?n:!1,this.valueHexView=e.valueHex?T.toUint8Array(e.valueHex):sc,this.tagClass=(r=e.tagClass)!==null&&r!==void 0?r:-1,this.tagNumber=(i=e.tagNumber)!==null&&i!==void 0?i:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!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",Xt}if(this.isConstructed&&(n|=32),this.tagNumber<31&&!this.isHexOnly){const i=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,n|=s,i[0]=n}return i.buffer}if(!this.isHexOnly){const i=cr(this.tagNumber,7),s=new Uint8Array(i),a=i.byteLength,c=new Uint8Array(a+1);if(c[0]=n|31,!e){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,!e){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(e,n,r){const i=T.toUint8Array(e);if(!yn(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,d=this.valueHexView=new Uint8Array(255),u=255;for(;s[l]&128;){if(d[l-1]=s[l]&127,l++,l>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(l===u){u+=255;const g=new Uint8Array(u);for(let _=0;_<d.length;_++)g[_]=d[_];d=this.valueHexView=new Uint8Array(u)}}this.blockLength=l+1,d[l-1]=s[l]&127;const f=new Uint8Array(l);for(let g=0;g<l;g++)f[g]=d[g];d=this.valueHexView=new Uint8Array(l),d.set(f),this.blockLength<=9?this.tagNumber=Zr(d,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}}}B_.NAME="identificationBlock";class L_ extends xr{constructor({lenBlock:e={}}={}){var n,r,i;super(),this.isIndefiniteForm=(n=e.isIndefiniteForm)!==null&&n!==void 0?n:!1,this.longFormUsed=(r=e.longFormUsed)!==null&&r!==void 0?r:!1,this.length=(i=e.length)!==null&&i!==void 0?i:0}fromBER(e,n,r){const i=T.toUint8Array(e);if(!yn(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=Zr(l,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=a+1,n+this.blockLength}toBER(e=!1){let n,r;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return n=new ArrayBuffer(1),e===!1&&(r=new Uint8Array(n),r[0]=128),n;if(this.longFormUsed){const i=cr(this.length,8);if(i.byteLength>127)return this.error="Too big length",Xt;if(n=new ArrayBuffer(i.byteLength+1),e)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),e===!1&&(r=new Uint8Array(n),r[0]=this.length),n}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}L_.NAME="lengthBlock";const D={};class Me extends xr{constructor({name:e=nt,optional:n=!1,primitiveSchema:r,...i}={},s){super(i),this.name=e,this.optional=n,r&&(this.primitiveSchema=r),this.idBlock=new B_(i),this.lenBlock=new L_(i),this.valueBlock=s?new s(i):new Ye(i)}fromBER(e,n,r){const i=this.valueBlock.fromBER(e,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(e,n){const r=n||new oc;n||U_(this);const i=this.idBlock.toBER(e);if(r.write(i),this.lenBlock.isIndefiniteForm)r.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,r),r.write(new ArrayBuffer(2));else{const s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;const a=this.lenBlock.toBER(e);r.write(a),r.write(s)}return n?Xt:r.final()}toJSON(){const e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():F.ToHex(this.toBER())}onAsciiEncoding(){const e=this.constructor.NAME,n=F.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${n}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;const n=this.toBER(),r=e.toBER();return q3(n,r)}}Me.NAME="BaseBlock";function U_(t){var e;if(t instanceof D.Constructed)for(const n of t.valueBlock.value)U_(n)&&(t.lenBlock.isIndefiniteForm=!0);return!!(!((e=t.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}class Vu extends Me{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=nt,...n}={},r){super(n,r),e&&this.fromString(e)}fromBER(e,n,r){const i=this.valueBlock.fromBER(e,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}'`}}Vu.NAME="BaseStringBlock";class D_ extends Zt(Ye){constructor({isHexOnly:e=!0,...n}={}){super(n),this.isHexOnly=e}}D_.NAME="PrimitiveValueBlock";var M_;class Ko extends Me{constructor(e={}){super(e,D_),this.idBlock.isConstructed=!1}}M_=Ko;D.Primitive=M_;Ko.NAME="PRIMITIVE";function Z3(t,e){if(t instanceof e)return t;const n=new e;return n.idBlock=t.idBlock,n.lenBlock=t.lenBlock,n.warnings=t.warnings,n.valueBeforeDecodeView=t.valueBeforeDecodeView,n}function gi(t,e=0,n=t.length){const r=e;let i=new Me({},Ye);const s=new xr;if(!yn(s,t,e,n))return i.error=s.error,{offset:-1,result:i};if(!t.subarray(e,e+n).length)return i.error="Zero buffer length",{offset:-1,result:i};let c=i.idBlock.fromBER(t,e,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(e=c,n-=i.idBlock.blockLength,c=i.lenBlock.fromBER(t,e,n),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),c===-1)return i.error=i.lenBlock.error,{offset:-1,result:i};if(e=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=Me;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=D.EndOfContent;break;case 1:l=D.Boolean;break;case 2:l=D.Integer;break;case 3:l=D.BitString;break;case 4:l=D.OctetString;break;case 5:l=D.Null;break;case 6:l=D.ObjectIdentifier;break;case 10:l=D.Enumerated;break;case 12:l=D.Utf8String;break;case 13:l=D.RelativeObjectIdentifier;break;case 14:l=D.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:l=D.Sequence;break;case 17:l=D.Set;break;case 18:l=D.NumericString;break;case 19:l=D.PrintableString;break;case 20:l=D.TeletexString;break;case 21:l=D.VideotexString;break;case 22:l=D.IA5String;break;case 23:l=D.UTCTime;break;case 24:l=D.GeneralizedTime;break;case 25:l=D.GraphicString;break;case 26:l=D.VisibleString;break;case 27:l=D.GeneralString;break;case 28:l=D.UniversalString;break;case 29:l=D.CharacterString;break;case 30:l=D.BmpString;break;case 31:l=D.DATE;break;case 32:l=D.TimeOfDay;break;case 33:l=D.DateTime;break;case 34:l=D.Duration;break;default:{const d=i.idBlock.isConstructed?new D.Constructed:new D.Primitive;d.idBlock=i.idBlock,d.lenBlock=i.lenBlock,d.warnings=i.warnings,i=d}}break;default:l=i.idBlock.isConstructed?D.Constructed:D.Primitive}return i=Z3(i,l),c=i.fromBER(t,e,i.lenBlock.isIndefiniteForm?n:i.lenBlock.length),i.valueBeforeDecodeView=t.subarray(r,r+i.blockLength),{offset:c,result:i}}function Hr(t){if(!t.byteLength){const e=new Me({},Ye);return e.error="Input buffer has zero length",{offset:-1,result:e}}return gi(T.toUint8Array(t).slice(),0,t.byteLength)}function Y3(t,e){return t?1:e}class In extends Ye{constructor({value:e=[],isIndefiniteForm:n=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=n}fromBER(e,n,r){const i=T.toUint8Array(e);if(!yn(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(;Y3(this.isIndefiniteForm,r)>0;){const a=gi(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===$o)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===$o?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,n){const r=n||new oc;for(let i=0;i<this.value.length;i++)this.value[i].toBER(e,r);return n?Xt:r.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const n of this.value)e.value.push(n.toJSON());return e}}In.NAME="ConstructedValueBlock";var q_;class Ze extends Me{constructor(e={}){super(e,In),this.idBlock.isConstructed=!0}fromBER(e,n,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const i=this.valueBlock.fromBER(e,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 e=[];for(const r of this.valueBlock.value)e.push(r.toString("ascii").split(`
67
+ 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 s3(t,e){const{options:n}=e;if(!n?.client_id||!n.client_secret)throw new Error("Missing required authentication parameters");const r=new kr(n.client_id,n.client_secret,`${me(t.env)}callback`),i=pe(),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 a3(t,e,n){const{options:r}=e;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new kr(r.client_id,r.client_secret,`${me(t.env)}callback`).validateAuthorizationCode("https://api.vipps.no/access-management-1.0/access/oauth2/token",n,null),a=Mo(s.idToken());if(!a)throw new Error("Invalid ID token");const c=gi.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 B(400,{message:"Failed to get user from vipps"});return await l.json()}const c3=Object.freeze(Object.defineProperty({__proto__:null,displayName:i3,getRedirect:s3,logo:o3,validateAuthorizationCodeAndGetUser:a3},Symbol.toStringTag,{value:"Module"})),l3="GitHub",d3=({className:t=""})=>p("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:t,children:p("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M22.5 0C10.074 0 0 10.335 0 23.077C0 33.266 6.444 41.895 15.39 44.955C16.515 45.165 16.935 44.46 16.935 43.857C16.935 43.32 16.92 41.865 16.905 39.99C10.65 41.355 9.33 36.99 9.33 36.99C8.31 34.32 6.825 33.615 6.825 33.615C4.77 32.205 6.975 32.235 6.975 32.235C9.24 32.385 10.425 34.59 10.425 34.59C12.45 38.13 15.75 37.125 17.01 36.555C17.22 35.07 17.82 34.065 18.48 33.51C13.455 32.94 8.19 30.93 8.19 22.035C8.19 19.5 9.075 17.43 10.47 15.81C10.23 15.24 9.435 12.87 10.695 9.66C10.695 9.66 12.585 9.045 16.875 12.06C18.675 11.565 20.595 11.31 22.5 11.31C24.405 11.31 26.325 11.565 28.125 12.06C32.415 9.045 34.305 9.66 34.305 9.66C35.565 12.87 34.77 15.24 34.53 15.81C35.925 17.43 36.81 19.5 36.81 22.035C36.81 30.96 31.53 32.925 26.49 33.48C27.33 34.2 28.095 35.625 28.095 37.815C28.095 40.95 28.065 43.47 28.065 43.857C28.065 44.46 28.485 45.18 29.625 44.955C38.571 41.88 45 33.252 45 23.077C45 10.335 34.926 0 22.5 0Z",fill:"currentColor"})});async function u3(t,e){const{options:n}=e;if(!n?.client_id||!n.client_secret)throw new Error("Missing required GitHub authentication parameters");const r=`${me(t.env)}callback`,i=new E_(n.client_id,n.client_secret,r),s=pe();return{redirectUrl:i.createAuthorizationURL(s,n.scope?.split(" ")||["user:email"]).href,code:s}}async function p3(t,e,n){const{options:r}=e;if(!r?.client_id||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new E_(r.client_id,r.client_secret,`${me(t.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 d=c.email;if(l.ok){const u=await l.json(),f=u.find(g=>g.primary&&g.verified)||u.find(g=>g.verified);f&&(d=f.email)}return t.set("log",`GitHub user: ${JSON.stringify(c)}`),{sub:c.id.toString(),email:d,name:c.name,given_name:c.name?.split(" ")[0],family_name:c.name?.split(" ").slice(1).join(" "),picture:c.avatar_url}}const f3=Object.freeze(Object.defineProperty({__proto__:null,displayName:l3,getRedirect:u3,logo:d3,validateAuthorizationCodeAndGetUser:p3},Symbol.toStringTag,{value:"Module"})),h3="Microsoft",g3=({className:t=""})=>p("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:t,children:[p("path",{fill:"#F25022",d:"M0 0H21.43V21.43H0V0Z"}),p("path",{fill:"#7FBA00",d:"M23.57 0H45V21.43H23.57V0Z"}),p("path",{fill:"#00A4EF",d:"M0 23.57H21.43V45H0V23.57Z"}),p("path",{fill:"#FFB900",d:"M23.57 23.57H45V45H23.57V23.57Z"})]});async function m3(t,e){const{options:n}=e;if(!n?.client_id||!n.client_secret)throw new Error("Missing required Microsoft authentication parameters");const r=`${me(t.env)}callback`,i=n.realms||"common",s=new N_(i,n.client_id,n.client_secret,r),a=pe(),c=rc();return{redirectUrl:s.createAuthorizationURL(a,c,n.scope?.split(" ")||["openid","profile","email"]).href,code:a,codeVerifier:c}}async function _3(t,e,n,r){const{options:i}=e;if(!i?.client_id||!i.client_secret||!r)throw new Error("Missing required authentication parameters");const s=i.realms||"common",c=await new N_(s,i.client_id,i.client_secret,`${me(t.env)}callback`).validateAuthorizationCode(n,r),l=Mo(c.idToken());if(!l)throw new Error("Invalid ID token");const d=gi.parse(l.payload);return t.set("log",`Microsoft user: ${JSON.stringify(d)}`),{sub:d.sub,email:d.email,given_name:d.given_name,family_name:d.family_name,name:d.name,picture:d.picture}}const y3=Object.freeze(Object.defineProperty({__proto__:null,displayName:h3,getRedirect:m3,logo:g3,validateAuthorizationCodeAndGetUser:_3},Symbol.toStringTag,{value:"Module"})),w3="OpenID Connect",b3=({className:t="",iconUrl:e})=>e?p("img",{src:e,alt:"OIDC Provider",className:t}):p("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:t,children:[p("path",{d:"M22.5 0C10.074 0 0 10.074 0 22.5S10.074 45 22.5 45 45 34.926 45 22.5 34.926 0 22.5 0zm0 40.5c-9.941 0-18-8.059-18-18s8.059-18 18-18 18 8.059 18 18-8.059 18-18 18z",fill:"currentColor"}),p("path",{d:"M22.5 9c-7.456 0-13.5 6.044-13.5 13.5S15.044 36 22.5 36 36 29.956 36 22.5 29.956 9 22.5 9zm0 22.5c-4.971 0-9-4.029-9-9s4.029-9 9-9 9 4.029 9 9-4.029 9-9 9z",fill:"currentColor"})]});async function v3(t,e){const{options:n}=e;if(!n?.client_id||!n.authorization_endpoint)throw new Error("Missing required OIDC authentication parameters");const r=`${me(t.env)}callback`,i=new kr(n.client_id,n.client_secret||null,r),s=S_(),a=rc(),c=n.scope?.split(" ")??["openid","profile","email"];return{redirectUrl:i.createAuthorizationURLWithPKCE(n.authorization_endpoint,s,ar.S256,a,c).href,code:s,codeVerifier:a}}async function $3(t,e,n,r){const{options:i}=e;if(!i?.client_id||!i.token_endpoint)throw new Error("Missing required authentication parameters");const s=`${me(t.env)}callback`,c=await new kr(i.client_id,i.client_secret||null,s).validateAuthorizationCode(i.token_endpoint,n,r||null);if(c.data.id_token){const d=Mo(c.idToken());if(d?.payload){const u=gi.passthrough().parse(d.payload);return{sub:u.sub,email:u.email,given_name:u.given_name,family_name:u.family_name,name:u.name}}}if(i.userinfo_endpoint){const d=await fetch(i.userinfo_endpoint,{headers:{Authorization:`Bearer ${c.accessToken()}`}});if(!d.ok)throw new Error("Failed to fetch user info");const u=await d.json();if(!u.sub)throw new Error("Unable to get user identifier: userinfo response missing sub");return{sub:u.sub,email:u.email,given_name:u.given_name,family_name:u.family_name,name:u.name}}throw new Error("Unable to get user information: no ID token or userinfo endpoint")}const k3=Object.freeze(Object.defineProperty({__proto__:null,displayName:w3,getRedirect:v3,logo:b3,validateAuthorizationCodeAndGetUser:$3},Symbol.toStringTag,{value:"Module"})),x3="OAuth 2.0",S3=({className:t="",iconUrl:e})=>e?p("img",{src:e,alt:"OAuth Provider",className:t}):p("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",className:t,children:p("path",{d:"M31.5 18h-1.5v-4.5c0-4.136-3.364-7.5-7.5-7.5s-7.5 3.364-7.5 7.5v4.5h-1.5c-1.657 0-3 1.343-3 3v15c0 1.657 1.343 3 3 3h18c1.657 0 3-1.343 3-3v-15c0-1.657-1.343-3-3-3zm-12-4.5c0-2.481 2.019-4.5 4.5-4.5s4.5 2.019 4.5 4.5v4.5h-9v-4.5zm12 22.5h-18v-15h18v15zm-9-6c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3z",fill:"currentColor"})});async function z3(t,e){const{options:n}=e;if(!n?.client_id||!n.authorization_endpoint)throw new Error("Missing required OAuth2 authentication parameters");const r=`${me(t.env)}callback`,i=new kr(n.client_id,n.client_secret||null,r),s=S_(),a=rc(),c=n.scope?.split(" ")??[];return{redirectUrl:i.createAuthorizationURLWithPKCE(n.authorization_endpoint,s,ar.S256,a,c).href,code:s,codeVerifier:a}}async function A3(t,e,n,r){const{options:i}=e;if(!i?.client_id||!i.token_endpoint)throw new Error("Missing required authentication parameters");const s=`${me(t.env)}callback`,c=await new kr(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 d=await l.json(),u=d.sub||d.id||d.user_id;if(!u)throw new Error("Unable to get user identifier: response missing sub, id, or user_id");return{sub:u,email:d.email,given_name:d.given_name||d.first_name,family_name:d.family_name||d.last_name,name:d.name||`${d.given_name||d.first_name||""} ${d.family_name||d.last_name||""}`.trim()}}const E3=Object.freeze(Object.defineProperty({__proto__:null,displayName:x3,getRedirect:z3,logo:S3,validateAuthorizationCodeAndGetUser:A3},Symbol.toStringTag,{value:"Module"})),Fu={apple:K2,facebook:Z2,"google-oauth2":r3,vipps:c3,github:f3,microsoft:y3,oidc:k3,oauth2:E3};function j_(t,e){const n=t.env.STRATEGIES||{},i={...Fu,...n}[e];if(!i)throw new Error(`Strategy ${e} not found`);return i}const C3=new Set(["oidc","samlp","waad","adfs","oauth2"]);function N3(t){return C3.has(t.strategy)?t.name:t.strategy}const rh=it.extend({users:o.z.array(Ft)}),I3=it.extend({sessions:o.z.array(Ja)}),j3=it.extend({organizations:o.z.array(zn)}),P3=new o.OpenAPIHono().openapi(o.createRoute({tags:["users"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Ft),rh])}},description:"List of users"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query");if(s?.includes("identities.profileData.email")){const d=s.split("=")[1],f=(await t.env.data.users.list(t.var.tenant_id,{page:e,per_page:n,include_totals:r,q:`email:${d}`})).users.filter(w=>w.linked_to),[g]=f;if(!g)return t.json([]);const _=await t.env.data.users.get(t.var.tenant_id,g.linked_to);if(!_)throw new v(500,{message:"Primary account not found"});return t.json([Ft.parse(_)])}const a=["-_exists_:linked_to"];s&&a.push(s);const c=await t.env.data.users.list(t.var.tenant_id,{page:e,per_page:n,include_totals:r,sort:Ke(i),q:a.join(" ")}),l=c.users.filter(d=>!d.linked_to);return r?t.json(rh.parse({users:l,length:c.length,start:c.start,limit:c.limit})):t.json(o.z.array(Ft).parse(l))}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ft}},description:"List of users"}}}),async t=>{const{user_id:e}=t.req.valid("param"),n=await t.env.data.users.get(t.var.tenant_id,e);if(!n)throw new v(404);if(n.linked_to)throw new v(404,{message:"User is linked to another user"});return t.json(n)}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{user_id:e}=t.req.valid("param");if(!await t.env.data.users.remove(t.var.tenant_id,e))throw new v(404);return await ie(t,t.var.tenant_id,{type:te.SUCCESS_API_OPERATION,description:"Delete a User",response:{statusCode:204,body:{}}}),t.text("OK")}).openapi(o.createRoute({tags:["users"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object({...Fs.shape,password:o.z.string().optional()})}}}},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Ft}},description:"Status"}}}),async t=>{const e=t.req.valid("json");t.set("body",e);const{email:n,phone_number:r,name:i,linked_to:s,email_verified:a,provider:c,connection:l,password:d}=e,u=await t.env.data.connections.get(t.var.tenant_id,l),f=u?N3(u):c||l,g=e.user_id,_=g?gs(g):Xa(),w=`${f}|${_}`;try{const k={email:n,user_id:w,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()},z=await t.env.data.users.create(t.var.tenant_id,k);if(d){const I={user_id:w,password:await Pn.hash(d,10),algorithm:"bcrypt",is_current:!0};await t.env.data.passwords.create(t.var.tenant_id,I)}t.set("user_id",z.user_id),await ie(t,t.var.tenant_id,{type:te.SUCCESS_API_OPERATION,description:"User created"});const N=z.identities?z:{...z,identities:[{connection:z.connection,provider:z.provider,user_id:gs(z.user_id),isSocial:z.is_social}]};return t.json(Ft.parse(N),{status:201})}catch(k){throw k.message==="User already exists"?new v(409,{message:"User already exists"}):k}}).openapi(o.createRoute({tags:["users"],method:"patch",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object({...Fs.shape,verify_email:o.z.boolean(),password:o.z.string()}).partial()}}},params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{data:e}=t.env,n=t.req.valid("json"),{user_id:r}=t.req.valid("param"),{verify_email:i,password:s,connection:a,...c}=n,l=await e.users.get(t.var.tenant_id,r);if(!l)throw new v(404);if(l.linked_to)throw new v(404,{message:"User is linked to another user"});let d=r,u=l;if(a)if(l.connection===a)d=r,u=l;else{const _=(await e.users.list(t.var.tenant_id,{page:0,per_page:100,include_totals:!1,q:`linked_to:${r}`})).users.find(w=>w.connection===a);if(!_)throw new v(404,{message:`No identity found with connection: ${a}`});d=_.user_id,u=_}if(c.email&&c.email!==u.email){const g=await Ru(t.env.data.users,t.var.tenant_id,c.email);if(g.length&&g.some(_=>_.user_id!==d))throw new v(409,{message:"Another user with the same email address already exists."})}if(await t.env.data.users.update(t.var.tenant_id,d,c),s){let g;if(a)if(a==="Username-Password-Authentication")g={provider:u.provider,user_id:gs(d)};else throw new v(400,{message:`Cannot set password for connection: ${a}`});else if(g=l.identities?.find(k=>k.connection==="Username-Password-Authentication"),!g)throw new v(400,{message:"User does not have a password identity"});const _=`${g.provider}|${g.user_id}`,w=await e.passwords.get(t.var.tenant_id,_);w&&await e.passwords.update(t.var.tenant_id,{id:w.id,user_id:_,password:w.password,algorithm:w.algorithm,is_current:!1}),await e.passwords.create(t.var.tenant_id,{user_id:_,password:await Pn.hash(s,10),algorithm:"bcrypt",is_current:!0})}const f=await t.env.data.users.get(t.var.tenant_id,r);if(!f)throw new v(500);return await ie(t,t.var.tenant_id,{type:te.SUCCESS_API_OPERATION,description:"Update a User",body:n,response:{statusCode:200,body:f}}),t.json(f)}).openapi(o.createRoute({tags:["users"],method:"post",path:"/{user_id}/identities",request:{headers:o.z.object({"tenant-id":o.z.string()}),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(o.z.object({connection:o.z.string(),provider:o.z.string(),user_id:o.z.string(),isSocial:o.z.boolean()}))}},description:"Status"}}}),async t=>{const e=t.req.valid("json"),{user_id:n}=t.req.valid("param"),r="link_with"in e?e.link_with:e.user_id,i=await t.env.data.users.get(t.var.tenant_id,n);if(!i)throw new v(400,{message:"Linking an inexistent identity is not allowed."});await t.env.data.users.update(t.var.tenant_id,r,{linked_to:n});const s=await t.env.data.users.list(t.var.tenant_id,{page:0,per_page:10,include_totals:!1,q:`linked_to:${n}`}),a=[i,...s.users].map(c=>({connection:c.connection,provider:c.provider,user_id:gs(c.user_id),isSocial:c.is_social}));return t.json(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()}),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(Ft)}},description:"Status"}}}),async t=>{const{user_id:e,provider:n,linked_user_id:r}=t.req.valid("param");await t.env.data.users.unlink(t.var.tenant_id,e,n,r);const i=await t.env.data.users.get(t.var.tenant_id,e);if(!i)throw new v(404);return t.json([Ft.parse(i)])}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/sessions",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Ja),I3])}},description:"List of sessions"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{include_totals:n,page:r,per_page:i}=t.req.valid("query"),s=await t.env.data.sessions.list(t.var.tenant_id,{page:r,per_page:i,include_totals:n,q:`user_id:${e}`});return n?t.json(s):t.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()}),query:Te},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Tm}},description:"User permissions"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{page:n,per_page:r,sort:i,q:s}=t.req.valid("query");if(!await t.env.data.users.get(t.var.tenant_id,e))throw new v(404,{message:"User not found"});const c=await t.env.data.userPermissions.list(t.var.tenant_id,e,{page:n,per_page:r,include_totals:!1,sort:Ke(i),q:s});return t.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()}),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:["auth:write"]}],responses:{201:{description:"Permissions assigned to user"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{permissions:n}=t.req.valid("json");if(!await t.env.data.users.get(t.var.tenant_id,e))throw new v(404,{message:"User not found"});for(const i of n)if(!await t.env.data.userPermissions.create(t.var.tenant_id,e,{user_id:e,resource_server_identifier:i.resource_server_identifier,permission_name:i.permission_name}))throw new v(500,{message:"Failed to assign permissions to user"});return t.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()}),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:["auth:write"]}],responses:{200:{description:"Permissions removed from user"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{permissions:n}=t.req.valid("json");if(!await t.env.data.users.get(t.var.tenant_id,e))throw new v(404,{message:"User not found"});for(const i of n)if(!await t.env.data.userPermissions.remove(t.var.tenant_id,e,i))throw new v(500,{message:"Failed to remove permissions from user"});return t.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:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Zs}},description:"User roles"}}}),async t=>{const{user_id:e}=t.req.valid("param");if(!await t.env.data.users.get(t.var.tenant_id,e))throw new v(404,{message:"User not found"});const r=await t.env.data.userRoles.list(t.var.tenant_id,e,void 0,"");return t.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:["auth:write"]}],responses:{201:{description:"Roles assigned to user"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{roles:n}=t.req.valid("json");if(!await t.env.data.users.get(t.var.tenant_id,e))throw new v(404,{message:"User not found"});for(const i of n)if(!await t.env.data.userRoles.create(t.var.tenant_id,e,i,""))throw new v(500,{message:"Failed to assign roles to user"});return t.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:["auth:write"]}],responses:{200:{description:"Roles removed from user"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{roles:n}=t.req.valid("json");if(!await t.env.data.users.get(t.var.tenant_id,e))throw new v(404,{message:"User not found"});for(const i of n)if(!await t.env.data.userRoles.remove(t.var.tenant_id,e,i,""))throw new v(500,{message:"Failed to remove roles from user"});return t.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:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([j3,o.z.array(zn)])}},description:"List of user organizations"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{page:n,per_page:r,include_totals:i,sort:s}=t.req.valid("query");if(!await t.env.data.users.get(t.var.tenant_id,e))throw new v(404,{message:"User not found"});const c=await t.env.data.userOrganizations.listUserOrganizations(t.var.tenant_id,e,{page:n,per_page:r,sort:Ke(s)});return i?t.json({organizations:c.organizations,start:c.start,limit:c.limit,length:c.length}):t.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()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"User removed from organization successfully"}}}),async t=>{const{user_id:e,organization_id:n}=t.req.valid("param");if(!await t.env.data.users.get(t.var.tenant_id,e))throw new v(404,{message:"User not found"});const s=(await t.env.data.userOrganizations.list(t.var.tenant_id,{q:`user_id:${e}`,per_page:100})).userOrganizations.find(a=>a.organization_id===n);if(!s)throw new v(404,{message:"User is not a member of this organization"});return await t.env.data.userOrganizations.remove(t.var.tenant_id,s.id),t.json({message:"User removed from organization successfully"})});var ih=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function O3(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var oh={};var sh;function T3(){if(sh)return oh;sh=1;var t;return(function(e){(function(n){var r=typeof globalThis=="object"?globalThis:typeof ih=="object"?ih:typeof self=="object"?self:typeof this=="object"?this:l(),i=s(e);typeof r.Reflect<"u"&&(i=s(r.Reflect,i)),n(i,r),typeof r.Reflect>"u"&&(r.Reflect=e);function s(d,u){return function(f,g){Object.defineProperty(d,f,{configurable:!0,writable:!0,value:g}),u&&u(f,g)}}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",d={__proto__:[]}instanceof Array,u=!l&&!d,f={create:l?function(){return al(Object.create(null))}:d?function(){return al({__proto__:null})}:function(){return al({})},has:u?function($,x){return i.call($,x)}:function($,x){return x in $},get:u?function($,x){return i.call($,x)?$[x]:void 0}:function($,x){return $[x]}},g=Object.getPrototypeOf(Function),_=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Aw(),w=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Ew(),k=typeof WeakMap=="function"?WeakMap:Cw(),z=s?Symbol.for("@reflect-metadata:registry"):void 0,N=xw(),I=Sw(N);function S($,x,A,R){if(K(A)){if(!tf($))throw new TypeError;if(!nf(x))throw new TypeError;return $e($,x)}else{if(!tf($))throw new TypeError;if(!ne(x))throw new TypeError;if(!ne(R)&&!K(R)&&!vt(R))throw new TypeError;return vt(R)&&(R=void 0),A=Dt(A),be($,x,A,R)}}n("decorate",S);function E($,x){function A(R,J){if(!ne(R))throw new TypeError;if(!K(J)&&!$w(J))throw new TypeError;Ut($,x,R,J)}return A}n("metadata",E);function P($,x,A,R){if(!ne(A))throw new TypeError;return K(R)||(R=Dt(R)),Ut($,x,A,R)}n("defineMetadata",P);function G($,x,A){if(!ne(x))throw new TypeError;return K(A)||(A=Dt(A)),sn($,x,A)}n("hasMetadata",G);function Z($,x,A){if(!ne(x))throw new TypeError;return K(A)||(A=Dt(A)),Be($,x,A)}n("hasOwnMetadata",Z);function W($,x,A){if(!ne(x))throw new TypeError;return K(A)||(A=Dt(A)),Qe($,x,A)}n("getMetadata",W);function M($,x,A){if(!ne(x))throw new TypeError;return K(A)||(A=Dt(A)),Lt($,x,A)}n("getOwnMetadata",M);function ce($,x){if(!ne($))throw new TypeError;return K(x)||(x=Dt(x)),Hn($,x)}n("getMetadataKeys",ce);function le($,x){if(!ne($))throw new TypeError;return K(x)||(x=Dt(x)),Pe($,x)}n("getOwnMetadataKeys",le);function fe($,x,A){if(!ne(x))throw new TypeError;if(K(A)||(A=Dt(A)),!ne(x))throw new TypeError;K(A)||(A=Dt(A));var R=Ei(x,A,!1);return K(R)?!1:R.OrdinaryDeleteMetadata($,x,A)}n("deleteMetadata",fe);function $e($,x){for(var A=$.length-1;A>=0;--A){var R=$[A],J=R(x);if(!K(J)&&!vt(J)){if(!nf(J))throw new TypeError;x=J}}return x}function be($,x,A,R){for(var J=$.length-1;J>=0;--J){var ze=$[J],Ie=ze(x,A,R);if(!K(Ie)&&!vt(Ie)){if(!ne(Ie))throw new TypeError;R=Ie}}return R}function sn($,x,A){var R=Be($,x,A);if(R)return!0;var J=sl(x);return vt(J)?!1:sn($,J,A)}function Be($,x,A){var R=Ei(x,A,!1);return K(R)?!1:ef(R.OrdinaryHasOwnMetadata($,x,A))}function Qe($,x,A){var R=Be($,x,A);if(R)return Lt($,x,A);var J=sl(x);if(!vt(J))return Qe($,J,A)}function Lt($,x,A){var R=Ei(x,A,!1);if(!K(R))return R.OrdinaryGetOwnMetadata($,x,A)}function Ut($,x,A,R){var J=Ei(A,R,!0);J.OrdinaryDefineOwnMetadata($,x,A,R)}function Hn($,x){var A=Pe($,x),R=sl($);if(R===null)return A;var J=Hn(R,x);if(J.length<=0)return A;if(A.length<=0)return J;for(var ze=new w,Ie=[],oe=0,L=A;oe<L.length;oe++){var q=L[oe],H=ze.has(q);H||(ze.add(q),Ie.push(q))}for(var V=0,se=J;V<se.length;V++){var q=se[V],H=ze.has(q);H||(ze.add(q),Ie.push(q))}return Ie}function Pe($,x){var A=Ei($,x,!1);return A?A.OrdinaryOwnMetadataKeys($,x):[]}function et($){if($===null)return 1;switch(typeof $){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return $===null?1:6;default:return 6}}function K($){return $===void 0}function vt($){return $===null}function il($){return typeof $=="symbol"}function ne($){return typeof $=="object"?$!==null:typeof $=="function"}function Vn($,x){switch(et($)){case 0:return $;case 1:return $;case 2:return $;case 3:return $;case 4:return $;case 5:return $}var A="string",R=rf($,a);if(R!==void 0){var J=R.call($,A);if(ne(J))throw new TypeError;return J}return bw($)}function bw($,x){var A,R,J;{var ze=$.toString;if(fs(ze)){var R=ze.call($);if(!ne(R))return R}var A=$.valueOf;if(fs(A)){var R=A.call($);if(!ne(R))return R}}throw new TypeError}function ef($){return!!$}function vw($){return""+$}function Dt($){var x=Vn($);return il(x)?x:vw(x)}function tf($){return Array.isArray?Array.isArray($):$ instanceof Object?$ instanceof Array:Object.prototype.toString.call($)==="[object Array]"}function fs($){return typeof $=="function"}function nf($){return typeof $=="function"}function $w($){switch(et($)){case 3:return!0;case 4:return!0;default:return!1}}function ol($,x){return $===x||$!==$&&x!==x}function rf($,x){var A=$[x];if(A!=null){if(!fs(A))throw new TypeError;return A}}function of($){var x=rf($,c);if(!fs(x))throw new TypeError;var A=x.call($);if(!ne(A))throw new TypeError;return A}function sf($){return $.value}function af($){var x=$.next();return x.done?!1:x}function cf($){var x=$.return;x&&x.call($)}function sl($){var x=Object.getPrototypeOf($);if(typeof $!="function"||$===g||x!==g)return x;var A=$.prototype,R=A&&Object.getPrototypeOf(A);if(R==null||R===Object.prototype)return x;var J=R.constructor;return typeof J!="function"||J===$?x:J}function kw(){var $;!K(z)&&typeof r.Reflect<"u"&&!(z in r.Reflect)&&typeof r.Reflect.defineMetadata=="function"&&($=zw(r.Reflect));var x,A,R,J=new k,ze={registerProvider:Ie,getProvider:L,setProvider:H};return ze;function Ie(V){if(!Object.isExtensible(ze))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case $===V:break;case K(x):x=V;break;case x===V:break;case K(A):A=V;break;case A===V:break;default:R===void 0&&(R=new w),R.add(V);break}}function oe(V,se){if(!K(x)){if(x.isProviderFor(V,se))return x;if(!K(A)){if(A.isProviderFor(V,se))return x;if(!K(R))for(var ge=of(R);;){var Ae=af(ge);if(!Ae)return;var $t=sf(Ae);if($t.isProviderFor(V,se))return cf(ge),$t}}}if(!K($)&&$.isProviderFor(V,se))return $}function L(V,se){var ge=J.get(V),Ae;return K(ge)||(Ae=ge.get(se)),K(Ae)&&(Ae=oe(V,se),K(Ae)||(K(ge)&&(ge=new _,J.set(V,ge)),ge.set(se,Ae))),Ae}function q(V){if(K(V))throw new TypeError;return x===V||A===V||!K(R)&&R.has(V)}function H(V,se,ge){if(!q(ge))throw new Error("Metadata provider not registered.");var Ae=L(V,se);if(Ae!==ge){if(!K(Ae))return!1;var $t=J.get(V);K($t)&&($t=new _,J.set(V,$t)),$t.set(se,ge)}return!0}}function xw(){var $;return!K(z)&&ne(r.Reflect)&&Object.isExtensible(r.Reflect)&&($=r.Reflect[z]),K($)&&($=kw()),!K(z)&&ne(r.Reflect)&&Object.isExtensible(r.Reflect)&&Object.defineProperty(r.Reflect,z,{enumerable:!1,configurable:!1,writable:!1,value:$}),$}function Sw($){var x=new k,A={isProviderFor:function(q,H){var V=x.get(q);return K(V)?!1:V.has(H)},OrdinaryDefineOwnMetadata:Ie,OrdinaryHasOwnMetadata:J,OrdinaryGetOwnMetadata:ze,OrdinaryOwnMetadataKeys:oe,OrdinaryDeleteMetadata:L};return N.registerProvider(A),A;function R(q,H,V){var se=x.get(q),ge=!1;if(K(se)){if(!V)return;se=new _,x.set(q,se),ge=!0}var Ae=se.get(H);if(K(Ae)){if(!V)return;if(Ae=new _,se.set(H,Ae),!$.setProvider(q,H,A))throw se.delete(H),ge&&x.delete(q),new Error("Wrong provider for target.")}return Ae}function J(q,H,V){var se=R(H,V,!1);return K(se)?!1:ef(se.has(q))}function ze(q,H,V){var se=R(H,V,!1);if(!K(se))return se.get(q)}function Ie(q,H,V,se){var ge=R(V,se,!0);ge.set(q,H)}function oe(q,H){var V=[],se=R(q,H,!1);if(K(se))return V;for(var ge=se.keys(),Ae=of(ge),$t=0;;){var lf=af(Ae);if(!lf)return V.length=$t,V;var Nw=sf(lf);try{V[$t]=Nw}catch(Iw){try{cf(Ae)}finally{throw Iw}}$t++}}function L(q,H,V){var se=R(H,V,!1);if(K(se)||!se.delete(q))return!1;if(se.size===0){var ge=x.get(H);K(ge)||(ge.delete(V),ge.size===0&&x.delete(ge))}return!0}}function zw($){var x=$.defineMetadata,A=$.hasOwnMetadata,R=$.getOwnMetadata,J=$.getOwnMetadataKeys,ze=$.deleteMetadata,Ie=new k,oe={isProviderFor:function(L,q){var H=Ie.get(L);return!K(H)&&H.has(q)?!0:J(L,q).length?(K(H)&&(H=new w,Ie.set(L,H)),H.add(q),!0):!1},OrdinaryDefineOwnMetadata:x,OrdinaryHasOwnMetadata:A,OrdinaryGetOwnMetadata:R,OrdinaryOwnMetadataKeys:J,OrdinaryDeleteMetadata:ze};return oe}function Ei($,x,A){var R=N.getProvider($,x);if(!K(R))return R;if(A){if(N.setProvider($,x,I))return I;throw new Error("Illegal state.")}}function Aw(){var $={},x=[],A=(function(){function oe(L,q,H){this._index=0,this._keys=L,this._values=q,this._selector=H}return oe.prototype["@@iterator"]=function(){return this},oe.prototype[c]=function(){return this},oe.prototype.next=function(){var L=this._index;if(L>=0&&L<this._keys.length){var q=this._selector(this._keys[L],this._values[L]);return L+1>=this._keys.length?(this._index=-1,this._keys=x,this._values=x):this._index++,{value:q,done:!1}}return{value:void 0,done:!0}},oe.prototype.throw=function(L){throw this._index>=0&&(this._index=-1,this._keys=x,this._values=x),L},oe.prototype.return=function(L){return this._index>=0&&(this._index=-1,this._keys=x,this._values=x),{value:L,done:!0}},oe})(),R=(function(){function oe(){this._keys=[],this._values=[],this._cacheKey=$,this._cacheIndex=-2}return Object.defineProperty(oe.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),oe.prototype.has=function(L){return this._find(L,!1)>=0},oe.prototype.get=function(L){var q=this._find(L,!1);return q>=0?this._values[q]:void 0},oe.prototype.set=function(L,q){var H=this._find(L,!0);return this._values[H]=q,this},oe.prototype.delete=function(L){var q=this._find(L,!1);if(q>=0){for(var H=this._keys.length,V=q+1;V<H;V++)this._keys[V-1]=this._keys[V],this._values[V-1]=this._values[V];return this._keys.length--,this._values.length--,ol(L,this._cacheKey)&&(this._cacheKey=$,this._cacheIndex=-2),!0}return!1},oe.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=$,this._cacheIndex=-2},oe.prototype.keys=function(){return new A(this._keys,this._values,J)},oe.prototype.values=function(){return new A(this._keys,this._values,ze)},oe.prototype.entries=function(){return new A(this._keys,this._values,Ie)},oe.prototype["@@iterator"]=function(){return this.entries()},oe.prototype[c]=function(){return this.entries()},oe.prototype._find=function(L,q){if(!ol(this._cacheKey,L)){this._cacheIndex=-1;for(var H=0;H<this._keys.length;H++)if(ol(this._keys[H],L)){this._cacheIndex=H;break}}return this._cacheIndex<0&&q&&(this._cacheIndex=this._keys.length,this._keys.push(L),this._values.push(void 0)),this._cacheIndex},oe})();return R;function J(oe,L){return oe}function ze(oe,L){return L}function Ie(oe,L){return[oe,L]}}function Ew(){var $=(function(){function x(){this._map=new _}return Object.defineProperty(x.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),x.prototype.has=function(A){return this._map.has(A)},x.prototype.add=function(A){return this._map.set(A,A),this},x.prototype.delete=function(A){return this._map.delete(A)},x.prototype.clear=function(){this._map.clear()},x.prototype.keys=function(){return this._map.keys()},x.prototype.values=function(){return this._map.keys()},x.prototype.entries=function(){return this._map.entries()},x.prototype["@@iterator"]=function(){return this.keys()},x.prototype[c]=function(){return this.keys()},x})();return $}function Cw(){var $=16,x=f.create(),A=R();return(function(){function L(){this._key=R()}return L.prototype.has=function(q){var H=J(q,!1);return H!==void 0?f.has(H,this._key):!1},L.prototype.get=function(q){var H=J(q,!1);return H!==void 0?f.get(H,this._key):void 0},L.prototype.set=function(q,H){var V=J(q,!0);return V[this._key]=H,this},L.prototype.delete=function(q){var H=J(q,!1);return H!==void 0?delete H[this._key]:!1},L.prototype.clear=function(){this._key=R()},L})();function R(){var L;do L="@@WeakMap@@"+oe();while(f.has(x,L));return x[L]=!0,L}function J(L,q){if(!i.call(L,A)){if(!q)return;Object.defineProperty(L,A,{value:f.create()})}return L[A]}function ze(L,q){for(var H=0;H<q;++H)L[H]=Math.random()*255|0;return L}function Ie(L){if(typeof Uint8Array=="function"){var q=new Uint8Array(L);return typeof crypto<"u"?crypto.getRandomValues(q):typeof msCrypto<"u"?msCrypto.getRandomValues(q):ze(q,L),q}return ze(new Array(L),L)}function oe(){var L=Ie($);L[6]=L[6]&79|64,L[8]=L[8]&191|128;for(var q="",H=0;H<$;++H){var V=L[H];(H===4||H===6||H===8)&&(q+="-"),V<16&&(q+="0"),q+=V.toString(16).toLowerCase()}return q}}function al($){return $.__=void 0,delete $.__,$}})})(t||(t={})),oh}T3();const R3="[object ArrayBuffer]";class T{static isArrayBuffer(e){return Object.prototype.toString.call(e)===R3}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,n){if(e.constructor===n)return e;if(this.isArrayBuffer(e))return new n(e);if(this.isArrayBufferView(e))return new n(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,n){const r=T.toUint8Array(e),i=T.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(...e){let n;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?n=e[0]:e[e.length-1]instanceof Function?n=e.slice(0,e.length-1):n=e;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 e[e.length-1]instanceof Function?this.toView(i,e[e.length-1]):i.buffer}}const pl="string",B3=/^[0-9a-f\s]+$/i,L3=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,U3=/^[a-zA-Z0-9-_]+$/;class ah{static fromString(e){const n=unescape(encodeURIComponent(e)),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r.buffer}static toString(e){const n=T.toUint8Array(e);let r="";for(let s=0;s<n.length;s++)r+=String.fromCharCode(n[s]);return decodeURIComponent(escape(r))}}class qt{static toString(e,n=!1){const r=T.toArrayBuffer(e),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(e,n=!1){const r=new ArrayBuffer(e.length*2),i=new DataView(r);for(let s=0;s<e.length;s++)i.setUint16(s*2,e.charCodeAt(s),n);return r}}class F{static isHex(e){return typeof e===pl&&B3.test(e)}static isBase64(e){return typeof e===pl&&L3.test(e)}static isBase64Url(e){return typeof e===pl&&U3.test(e)}static ToString(e,n="utf8"){const r=T.toUint8Array(e);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 qt.toString(r,!0);case"utf16":case"utf16be":return qt.toString(r);default:throw new Error(`Unknown type of encoding '${n}'`)}}static FromString(e,n="utf8"){if(!e)return new ArrayBuffer(0);switch(n.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return qt.fromString(e,!0);case"utf16":case"utf16be":return qt.fromString(e);default:throw new Error(`Unknown type of encoding '${n}'`)}}static ToBase64(e){const n=T.toUint8Array(e);if(typeof btoa<"u"){const r=this.ToString(n,"binary");return btoa(r)}else return Buffer.from(n).toString("base64")}static FromBase64(e){const n=this.formatString(e);if(!n)return new ArrayBuffer(0);if(!F.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(e){const n=this.formatString(e);if(!n)return new ArrayBuffer(0);if(!F.isBase64Url(n))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(n.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,n=F.DEFAULT_UTF8_ENCODING){switch(n){case"ascii":return this.FromBinary(e);case"utf8":return ah.fromString(e);case"utf16":case"utf16be":return qt.fromString(e);case"utf16le":case"usc2":return qt.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${n}'`)}}static ToUtf8String(e,n=F.DEFAULT_UTF8_ENCODING){switch(n){case"ascii":return this.ToBinary(e);case"utf8":return ah.toString(e);case"utf16":case"utf16be":return qt.toString(e);case"utf16le":case"usc2":return qt.toString(e,!0);default:throw new Error(`Unknown type of encoding '${n}'`)}}static FromBinary(e){const n=e.length,r=new Uint8Array(n);for(let i=0;i<n;i++)r[i]=e.charCodeAt(i);return r.buffer}static ToBinary(e){const n=T.toUint8Array(e);let r="";for(let i=0;i<n.length;i++)r+=String.fromCharCode(n[i]);return r}static ToHex(e){const n=T.toUint8Array(e);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(e){let n=this.formatString(e);if(!n)return new ArrayBuffer(0);if(!F.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(e,n=!1){return qt.toString(e,n)}static FromUtf16String(e,n=!1){return qt.fromString(e,n)}static Base64Padding(e){const n=4-e.length%4;if(n<4)for(let r=0;r<n;r++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}}F.DEFAULT_UTF8_ENCODING="utf8";function D3(...t){const e=t.map(i=>i.byteLength).reduce((i,s)=>i+s),n=new Uint8Array(e);let r=0;return t.map(i=>new Uint8Array(i)).forEach(i=>{for(const s of i)n[r++]=s}),n.buffer}function P_(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;const n=new Uint8Array(t),r=new Uint8Array(e);for(let i=0;i<t.byteLength;i++)if(n[i]!==r[i])return!1;return!0}function Yr(t,e){let n=0;if(t.length===1)return t[0];for(let r=t.length-1;r>=0;r--)n+=t[t.length-1-r]*Math.pow(2,e*r);return n}function cr(t,e,n=-1){const r=n;let i=t,s=0,a=Math.pow(2,e);for(let c=1;c<8;c++){if(t<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 d=new Uint8Array(l);for(let u=c-1;u>=0;u--){const f=Math.pow(2,u*e);d[s-u-1]=Math.floor(i/f),i-=d[s-u-1]*f}return l}a*=Math.pow(2,e)}return new ArrayBuffer(0)}function Jl(...t){let e=0,n=0;for(const s of t)e+=s.length;const r=new ArrayBuffer(e),i=new Uint8Array(r);for(const s of t)i.set(s,n),n+=s.length;return i}function O_(){const t=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const c=t[0]===255&&t[1]&128,l=t[0]===0&&(t[1]&128)===0;(c||l)&&this.warnings.push("Needlessly long format")}const e=new ArrayBuffer(this.valueHex.byteLength),n=new Uint8Array(e);for(let c=0;c<this.valueHex.byteLength;c++)n[c]=0;n[0]=t[0]&128;const r=Yr(n,8),i=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(i);for(let c=0;c<this.valueHex.byteLength;c++)s[c]=t[c];return s[0]&=127,Yr(s,8)-r}function M3(t){const e=t<0?t*-1:t;let n=128;for(let r=1;r<8;r++){if(e<=n){if(t<0){const a=n-e,c=cr(a,8,r),l=new Uint8Array(c);return l[0]|=128,c}let i=cr(e,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 q3(t,e){if(t.byteLength!==e.byteLength)return!1;const n=new Uint8Array(t),r=new Uint8Array(e);for(let i=0;i<n.length;i++)if(n[i]!==r[i])return!1;return!0}function at(t,e){const n=t.toString(10);if(e<n.length)return"";const r=e-n.length,i=new Array(r);for(let a=0;a<r;a++)i[a]="0";return i.join("").concat(n)}function sa(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Hu(t){let e=0,n=0;for(let i=0;i<t.length;i++){const s=t[i];e+=s.byteLength}const r=new Uint8Array(e);for(let i=0;i<t.length;i++){const s=t[i];r.set(new Uint8Array(s),n),n+=s.byteLength}return r.buffer}function yn(t,e,n,r){return e instanceof Uint8Array?e.byteLength?n<0?(t.error="Wrong parameter: inputOffset less than zero",!1):r<0?(t.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-n-r<0?(t.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(t.error="Wrong parameter: inputBuffer has zero length",!1):(t.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class oc{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Hu(this.items)}}const Ii=[new Uint8Array([1])],ch="0123456789",fl="name",lh="valueHexView",F3="isHexOnly",H3="idBlock",V3="tagClass",K3="tagNumber",G3="isConstructed",W3="fromBER",J3="toBER",X3="local",nt="",Xt=new ArrayBuffer(0),sc=new Uint8Array(0),$o="EndOfContent",T_="OCTET STRING",R_="BIT STRING";function Zt(t){var e;return e=class extends t{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?T.toUint8Array(s.valueHex):sc}fromBER(r,i,s){const a=r instanceof ArrayBuffer?new Uint8Array(r):r;if(!yn(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",Xt)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:F.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}class xr{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:n=nt,warnings:r=[],valueBeforeDecode:i=sc}={}){this.blockLength=e,this.error=n,this.warnings=r,this.valueBeforeDecodeView=T.toUint8Array(i)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:F.ToHex(this.valueBeforeDecodeView)}}}xr.NAME="baseBlock";class Ye extends xr{fromBER(e,n,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}Ye.NAME="valueBlock";class B_ extends Zt(xr){constructor({idBlock:e={}}={}){var n,r,i,s;super(),e?(this.isHexOnly=(n=e.isHexOnly)!==null&&n!==void 0?n:!1,this.valueHexView=e.valueHex?T.toUint8Array(e.valueHex):sc,this.tagClass=(r=e.tagClass)!==null&&r!==void 0?r:-1,this.tagNumber=(i=e.tagNumber)!==null&&i!==void 0?i:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!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",Xt}if(this.isConstructed&&(n|=32),this.tagNumber<31&&!this.isHexOnly){const i=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,n|=s,i[0]=n}return i.buffer}if(!this.isHexOnly){const i=cr(this.tagNumber,7),s=new Uint8Array(i),a=i.byteLength,c=new Uint8Array(a+1);if(c[0]=n|31,!e){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,!e){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(e,n,r){const i=T.toUint8Array(e);if(!yn(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,d=this.valueHexView=new Uint8Array(255),u=255;for(;s[l]&128;){if(d[l-1]=s[l]&127,l++,l>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(l===u){u+=255;const g=new Uint8Array(u);for(let _=0;_<d.length;_++)g[_]=d[_];d=this.valueHexView=new Uint8Array(u)}}this.blockLength=l+1,d[l-1]=s[l]&127;const f=new Uint8Array(l);for(let g=0;g<l;g++)f[g]=d[g];d=this.valueHexView=new Uint8Array(l),d.set(f),this.blockLength<=9?this.tagNumber=Yr(d,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}}}B_.NAME="identificationBlock";class L_ extends xr{constructor({lenBlock:e={}}={}){var n,r,i;super(),this.isIndefiniteForm=(n=e.isIndefiniteForm)!==null&&n!==void 0?n:!1,this.longFormUsed=(r=e.longFormUsed)!==null&&r!==void 0?r:!1,this.length=(i=e.length)!==null&&i!==void 0?i:0}fromBER(e,n,r){const i=T.toUint8Array(e);if(!yn(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=Yr(l,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=a+1,n+this.blockLength}toBER(e=!1){let n,r;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return n=new ArrayBuffer(1),e===!1&&(r=new Uint8Array(n),r[0]=128),n;if(this.longFormUsed){const i=cr(this.length,8);if(i.byteLength>127)return this.error="Too big length",Xt;if(n=new ArrayBuffer(i.byteLength+1),e)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),e===!1&&(r=new Uint8Array(n),r[0]=this.length),n}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}L_.NAME="lengthBlock";const D={};class Me extends xr{constructor({name:e=nt,optional:n=!1,primitiveSchema:r,...i}={},s){super(i),this.name=e,this.optional=n,r&&(this.primitiveSchema=r),this.idBlock=new B_(i),this.lenBlock=new L_(i),this.valueBlock=s?new s(i):new Ye(i)}fromBER(e,n,r){const i=this.valueBlock.fromBER(e,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(e,n){const r=n||new oc;n||U_(this);const i=this.idBlock.toBER(e);if(r.write(i),this.lenBlock.isIndefiniteForm)r.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,r),r.write(new ArrayBuffer(2));else{const s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;const a=this.lenBlock.toBER(e);r.write(a),r.write(s)}return n?Xt:r.final()}toJSON(){const e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():F.ToHex(this.toBER())}onAsciiEncoding(){const e=this.constructor.NAME,n=F.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${n}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;const n=this.toBER(),r=e.toBER();return q3(n,r)}}Me.NAME="BaseBlock";function U_(t){var e;if(t instanceof D.Constructed)for(const n of t.valueBlock.value)U_(n)&&(t.lenBlock.isIndefiniteForm=!0);return!!(!((e=t.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}class Vu extends Me{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=nt,...n}={},r){super(n,r),e&&this.fromString(e)}fromBER(e,n,r){const i=this.valueBlock.fromBER(e,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}'`}}Vu.NAME="BaseStringBlock";class D_ extends Zt(Ye){constructor({isHexOnly:e=!0,...n}={}){super(n),this.isHexOnly=e}}D_.NAME="PrimitiveValueBlock";var M_;class Ko extends Me{constructor(e={}){super(e,D_),this.idBlock.isConstructed=!1}}M_=Ko;D.Primitive=M_;Ko.NAME="PRIMITIVE";function Z3(t,e){if(t instanceof e)return t;const n=new e;return n.idBlock=t.idBlock,n.lenBlock=t.lenBlock,n.warnings=t.warnings,n.valueBeforeDecodeView=t.valueBeforeDecodeView,n}function mi(t,e=0,n=t.length){const r=e;let i=new Me({},Ye);const s=new xr;if(!yn(s,t,e,n))return i.error=s.error,{offset:-1,result:i};if(!t.subarray(e,e+n).length)return i.error="Zero buffer length",{offset:-1,result:i};let c=i.idBlock.fromBER(t,e,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(e=c,n-=i.idBlock.blockLength,c=i.lenBlock.fromBER(t,e,n),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),c===-1)return i.error=i.lenBlock.error,{offset:-1,result:i};if(e=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=Me;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=D.EndOfContent;break;case 1:l=D.Boolean;break;case 2:l=D.Integer;break;case 3:l=D.BitString;break;case 4:l=D.OctetString;break;case 5:l=D.Null;break;case 6:l=D.ObjectIdentifier;break;case 10:l=D.Enumerated;break;case 12:l=D.Utf8String;break;case 13:l=D.RelativeObjectIdentifier;break;case 14:l=D.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:l=D.Sequence;break;case 17:l=D.Set;break;case 18:l=D.NumericString;break;case 19:l=D.PrintableString;break;case 20:l=D.TeletexString;break;case 21:l=D.VideotexString;break;case 22:l=D.IA5String;break;case 23:l=D.UTCTime;break;case 24:l=D.GeneralizedTime;break;case 25:l=D.GraphicString;break;case 26:l=D.VisibleString;break;case 27:l=D.GeneralString;break;case 28:l=D.UniversalString;break;case 29:l=D.CharacterString;break;case 30:l=D.BmpString;break;case 31:l=D.DATE;break;case 32:l=D.TimeOfDay;break;case 33:l=D.DateTime;break;case 34:l=D.Duration;break;default:{const d=i.idBlock.isConstructed?new D.Constructed:new D.Primitive;d.idBlock=i.idBlock,d.lenBlock=i.lenBlock,d.warnings=i.warnings,i=d}}break;default:l=i.idBlock.isConstructed?D.Constructed:D.Primitive}return i=Z3(i,l),c=i.fromBER(t,e,i.lenBlock.isIndefiniteForm?n:i.lenBlock.length),i.valueBeforeDecodeView=t.subarray(r,r+i.blockLength),{offset:c,result:i}}function Hr(t){if(!t.byteLength){const e=new Me({},Ye);return e.error="Input buffer has zero length",{offset:-1,result:e}}return mi(T.toUint8Array(t).slice(),0,t.byteLength)}function Y3(t,e){return t?1:e}class In extends Ye{constructor({value:e=[],isIndefiniteForm:n=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=n}fromBER(e,n,r){const i=T.toUint8Array(e);if(!yn(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(;Y3(this.isIndefiniteForm,r)>0;){const a=mi(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===$o)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===$o?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,n){const r=n||new oc;for(let i=0;i<this.value.length;i++)this.value[i].toBER(e,r);return n?Xt:r.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const n of this.value)e.value.push(n.toJSON());return e}}In.NAME="ConstructedValueBlock";var q_;class Ze extends Me{constructor(e={}){super(e,In),this.idBlock.isConstructed=!0}fromBER(e,n,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const i=this.valueBlock.fromBER(e,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 e=[];for(const r of this.valueBlock.value)e.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 e.length?`${n} :
70
70
  ${e.join(`
71
- `)}`:`${n} :`}}q_=Ze;D.Constructed=q_;Ze.NAME="CONSTRUCTED";class F_ extends Ye{fromBER(e,n,r){return n}toBER(e){return Xt}}F_.override="EndOfContentValueBlock";var H_;class Ku extends Me{constructor(e={}){super(e,F_),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}H_=Ku;D.EndOfContent=H_;Ku.NAME=$o;var V_;class lr extends Me{constructor(e={}){super(e,Ye),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,n,r){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=r,n+r>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):n+r}toBER(e,n){const r=new ArrayBuffer(2);if(!e){const i=new Uint8Array(r);i[0]=5,i[1]=0}return n&&n.write(r),r}onAsciiEncoding(){return`${this.constructor.NAME}`}}V_=lr;D.Null=V_;lr.NAME="NULL";class K_ extends Zt(Ye){get value(){for(const e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...n}={}){super(n),n.valueHex?this.valueHexView=T.toUint8Array(n.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,n,r){const i=T.toUint8Array(e);return yn(this,i,n,r)?(this.valueHexView=i.subarray(n,n+r),r>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,O_.call(this),this.blockLength=r,n+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}K_.NAME="BooleanValueBlock";var G_;let ac=class extends Me{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,K_),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};G_=ac;D.Boolean=G_;ac.NAME="BOOLEAN";class W_ extends Zt(In){constructor({isConstructed:e=!1,...n}={}){super(n),this.isConstructed=e}fromBER(e,n,r){let i=0;if(this.isConstructed){if(this.isHexOnly=!1,i=In.prototype.fromBER.call(this,e,n,r),i===-1)return i;for(let s=0;s<this.value.length;s++){const a=this.value[s].constructor.NAME;if(a===$o){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==T_)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,i=super.fromBER(e,n,r),this.blockLength=r;return i}toBER(e,n){return this.isConstructed?In.prototype.toBER.call(this,e,n):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}W_.NAME="OctetStringValueBlock";var Gu;let rr=class extends Me{constructor({idBlock:e={},lenBlock:n={},...r}={}){var i,s;(i=r.isConstructed)!==null&&i!==void 0||(r.isConstructed=!!(!((s=r.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...n,isIndefiniteForm:!!r.isIndefiniteForm},...r},W_),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,n,r){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,r===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),n;if(!this.valueBlock.isConstructed){const s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(n,n+r);try{if(s.byteLength){const a=gi(s,0,s.byteLength);a.offset!==-1&&a.offset===r&&(this.valueBlock.value=[a.result])}}catch{}}return super.fromBER(e,n,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Ze.prototype.onAsciiEncoding.call(this);const e=this.constructor.NAME,n=F.ToHex(this.valueBlock.valueHexView);return`${e} : ${n}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;const e=[];for(const n of this.valueBlock.value)n instanceof Gu&&e.push(n.valueBlock.valueHexView);return T.concat(e)}};Gu=rr;D.OctetString=Gu;rr.NAME=T_;class J_ extends Zt(In){constructor({unusedBits:e=0,isConstructed:n=!1,...r}={}){super(r),this.unusedBits=e,this.isConstructed=n,this.blockLength=this.valueHexView.byteLength}fromBER(e,n,r){if(!r)return n;let i=-1;if(this.isConstructed){if(i=In.prototype.fromBER.call(this,e,n,r),i===-1)return i;for(const c of this.value){const l=c.constructor.NAME;if(l===$o){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(l!==R_)return this.error="BIT STRING may consists of BIT STRINGs only",-1;const d=c.valueBlock;if(this.unusedBits>0&&d.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=d.unusedBits}return i}const s=T.toUint8Array(e);if(!yn(this,s,n,r))return-1;const a=s.subarray(n,n+r);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const c=a.subarray(1);try{if(c.byteLength){const l=gi(c,0,c.byteLength);l.offset!==-1&&l.offset===r-1&&(this.value=[l.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,n+r}toBER(e,n){if(this.isConstructed)return In.prototype.toBER.call(this,e,n);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){const i=new Uint8Array(1);return i[0]=0,i.buffer}const r=new Uint8Array(this.valueHexView.length+1);return r[0]=this.unusedBits,r.set(this.valueHexView,1),r.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}J_.NAME="BitStringValueBlock";var X_;let ir=class extends Me{constructor({idBlock:e={},lenBlock:n={},...r}={}){var i,s;(i=r.isConstructed)!==null&&i!==void 0||(r.isConstructed=!!(!((s=r.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...n,isIndefiniteForm:!!r.isIndefiniteForm},...r},J_),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,n,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,n,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Ze.prototype.onAsciiEncoding.call(this);{const e=[],n=this.valueBlock.valueHexView;for(const a of n)e.push(a.toString(2).padStart(8,"0"));const r=e.join(""),i=this.constructor.NAME,s=r.substring(0,r.length-this.valueBlock.unusedBits);return`${i} : ${s}`}}};X_=ir;D.BitString=X_;ir.NAME=R_;var Z_;function Q3(t,e){const n=new Uint8Array([0]),r=new Uint8Array(t),i=new Uint8Array(e);let s=r.slice(0);const a=s.length-1,c=i.slice(0),l=c.length-1;let d=0;const u=l<a?a:l;let f=0;for(let g=u;g>=0;g--,f++)!0===f<c.length?d=s[a-f]+c[l-f]+n[0]:d=s[a-f]+n[0],n[0]=d/10,!0===f>=s.length?s=Jl(new Uint8Array([d%10]),s):s[a-f]=d%10;return n[0]>0&&(s=Jl(n,s)),s}function dh(t){if(t>=Ni.length)for(let e=Ni.length;e<=t;e++){const n=new Uint8Array([0]);let r=Ni[e-1].slice(0);for(let i=r.length-1;i>=0;i--){const s=new Uint8Array([(r[i]<<1)+n[0]]);n[0]=s[0]/10,r[i]=s[0]%10}n[0]>0&&(r=Jl(n,r)),Ni.push(r)}return Ni[t]}function e4(t,e){let n=0;const r=new Uint8Array(t),i=new Uint8Array(e),s=r.slice(0),a=s.length-1,c=i.slice(0),l=c.length-1;let d,u=0;for(let f=l;f>=0;f--,u++)d=s[a-u]-c[l-u]-n,!0===d<0?(n=1,s[a-u]=d+10):(n=0,s[a-u]=d);if(n>0)for(let f=a-l+1;f>=0;f--,u++)if(d=s[a-u]-n,d<0)n=1,s[a-u]=d+10;else{n=0,s[a-u]=d;break}return s.slice()}class Wu extends Zt(Ye){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=O_.call(this)))}constructor({value:e,...n}={}){super(n),this._valueDec=0,n.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(M3(e))}get valueDec(){return this._valueDec}fromDER(e,n,r,i=0){const s=this.fromBER(e,n,r);if(s===-1)return s;const a=this.valueHexView;return a[0]===0&&(a[1]&128)!==0?this.valueHexView=a.subarray(1):i!==0&&a.length<i&&(i-a.length>1&&(i=a.length+1),this.valueHexView=a.subarray(i-a.length)),s}toDER(e=!1){const n=this.valueHexView;switch(!0){case(n[0]&128)!==0:{const r=new Uint8Array(this.valueHexView.length+1);r[0]=0,r.set(n,1),this.valueHexView=r}break;case(n[0]===0&&(n[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,n,r){const i=super.fromBER(e,n,r);return i===-1||this.setValueHex(),i}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){const e=this.valueHexView.length*8-1;let n=new Uint8Array(this.valueHexView.length*8/3),r=0,i;const s=this.valueHexView;let a="",c=!1;for(let l=s.byteLength-1;l>=0;l--){i=s[l];for(let d=0;d<8;d++)(i&1)===1&&(r===e?(n=e4(dh(r),n),a="-"):n=Q3(n,dh(r))),r++,i>>=1}for(let l=0;l<n.length;l++)n[l]&&(c=!0),c&&(a+=ch.charAt(n[l]));return c===!1&&(a+=ch.charAt(0)),a}}Z_=Wu;Wu.NAME="IntegerValueBlock";Object.defineProperty(Z_.prototype,"valueHex",{set:function(t){this.valueHexView=new Uint8Array(t),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var so;class mi extends Me{constructor(e={}){super(e,Wu),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return sa(),BigInt(this.valueBlock.toString())}static fromBigInt(e){sa();const n=BigInt(e),r=new oc,i=n.toString(16).replace(/^-/,""),s=new Uint8Array(F.FromHex(i));if(n<0){const c=new Uint8Array(s.length+(s[0]&128?1:0));c[0]|=128;const d=BigInt(`0x${F.ToHex(c)}`)+n,u=T.toUint8Array(F.FromHex(d.toString(16)));u[0]|=128,r.write(u)}else s[0]&128&&r.write(new Uint8Array([0])),r.write(s);return new so({valueHex:r.final()})}convertToDER(){const e=new so({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new so({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}so=mi;D.Integer=so;mi.NAME="INTEGER";var Y_;class cc extends mi{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}Y_=cc;D.Enumerated=Y_;cc.NAME="ENUMERATED";class Xl extends Zt(Ye){constructor({valueDec:e=-1,isFirstSid:n=!1,...r}={}){super(r),this.valueDec=e,this.isFirstSid=n}fromBER(e,n,r){if(!r)return n;const i=T.toUint8Array(e);if(!yn(this,i,n,r))return-1;const s=i.subarray(n,n+r);this.valueHexView=new Uint8Array(r);for(let c=0;c<r&&(this.valueHexView[c]=s[c]&127,this.blockLength++,(s[c]&128)!==0);c++);const a=new Uint8Array(this.blockLength);for(let c=0;c<this.blockLength;c++)a[c]=this.valueHexView[c];return this.valueHexView=a,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Zr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),n+this.blockLength)}set valueBigInt(e){sa();let n=BigInt(e).toString(2);for(;n.length%7;)n="0"+n;const r=new Uint8Array(n.length/7);for(let i=0;i<r.length;i++)r[i]=parseInt(n.slice(i*7,i*7+7),2)+(i+1<r.length?128:0);this.fromBER(r.buffer,0,r.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const i=this.valueHexView,s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength-1;a++)s[a]=i[a]|128;return s[this.blockLength-1]=i[this.blockLength-1],s.buffer}const n=cr(this.valueDec,7);if(n.byteLength===0)return this.error="Error during encoding SID value",Xt;const r=new Uint8Array(n.byteLength);if(!e){const i=new Uint8Array(n),s=n.byteLength-1;for(let a=0;a<s;a++)r[a]=i[a]|128;r[s]=i[s]}return r}toString(){let e="";if(this.isHexOnly)e=F.ToHex(this.valueHexView);else if(this.isFirstSid){let n=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",n-=40):(e="2.",n-=80),e+=n.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}}Xl.NAME="sidBlock";class Q_ extends Ye{constructor({value:e=nt,...n}={}){super(n),this.value=[],e&&this.fromString(e)}fromBER(e,n,r){let i=n;for(;r>0;){const s=new Xl;if(i=s.fromBER(e,i,r),i===-1)return this.blockLength=0,this.error=s.error,i;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,r-=s.blockLength,this.value.push(s)}return i}toBER(e){const n=[];for(let r=0;r<this.value.length;r++){const i=this.value[r].toBER(e);if(i.byteLength===0)return this.error=this.value[r].error,Xt;n.push(i)}return Hu(n)}fromString(e){this.value=[];let n=0,r=0,i="",s=!1;do if(r=e.indexOf(".",n),r===-1?i=e.substring(n):i=e.substring(n,r),n=r+1,s){const a=this.value[0];let c=0;switch(a.valueDec){case 0:break;case 1:c=40;break;case 2:c=80;break;default:this.value=[];return}const l=parseInt(i,10);if(isNaN(l))return;a.valueDec=l+c,s=!1}else{const a=new Xl;if(i>Number.MAX_SAFE_INTEGER){sa();const c=BigInt(i);a.valueBigInt=c}else if(a.valueDec=parseInt(i,10),isNaN(a.valueDec))return;this.value.length||(a.isFirstSid=!0,s=!0),this.value.push(a)}while(r!==-1)}toString(){let e="",n=!1;for(let r=0;r<this.value.length;r++){n=this.value[r].isHexOnly;let i=this.value[r].toString();r!==0&&(e=`${e}.`),n?(i=`{${i}}`,this.value[r].isFirstSid?e=`2.{${i} - 80}`:e+=i):e+=i}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let n=0;n<this.value.length;n++)e.sidArray.push(this.value[n].toJSON());return e}}Q_.NAME="ObjectIdentifierValueBlock";var ey;class lc extends Me{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Q_),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}ey=lc;D.ObjectIdentifier=ey;lc.NAME="OBJECT IDENTIFIER";class Zl extends Zt(xr){constructor({valueDec:e=0,...n}={}){super(n),this.valueDec=e}fromBER(e,n,r){if(r===0)return n;const i=T.toUint8Array(e);if(!yn(this,i,n,r))return-1;const s=i.subarray(n,n+r);this.valueHexView=new Uint8Array(r);for(let c=0;c<r&&(this.valueHexView[c]=s[c]&127,this.blockLength++,(s[c]&128)!==0);c++);const a=new Uint8Array(this.blockLength);for(let c=0;c<this.blockLength;c++)a[c]=this.valueHexView[c];return this.valueHexView=a,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Zr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),n+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const i=this.valueHexView,s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength-1;a++)s[a]=i[a]|128;return s[this.blockLength-1]=i[this.blockLength-1],s.buffer}const n=cr(this.valueDec,7);if(n.byteLength===0)return this.error="Error during encoding SID value",Xt;const r=new Uint8Array(n.byteLength);if(!e){const i=new Uint8Array(n),s=n.byteLength-1;for(let a=0;a<s;a++)r[a]=i[a]|128;r[s]=i[s]}return r.buffer}toString(){let e="";return this.isHexOnly?e=F.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Zl.NAME="relativeSidBlock";class ty extends Ye{constructor({value:e=nt,...n}={}){super(n),this.value=[],e&&this.fromString(e)}fromBER(e,n,r){let i=n;for(;r>0;){const s=new Zl;if(i=s.fromBER(e,i,r),i===-1)return this.blockLength=0,this.error=s.error,i;this.blockLength+=s.blockLength,r-=s.blockLength,this.value.push(s)}return i}toBER(e,n){const r=[];for(let i=0;i<this.value.length;i++){const s=this.value[i].toBER(e);if(s.byteLength===0)return this.error=this.value[i].error,Xt;r.push(s)}return Hu(r)}fromString(e){this.value=[];let n=0,r=0,i="";do{r=e.indexOf(".",n),r===-1?i=e.substring(n):i=e.substring(n,r),n=r+1;const s=new Zl;if(s.valueDec=parseInt(i,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(r!==-1);return!0}toString(){let e="",n=!1;for(let r=0;r<this.value.length;r++){n=this.value[r].isHexOnly;let i=this.value[r].toString();r!==0&&(e=`${e}.`),n&&(i=`{${i}}`),e+=i}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let n=0;n<this.value.length;n++)e.sidArray.push(this.value[n].toJSON());return e}}ty.NAME="RelativeObjectIdentifierValueBlock";var ny;class Ju extends Me{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,ty),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}ny=Ju;D.RelativeObjectIdentifier=ny;Ju.NAME="RelativeObjectIdentifier";var ry;class It extends Ze{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}ry=It;D.Sequence=ry;It.NAME="SEQUENCE";var iy;let Kt=class extends Ze{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};iy=Kt;D.Set=iy;Kt.NAME="SET";class oy extends Zt(Ye){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=nt}toJSON(){return{...super.toJSON(),value:this.value}}}oy.NAME="StringValueBlock";class sy extends oy{}sy.NAME="SimpleStringValueBlock";class dt extends Vu{constructor({...e}={}){super(e,sy)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,T.toUint8Array(e))}fromString(e){const n=e.length,r=this.valueBlock.valueHexView=new Uint8Array(n);for(let i=0;i<n;i++)r[i]=e.charCodeAt(i);this.valueBlock.value=e}}dt.NAME="SIMPLE STRING";class ay extends dt{fromBuffer(e){this.valueBlock.valueHexView=T.toUint8Array(e);try{this.valueBlock.value=F.ToUtf8String(e)}catch(n){this.warnings.push(`Error during "decodeURIComponent": ${n}, using raw string`),this.valueBlock.value=F.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(F.FromUtf8String(e)),this.valueBlock.value=e}}ay.NAME="Utf8StringValueBlock";var cy;class wn extends ay{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}cy=wn;D.Utf8String=cy;wn.NAME="UTF8String";class ly extends dt{fromBuffer(e){this.valueBlock.value=F.ToUtf16String(e),this.valueBlock.valueHexView=T.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(F.FromUtf16String(e))}}ly.NAME="BmpStringValueBlock";var dy;class dc extends ly{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}dy=dc;D.BmpString=dy;dc.NAME="BMPString";class uy extends dt{fromBuffer(e){const n=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),r=new Uint8Array(n);for(let i=0;i<r.length;i+=4)r[i]=r[i+3],r[i+1]=r[i+2],r[i+2]=0,r[i+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(n))}fromString(e){const n=e.length,r=this.valueBlock.valueHexView=new Uint8Array(n*4);for(let i=0;i<n;i++){const s=cr(e.charCodeAt(i),8),a=new Uint8Array(s);if(a.length>4)continue;const c=4-a.length;for(let l=a.length-1;l>=0;l--)r[i*4+l+c]=a[l]}this.valueBlock.value=e}}uy.NAME="UniversalStringValueBlock";var py;class uc extends uy{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}py=uc;D.UniversalString=py;uc.NAME="UniversalString";var fy;class pc extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}fy=pc;D.NumericString=fy;pc.NAME="NumericString";var hy;class fc extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}hy=fc;D.PrintableString=hy;fc.NAME="PrintableString";var gy;class hc extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}gy=hc;D.TeletexString=gy;hc.NAME="TeletexString";var my;class gc extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}my=gc;D.VideotexString=my;gc.NAME="VideotexString";var _y;class mc extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}_y=mc;D.IA5String=_y;mc.NAME="IA5String";var yy;class _c extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}yy=_c;D.GraphicString=yy;_c.NAME="GraphicString";var wy;class Go extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}wy=Go;D.VisibleString=wy;Go.NAME="VisibleString";var by;class yc extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}by=yc;D.GeneralString=by;yc.NAME="GeneralString";var vy;class wc extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}vy=wc;D.CharacterString=vy;wc.NAME="CharacterString";var $y;class Wo extends Go{constructor({value:e,valueDate:n,...r}={}){if(super(r),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let i=0;i<e.length;i++)this.valueBlock.valueHexView[i]=e.charCodeAt(i)}n&&(this.fromDate(n),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,T.toUint8Array(e)))}toBuffer(){const e=this.toString(),n=new ArrayBuffer(e.length),r=new Uint8Array(n);for(let i=0;i<e.length;i++)r[i]=e.charCodeAt(i);return n}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){const r=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(r===null){this.error="Wrong input string for conversion";return}const i=parseInt(r[1],10);i>=50?this.year=1900+i:this.year=2e3+i,this.month=parseInt(r[2],10),this.day=parseInt(r[3],10),this.hour=parseInt(r[4],10),this.minute=parseInt(r[5],10),this.second=parseInt(r[6],10)}toString(e="iso"){if(e==="iso"){const n=new Array(7);return n[0]=at(this.year<2e3?this.year-1900:this.year-2e3,2),n[1]=at(this.month,2),n[2]=at(this.day,2),n[3]=at(this.hour,2),n[4]=at(this.minute,2),n[5]=at(this.second,2),n[6]="Z",n.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}}$y=Wo;D.UTCTime=$y;Wo.NAME="UTCTime";var ky;class bc extends Wo{constructor(e={}){var n;super(e),(n=this.millisecond)!==null&&n!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){const e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let n=!1,r="",i="",s=0,a,c=0,l=0;if(e[e.length-1]==="Z")r=e.substring(0,e.length-1),n=!0;else{const f=new Number(e[e.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");r=e}if(n){if(r.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(r.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,g=r.indexOf("+"),_="";if(g===-1&&(g=r.indexOf("-"),f=-1),g!==-1){if(_=r.substring(g+1),r=r.substring(0,g),_.length!==2&&_.length!==4)throw new Error("Wrong input string for conversion");let w=parseInt(_.substring(0,2),10);if(isNaN(w.valueOf()))throw new Error("Wrong input string for conversion");if(c=f*w,_.length===4){if(w=parseInt(_.substring(2,4),10),isNaN(w.valueOf()))throw new Error("Wrong input string for conversion");l=f*w}}}let d=r.indexOf(".");if(d===-1&&(d=r.indexOf(",")),d!==-1){const f=new Number(`0${r.substring(d)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");s=f.valueOf(),i=r.substring(0,d)}else i=r;switch(!0){case i.length===8:if(a=/(\d{4})(\d{2})(\d{2})/ig,d!==-1)throw new Error("Wrong input string for conversion");break;case i.length===10:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,d!==-1){let f=60*s;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case i.length===12:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,d!==-1){let f=60*s;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case i.length===14:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,d!==-1){const f=1e3*s;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}const u=a.exec(i);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+c;break;case 5:this.minute=parseInt(u[f],10)+l;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(n===!1){const f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){const n=[];return n.push(at(this.year,4)),n.push(at(this.month,2)),n.push(at(this.day,2)),n.push(at(this.hour,2)),n.push(at(this.minute,2)),n.push(at(this.second,2)),this.millisecond!==0&&(n.push("."),n.push(at(this.millisecond,3))),n.push("Z"),n.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}ky=bc;D.GeneralizedTime=ky;bc.NAME="GeneralizedTime";var xy;class Xu extends wn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}xy=Xu;D.DATE=xy;Xu.NAME="DATE";var Sy;class Zu extends wn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}Sy=Zu;D.TimeOfDay=Sy;Zu.NAME="TimeOfDay";var zy;class Yu extends wn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}zy=Yu;D.DateTime=zy;Yu.NAME="DateTime";var Ay;class Qu extends wn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}Ay=Qu;D.Duration=Ay;Qu.NAME="Duration";var Ey;class ep extends wn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}Ey=ep;D.TIME=Ey;ep.NAME="TIME";class dr{constructor({name:e=nt,optional:n=!1}={}){this.name=e,this.optional=n}}class tp extends dr{constructor({value:e=[],...n}={}){super(n),this.value=e}}class aa extends dr{constructor({value:e=new dr,local:n=!1,...r}={}){super(r),this.value=e,this.local=n}}class t4{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=T.toUint8Array(e)}constructor({data:e=sc}={}){this.dataView=T.toUint8Array(e)}fromBER(e,n,r){const i=n+r;return this.dataView=T.toUint8Array(e).subarray(n,i),i}toBER(e){return this.dataView.slice().buffer}}function An(t,e,n){if(n instanceof tp){for(const s of n.value)if(An(t,e,s).verified)return{verified:!0,result:t};{const s={verified:!1,result:{error:"Wrong values for Choice type"}};return n.hasOwnProperty(fl)&&(s.name=n.name),s}}if(n instanceof dr)return n.hasOwnProperty(fl)&&(t[n.name]=e),{verified:!0,result:t};if(!(t instanceof Object))return{verified:!1,result:{error:"Wrong root object"}};if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(!(n instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(H3 in n))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(W3 in n.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(J3 in n.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const r=n.idBlock.toBER(!1);if(r.byteLength===0)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(n.idBlock.fromBER(r,0,r.byteLength)===-1)return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(n.idBlock.hasOwnProperty(V3)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(n.idBlock.tagClass!==e.idBlock.tagClass)return{verified:!1,result:t};if(n.idBlock.hasOwnProperty(K3)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(n.idBlock.tagNumber!==e.idBlock.tagNumber)return{verified:!1,result:t};if(n.idBlock.hasOwnProperty(G3)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(n.idBlock.isConstructed!==e.idBlock.isConstructed)return{verified:!1,result:t};if(!(F3 in n.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(n.idBlock.isHexOnly!==e.idBlock.isHexOnly)return{verified:!1,result:t};if(n.idBlock.isHexOnly){if(!(lh in n.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const s=n.idBlock.valueHexView,a=e.idBlock.valueHexView;if(s.length!==a.length)return{verified:!1,result:t};for(let c=0;c<s.length;c++)if(s[c]!==a[1])return{verified:!1,result:t}}if(n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,nt),n.name&&(t[n.name]=e)),n instanceof D.Constructed){let s=0,a={verified:!1,result:{error:"Unknown error"}},c=n.valueBlock.value.length;if(c>0&&n.valueBlock.value[0]instanceof aa&&(c=e.valueBlock.value.length),c===0)return{verified:!0,result:t};if(e.valueBlock.value.length===0&&n.valueBlock.value.length!==0){let l=!0;for(let d=0;d<n.valueBlock.value.length;d++)l=l&&(n.valueBlock.value[d].optional||!1);return l?{verified:!0,result:t}:(n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,nt),n.name&&delete t[n.name]),t.error="Inconsistent object length",{verified:!1,result:t})}for(let l=0;l<c;l++)if(l-s>=e.valueBlock.value.length){if(n.valueBlock.value[l].optional===!1){const d={verified:!1,result:t};return t.error="Inconsistent length between ASN.1 data and schema",n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,nt),n.name&&(delete t[n.name],d.name=n.name)),d}}else if(n.valueBlock.value[0]instanceof aa){if(a=An(t,e.valueBlock.value[l],n.valueBlock.value[0].value),a.verified===!1)if(n.valueBlock.value[0].optional)s++;else return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,nt),n.name&&delete t[n.name]),a;if(fl in n.valueBlock.value[0]&&n.valueBlock.value[0].name.length>0){let d={};X3 in n.valueBlock.value[0]&&n.valueBlock.value[0].local?d=e:d=t,typeof d[n.valueBlock.value[0].name]>"u"&&(d[n.valueBlock.value[0].name]=[]),d[n.valueBlock.value[0].name].push(e.valueBlock.value[l])}}else if(a=An(t,e.valueBlock.value[l-s],n.valueBlock.value[l]),a.verified===!1)if(n.valueBlock.value[l].optional)s++;else return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,nt),n.name&&delete t[n.name]),a;if(a.verified===!1){const l={verified:!1,result:t};return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,nt),n.name&&(delete t[n.name],l.name=n.name)),l}return{verified:!0,result:t}}if(n.primitiveSchema&&lh in e.valueBlock){const s=gi(e.valueBlock.valueHexView);if(s.offset===-1){const a={verified:!1,result:s.result};return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,nt),n.name&&(delete t[n.name],a.name=n.name)),a}return An(t,s.result,n.primitiveSchema)}return{verified:!0,result:t}}function n4(t,e){if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const n=gi(T.toUint8Array(t));return n.offset===-1?{verified:!1,result:n.result}:An(n.result,n.result,e)}const Cy=Object.freeze(Object.defineProperty({__proto__:null,Any:dr,BaseBlock:Me,BaseStringBlock:Vu,BitString:ir,BmpString:dc,Boolean:ac,CharacterString:wc,Choice:tp,Constructed:Ze,DATE:Xu,DateTime:Yu,Duration:Qu,EndOfContent:Ku,Enumerated:cc,GeneralString:yc,GeneralizedTime:bc,GraphicString:_c,HexBlock:Zt,IA5String:mc,Integer:mi,Null:lr,NumericString:pc,ObjectIdentifier:lc,OctetString:rr,Primitive:Ko,PrintableString:fc,RawData:t4,RelativeObjectIdentifier:Ju,Repeated:aa,Sequence:It,Set:Kt,TIME:ep,TeletexString:hc,TimeOfDay:Zu,UTCTime:Wo,UniversalString:uc,Utf8String:wn,ValueBlock:Ye,VideotexString:gc,ViewWriter:oc,VisibleString:Go,compareSchema:An,fromBER:Hr,verifySchema:n4},Symbol.toStringTag,{value:"Module"}));var C;(function(t){t[t.Sequence=0]="Sequence",t[t.Set=1]="Set",t[t.Choice=2]="Choice"})(C||(C={}));var b;(function(t){t[t.Any=1]="Any",t[t.Boolean=2]="Boolean",t[t.OctetString=3]="OctetString",t[t.BitString=4]="BitString",t[t.Integer=5]="Integer",t[t.Enumerated=6]="Enumerated",t[t.ObjectIdentifier=7]="ObjectIdentifier",t[t.Utf8String=8]="Utf8String",t[t.BmpString=9]="BmpString",t[t.UniversalString=10]="UniversalString",t[t.NumericString=11]="NumericString",t[t.PrintableString=12]="PrintableString",t[t.TeletexString=13]="TeletexString",t[t.VideotexString=14]="VideotexString",t[t.IA5String=15]="IA5String",t[t.GraphicString=16]="GraphicString",t[t.VisibleString=17]="VisibleString",t[t.GeneralString=18]="GeneralString",t[t.CharacterString=19]="CharacterString",t[t.UTCTime=20]="UTCTime",t[t.GeneralizedTime=21]="GeneralizedTime",t[t.DATE=22]="DATE",t[t.TimeOfDay=23]="TimeOfDay",t[t.DateTime=24]="DateTime",t[t.Duration=25]="Duration",t[t.TIME=26]="TIME",t[t.Null=27]="Null"})(b||(b={}));class vc{constructor(e,n=0){if(this.unusedBits=0,this.value=new ArrayBuffer(0),e)if(typeof e=="number")this.fromNumber(e);else if(T.isBufferSource(e))this.unusedBits=n,this.value=T.toArrayBuffer(e);else throw TypeError("Unsupported type of 'params' argument for BitString")}fromASN(e){if(!(e instanceof ir))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=e.valueBlock.valueHex,this}toASN(){return new ir({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new ir({name:e})}toNumber(){let e="";const n=new Uint8Array(this.value);for(const r of n)e+=r.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let n=e.toString(2);const r=n.length+7>>3;this.unusedBits=(r<<3)-n.length;const i=new Uint8Array(r);n=n.padStart(r<<3,"0").split("").reverse().join("");let s=0;for(;s<r;)i[s]=parseInt(n.slice(s<<3,(s<<3)+8),2),s++;this.value=i.buffer}}class ae{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){typeof e=="number"?this.buffer=new ArrayBuffer(e):T.isBufferSource(e)?this.buffer=T.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof rr))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new rr({valueHex:this.buffer})}toSchema(e){return new rr({name:e})}}const r4={fromASN:t=>t instanceof lr?null:t.valueBeforeDecodeView,toASN:t=>{if(t===null)return new lr;const e=Hr(t);if(e.result.error)throw new Error(e.result.error);return e.result}},i4={fromASN:t=>t.valueBlock.valueHexView.byteLength>=4?t.valueBlock.toString():t.valueBlock.valueDec,toASN:t=>new mi({value:+t})},o4={fromASN:t=>t.valueBlock.valueDec,toASN:t=>new cc({value:t})},_e={fromASN:t=>t.valueBlock.valueHexView,toASN:t=>new mi({valueHex:t})},s4={fromASN:t=>t.valueBlock.valueHexView,toASN:t=>new ir({valueHex:t})},a4={fromASN:t=>t.valueBlock.toString(),toASN:t=>new lc({value:t})},c4={fromASN:t=>t.valueBlock.value,toASN:t=>new ac({value:t})},ca={fromASN:t=>t.valueBlock.valueHexView,toASN:t=>new rr({valueHex:t})},l4={fromASN:t=>new ae(t.getValue()),toASN:t=>t.toASN()};function bt(t){return{fromASN:e=>e.valueBlock.value,toASN:e=>new t({value:e})}}const Ny=bt(wn),d4=bt(dc),u4=bt(uc),p4=bt(pc),f4=bt(fc),h4=bt(hc),g4=bt(gc),m4=bt(mc),_4=bt(_c),y4=bt(Go),w4=bt(yc),b4=bt(wc),v4={fromASN:t=>t.toDate(),toASN:t=>new Wo({valueDate:t})},$4={fromASN:t=>t.toDate(),toASN:t=>new bc({valueDate:t})},k4={fromASN:()=>null,toASN:()=>new lr};function ao(t){switch(t){case b.Any:return r4;case b.BitString:return s4;case b.BmpString:return d4;case b.Boolean:return c4;case b.CharacterString:return b4;case b.Enumerated:return o4;case b.GeneralString:return w4;case b.GeneralizedTime:return $4;case b.GraphicString:return _4;case b.IA5String:return m4;case b.Integer:return i4;case b.Null:return k4;case b.NumericString:return p4;case b.ObjectIdentifier:return a4;case b.OctetString:return ca;case b.PrintableString:return f4;case b.TeletexString:return h4;case b.UTCTime:return v4;case b.UniversalString:return u4;case b.Utf8String:return Ny;case b.VideotexString:return g4;case b.VisibleString:return y4;default:return null}}function ln(t){return typeof t=="function"&&t.prototype?t.prototype.toASN&&t.prototype.fromASN?!0:ln(t.prototype):!!(t&&typeof t=="object"&&"toASN"in t&&"fromASN"in t)}function Iy(t){var e;if(t){const n=Object.getPrototypeOf(t);return((e=n?.prototype)===null||e===void 0?void 0:e.constructor)===Array?!0:Iy(n)}return!1}function x4(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;const n=new Uint8Array(t),r=new Uint8Array(e);for(let i=0;i<t.byteLength;i++)if(n[i]!==r[i])return!1;return!0}class S4{constructor(){this.items=new WeakMap}has(e){return this.items.has(e)}get(e,n=!1){const r=this.items.get(e);if(!r)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(n&&!r.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return r}cache(e){const n=this.get(e);n.schema||(n.schema=this.create(e,!0))}createDefault(e){const n={type:C.Sequence,items:{}},r=this.findParentSchema(e);return r&&(Object.assign(n,r),n.items=Object.assign({},n.items,r.items)),n}create(e,n){const r=this.items.get(e)||this.createDefault(e),i=[];for(const s in r.items){const a=r.items[s],c=n?s:"";let l;if(typeof a.type=="number"){const u=b[a.type],f=Cy[u];if(!f)throw new Error(`Cannot get ASN1 class by name '${u}'`);l=new f({name:c})}else ln(a.type)?l=new a.type().toSchema(c):a.optional?this.get(a.type).type===C.Choice?l=new dr({name:c}):(l=this.create(a.type,!1),l.name=c):l=new dr({name:c});const d=!!a.optional||a.defaultValue!==void 0;if(a.repeated){l.name="";const u=a.repeated==="set"?Kt:It;l=new u({name:"",value:[new aa({name:c,value:l})]})}if(a.context!==null&&a.context!==void 0)if(a.implicit)if(typeof a.type=="number"||ln(a.type)){const u=a.repeated?Ze:Ko;i.push(new u({name:c,optional:d,idBlock:{tagClass:3,tagNumber:a.context}}))}else{this.cache(a.type);const u=!!a.repeated;let f=u?l:this.get(a.type,!0).schema;f="valueBlock"in f?f.valueBlock.value:f.value,i.push(new Ze({name:u?"":c,optional:d,idBlock:{tagClass:3,tagNumber:a.context},value:f}))}else i.push(new Ze({optional:d,idBlock:{tagClass:3,tagNumber:a.context},value:[l]}));else l.optional=d,i.push(l)}switch(r.type){case C.Sequence:return new It({value:i,name:""});case C.Set:return new Kt({value:i,name:""});case C.Choice:return new tp({value:i,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,n){return this.items.set(e,n),this}findParentSchema(e){const n=Object.getPrototypeOf(e);return n?this.items.get(n)||this.findParentSchema(n):null}}const Le=new S4,j=t=>e=>{let n;Le.has(e)?n=Le.get(e):(n=Le.createDefault(e),Le.set(e,n)),Object.assign(n,t)},m=t=>(e,n)=>{let r;Le.has(e.constructor)?r=Le.get(e.constructor):(r=Le.createDefault(e.constructor),Le.set(e.constructor,r));const i=Object.assign({},t);if(typeof i.type=="number"&&!i.converter){const s=ao(t.type);if(!s)throw new Error(`Cannot get default converter for property '${n}' of ${e.constructor.name}`);i.converter=s}i.raw=t.raw,r.items[n]=i};class Ii extends Error{constructor(){super(...arguments),this.schemas=[]}}class z4{static parse(e,n){const r=Hr(e);if(r.result.error)throw new Error(r.result.error);return this.fromASN(r.result,n)}static fromASN(e,n){try{if(ln(n))return new n().fromASN(e);const r=Le.get(n);Le.cache(n);let i=r.schema;const s=this.handleChoiceTypes(e,r,n,i);if(s?.result)return s.result;s?.targetSchema&&(i=s.targetSchema);const a=this.handleSequenceTypes(e,r,n,i),c=new n;return Iy(n)?this.handleArrayTypes(e,r,n):(this.processSchemaItems(r,a,c),c)}catch(r){throw r instanceof Ii&&r.schemas.push(n.name),r}}static handleChoiceTypes(e,n,r,i){if(e.constructor===Ze&&n.type===C.Choice&&e.idBlock.tagClass===3)for(const s in n.items){const a=n.items[s];if(a.context===e.idBlock.tagNumber&&a.implicit&&typeof a.type=="function"&&Le.has(a.type)){const c=Le.get(a.type);if(c&&c.type===C.Sequence){const l=new It;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in l.valueBlock){l.valueBlock.value=e.valueBlock.value;const d=this.fromASN(l,a.type),u=new r;return u[s]=d,{result:u}}}}}else if(e.constructor===Ze&&n.type!==C.Choice){const s=new Ze({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:n.schema.valueBlock.value});for(const a in n.items)delete e[a];return{targetSchema:s}}return null}static handleSequenceTypes(e,n,r,i){if(n.type===C.Sequence){const s=An({},e,i);if(!s.verified)throw new Ii(`Data does not match to ${r.name} ASN1 schema.${s.result.error?` ${s.result.error}`:""}`);return s}else{const s=An({},e,i);if(!s.verified)throw new Ii(`Data does not match to ${r.name} ASN1 schema.${s.result.error?` ${s.result.error}`:""}`);return s}}static processRepeatedField(e,n,r){let i=e.slice(n);if(i.length===1&&i[0].constructor.name==="Sequence"){const s=i[0];s.valueBlock&&s.valueBlock.value&&Array.isArray(s.valueBlock.value)&&(i=s.valueBlock.value)}if(typeof r.type=="number"){const s=ao(r.type);if(!s)throw new Error(`No converter for ASN.1 type ${r.type}`);return i.filter(a=>a&&a.valueBlock).map(a=>{try{return s.fromASN(a)}catch{return}}).filter(a=>a!==void 0)}else return i.filter(s=>s&&s.valueBlock).map(s=>{try{return this.fromASN(s,r.type)}catch{return}}).filter(s=>s!==void 0)}static processPrimitiveField(e,n){const r=ao(n.type);if(!r)throw new Error(`No converter for ASN.1 type ${n.type}`);return r.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type=="function"&&Le.has(e.type)&&Le.get(e.type).type===C.Choice}static processOptionalChoiceField(e,n){try{return{processed:!0,value:this.fromASN(e,n.type)}}catch(r){if(r instanceof Ii&&/Wrong values for Choice type/.test(r.message))return{processed:!1};throw r}}static handleArrayTypes(e,n,r){if(!("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const i=n.itemType;if(typeof i=="number"){const s=ao(i);if(!s)throw new Error(`Cannot get default converter for array item of ${r.name} ASN1 schema`);return r.from(e.valueBlock.value,a=>s.fromASN(a))}else return r.from(e.valueBlock.value,s=>this.fromASN(s,i))}static processSchemaItems(e,n,r){for(const i in e.items){const s=n.result[i];if(!s)continue;const a=e.items[i],c=a.type;let l;typeof c=="number"||ln(c)?l=this.processPrimitiveSchemaItem(s,a,c):l=this.processComplexSchemaItem(s,a,c),l&&typeof l=="object"&&"value"in l&&"raw"in l?(r[i]=l.value,r[`${i}Raw`]=l.raw):r[i]=l}}static processPrimitiveSchemaItem(e,n,r){var i;const s=(i=n.converter)!==null&&i!==void 0?i:ln(r)?new r:null;if(!s)throw new Error("Converter is empty");return n.repeated?this.processRepeatedPrimitiveItem(e,n,s):this.processSinglePrimitiveItem(e,n,r,s)}static processRepeatedPrimitiveItem(e,n,r){if(n.implicit){const i=n.repeated==="sequence"?It:Kt,s=new i;s.valueBlock=e.valueBlock;const a=Hr(s.toBER(!1));if(a.offset===-1)throw new Error(`Cannot parse the child item. ${a.result.error}`);if(!("value"in a.result.valueBlock&&Array.isArray(a.result.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const c=a.result.valueBlock.value;return Array.from(c,l=>r.fromASN(l))}else return Array.from(e,i=>r.fromASN(i))}static processSinglePrimitiveItem(e,n,r,i){let s=e;if(n.implicit){let a;if(ln(r))a=new r().toSchema("");else{const c=b[r],l=Cy[c];if(!l)throw new Error(`Cannot get '${c}' class from asn1js module`);a=new l}a.valueBlock=s.valueBlock,s=Hr(a.toBER(!1)).result}return i.fromASN(s)}static processComplexSchemaItem(e,n,r){if(n.repeated){if(!Array.isArray(e))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");return Array.from(e,i=>this.fromASN(i,r))}else{const i=this.handleImplicitTagging(e,n,r);if(this.isOptionalChoiceField(n))try{return this.fromASN(i,r)}catch(s){if(s instanceof Ii&&/Wrong values for Choice type/.test(s.message))return;throw s}else{const s=this.fromASN(i,r);return n.raw?{value:s,raw:e.valueBeforeDecodeView}:s}}}static handleImplicitTagging(e,n,r){if(n.implicit&&typeof n.context=="number"){const i=Le.get(r);if(i.type===C.Sequence){const s=new It;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in s.valueBlock)return s.valueBlock.value=e.valueBlock.value,s}else if(i.type===C.Set){const s=new Kt;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in s.valueBlock)return s.valueBlock.value=e.valueBlock.value,s}}return e}}class np{static serialize(e){return e instanceof Me?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&typeof e=="object"&&ln(e))return e.toASN();if(!(e&&typeof e=="object"))throw new TypeError("Parameter 1 should be type of Object.");const n=e.constructor,r=Le.get(n);Le.cache(n);let i=[];if(r.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if(typeof r.itemType=="number"){const a=ao(r.itemType);if(!a)throw new Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);i=e.map(c=>a.toASN(c))}else i=e.map(a=>this.toAsnItem({type:r.itemType},"[]",n,a))}else for(const a in r.items){const c=r.items[a],l=e[a];if(l===void 0||c.defaultValue===l||typeof c.defaultValue=="object"&&typeof l=="object"&&x4(this.serialize(c.defaultValue),this.serialize(l)))continue;const d=np.toAsnItem(c,a,n,l);if(typeof c.context=="number")if(c.implicit)if(!c.repeated&&(typeof c.type=="number"||ln(c.type))){const u={};u.valueHex=d instanceof lr?d.valueBeforeDecodeView:d.valueBlock.toBER(),i.push(new Ko({optional:c.optional,idBlock:{tagClass:3,tagNumber:c.context},...u}))}else i.push(new Ze({optional:c.optional,idBlock:{tagClass:3,tagNumber:c.context},value:d.valueBlock.value}));else i.push(new Ze({optional:c.optional,idBlock:{tagClass:3,tagNumber:c.context},value:[d]}));else c.repeated?i=i.concat(d):i.push(d)}let s;switch(r.type){case C.Sequence:s=new It({value:i});break;case C.Set:s=new Kt({value:i});break;case C.Choice:if(!i[0])throw new Error(`Schema '${n.name}' has wrong data. Choice cannot be empty.`);s=i[0];break}return s}static toAsnItem(e,n,r,i){let s;if(typeof e.type=="number"){const a=e.converter;if(!a)throw new Error(`Property '${n}' doesn't have converter for type ${b[e.type]} in schema '${r.name}'`);if(e.repeated){if(!Array.isArray(i))throw new TypeError("Parameter 'objProp' should be type of Array.");const c=Array.from(i,d=>a.toASN(d)),l=e.repeated==="sequence"?It:Kt;s=new l({value:c})}else s=a.toASN(i)}else if(e.repeated){if(!Array.isArray(i))throw new TypeError("Parameter 'objProp' should be type of Array.");const a=Array.from(i,l=>this.toASN(l)),c=e.repeated==="sequence"?It:Kt;s=new c({value:a})}else s=this.toASN(i);return s}}class ue extends Array{constructor(e=[]){if(typeof e=="number")super(e);else{super();for(const n of e)this.push(n)}}}class O{static serialize(e){return np.serialize(e)}static parse(e,n){return z4.parse(e,n)}static toString(e){const n=T.isBufferSource(e)?T.toArrayBuffer(e):O.serialize(e),r=Hr(n);if(r.offset===-1)throw new Error(`Cannot decode ASN.1 data. ${r.result.error}`);return r.result.toString()}}function h(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var c=t.length-1;c>=0;c--)(a=t[c])&&(s=(i<3?a(s):i>3?a(e,n,s):a(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s}function re(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}function ye(t,e,n,r,i){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?i.call(t,n):i?i.value=n:e.set(t,n),n}class uh{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){const n=e.split(".");if(n.length!==4)throw new Error("Invalid IPv4 address");return n.map(r=>{const i=parseInt(r,10);if(isNaN(i)||i<0||i>255)throw new Error("Invalid IPv4 address part");return i})}static parseIPv6(e){const r=this.expandIPv6(e).split(":");if(r.length!==8)throw new Error("Invalid IPv6 address");return r.reduce((i,s)=>{const a=parseInt(s,16);if(isNaN(a)||a<0||a>65535)throw new Error("Invalid IPv6 address part");return i.push(a>>8&255),i.push(a&255),i},[])}static expandIPv6(e){if(!e.includes("::"))return e;const n=e.split("::");if(n.length>2)throw new Error("Invalid IPv6 address");const r=n[0]?n[0].split(":"):[],i=n[1]?n[1].split(":"):[],s=8-(r.length+i.length);if(s<0)throw new Error("Invalid IPv6 address");return[...r,...Array(s).fill("0"),...i].join(":")}static formatIPv6(e){const n=[];for(let r=0;r<16;r+=2)n.push((e[r]<<8|e[r+1]).toString(16));return this.compressIPv6(n.join(":"))}static compressIPv6(e){const n=e.split(":");let r=-1,i=0,s=-1,a=0;for(let c=0;c<n.length;c++)n[c]==="0"?(s===-1&&(s=c),a++):(a>i&&(r=s,i=a),s=-1,a=0);if(a>i&&(r=s,i=a),i>1){const c=n.slice(0,r).join(":"),l=n.slice(r+i).join(":");return`${c}::${l}`}return e}static parseCIDR(e){const[n,r]=e.split("/"),i=parseInt(r,10);if(this.isIPv4(n)){if(i<0||i>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(n),i]}else{if(i<0||i>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(n),i]}}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return"::/0";if(e.length!==16)return e;const n=parseInt(e.slice(8),16).toString(2).split("").reduce((i,s)=>i+ +s,0);let r=e.slice(0,8).replace(/(.{2})/g,i=>`${parseInt(i,16)}.`);return r=r.slice(0,-1),`${r}/${n}`}static toString(e){const n=new Uint8Array(e);if(n.length===4)return Array.from(n).join(".");if(n.length===16)return this.formatIPv6(n);if(n.length===8||n.length===32){const r=n.length/2,i=n.slice(0,r),s=n.slice(r);if(n.every(l=>l===0))return n.length===8?"0.0.0.0/0":"::/0";const c=s.reduce((l,d)=>l+(d.toString(2).match(/1/g)||[]).length,0);return n.length===8?`${Array.from(i).join(".")}/${c}`:`${this.formatIPv6(i)}/${c}`}return this.decodeIP(F.ToHex(e))}static fromString(e){if(e.includes("/")){const[r,i]=this.parseCIDR(e),s=new Uint8Array(r.length);let a=i;for(let l=0;l<s.length;l++)a>=8?(s[l]=255,a-=8):a>0&&(s[l]=255<<8-a,a=0);const c=new Uint8Array(r.length*2);return c.set(r,0),c.set(s,r.length),c.buffer}const n=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(n).buffer}}var Yl,Ql,ed;let qe=class{constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};h([m({type:b.TeletexString})],qe.prototype,"teletexString",void 0);h([m({type:b.PrintableString})],qe.prototype,"printableString",void 0);h([m({type:b.UniversalString})],qe.prototype,"universalString",void 0);h([m({type:b.Utf8String})],qe.prototype,"utf8String",void 0);h([m({type:b.BmpString})],qe.prototype,"bmpString",void 0);qe=h([j({type:C.Choice})],qe);let Yr=class extends qe{constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?F.ToHex(this.anyValue):super.toString())}};h([m({type:b.IA5String})],Yr.prototype,"ia5String",void 0);h([m({type:b.Any})],Yr.prototype,"anyValue",void 0);Yr=h([j({type:C.Choice})],Yr);class $c{constructor(e={}){this.type="",this.value=new Yr,Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],$c.prototype,"type",void 0);h([m({type:Yr})],$c.prototype,"value",void 0);let Qr=Yl=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Yl.prototype)}};Qr=Yl=h([j({type:C.Set,itemType:$c})],Qr);let td=Ql=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Ql.prototype)}};td=Ql=h([j({type:C.Sequence,itemType:Qr})],td);let Ce=ed=class extends td{constructor(e){super(e),Object.setPrototypeOf(this,ed.prototype)}};Ce=ed=h([j({type:C.Sequence})],Ce);const A4={fromASN:t=>uh.toString(ca.fromASN(t)),toASN:t=>ca.toASN(uh.fromString(t))};class ko{constructor(e={}){this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],ko.prototype,"typeId",void 0);h([m({type:b.Any,context:0})],ko.prototype,"value",void 0);class rp{constructor(e={}){this.partyName=new qe,Object.assign(this,e)}}h([m({type:qe,optional:!0,context:0,implicit:!0})],rp.prototype,"nameAssigner",void 0);h([m({type:qe,context:1,implicit:!0})],rp.prototype,"partyName",void 0);let ee=class{constructor(e={}){Object.assign(this,e)}};h([m({type:ko,context:0,implicit:!0})],ee.prototype,"otherName",void 0);h([m({type:b.IA5String,context:1,implicit:!0})],ee.prototype,"rfc822Name",void 0);h([m({type:b.IA5String,context:2,implicit:!0})],ee.prototype,"dNSName",void 0);h([m({type:b.Any,context:3,implicit:!0})],ee.prototype,"x400Address",void 0);h([m({type:Ce,context:4,implicit:!1})],ee.prototype,"directoryName",void 0);h([m({type:rp,context:5})],ee.prototype,"ediPartyName",void 0);h([m({type:b.IA5String,context:6,implicit:!0})],ee.prototype,"uniformResourceIdentifier",void 0);h([m({type:b.OctetString,context:7,implicit:!0,converter:A4})],ee.prototype,"iPAddress",void 0);h([m({type:b.ObjectIdentifier,context:8,implicit:!0})],ee.prototype,"registeredID",void 0);ee=h([j({type:C.Choice})],ee);const ip="1.3.6.1.5.5.7",E4=`${ip}.1`,_i=`${ip}.3`,kc=`${ip}.48`,ph=`${kc}.1`,fh=`${kc}.2`,hh=`${kc}.3`,gh=`${kc}.5`,bn="2.5.29";var nd;const rd=`${E4}.1`;class Jo{constructor(e={}){this.accessMethod="",this.accessLocation=new ee,Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],Jo.prototype,"accessMethod",void 0);h([m({type:ee})],Jo.prototype,"accessLocation",void 0);let Ur=nd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,nd.prototype)}};Ur=nd=h([j({type:C.Sequence,itemType:Jo})],Ur);const id=`${bn}.35`;class op extends ae{}class Qn{constructor(e={}){e&&Object.assign(this,e)}}h([m({type:op,context:0,optional:!0,implicit:!0})],Qn.prototype,"keyIdentifier",void 0);h([m({type:ee,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Qn.prototype,"authorityCertIssuer",void 0);h([m({type:b.Integer,context:2,optional:!0,implicit:!0,converter:_e})],Qn.prototype,"authorityCertSerialNumber",void 0);const jy=`${bn}.19`;class la{constructor(e={}){this.cA=!1,Object.assign(this,e)}}h([m({type:b.Boolean,defaultValue:!1})],la.prototype,"cA",void 0);h([m({type:b.Integer,optional:!0})],la.prototype,"pathLenConstraint",void 0);var od;let We=od=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,od.prototype)}};We=od=h([j({type:C.Sequence,itemType:ee})],We);var sd;let mh=sd=class extends We{constructor(e){super(e),Object.setPrototypeOf(this,sd.prototype)}};mh=sd=h([j({type:C.Sequence})],mh);var ad;const Py=`${bn}.32`;let un=class{constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};h([m({type:b.IA5String})],un.prototype,"ia5String",void 0);h([m({type:b.VisibleString})],un.prototype,"visibleString",void 0);h([m({type:b.BmpString})],un.prototype,"bmpString",void 0);h([m({type:b.Utf8String})],un.prototype,"utf8String",void 0);un=h([j({type:C.Choice})],un);class sp{constructor(e={}){this.organization=new un,this.noticeNumbers=[],Object.assign(this,e)}}h([m({type:un})],sp.prototype,"organization",void 0);h([m({type:b.Integer,repeated:"sequence"})],sp.prototype,"noticeNumbers",void 0);class ap{constructor(e={}){Object.assign(this,e)}}h([m({type:sp,optional:!0})],ap.prototype,"noticeRef",void 0);h([m({type:un,optional:!0})],ap.prototype,"explicitText",void 0);let da=class{constructor(e={}){Object.assign(this,e)}};h([m({type:b.IA5String})],da.prototype,"cPSuri",void 0);h([m({type:ap})],da.prototype,"userNotice",void 0);da=h([j({type:C.Choice})],da);class cp{constructor(e={}){this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],cp.prototype,"policyQualifierId",void 0);h([m({type:b.Any})],cp.prototype,"qualifier",void 0);class xc{constructor(e={}){this.policyIdentifier="",Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],xc.prototype,"policyIdentifier",void 0);h([m({type:cp,repeated:"sequence",optional:!0})],xc.prototype,"policyQualifiers",void 0);let ua=ad=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,ad.prototype)}};ua=ad=h([j({type:C.Sequence,itemType:xc})],ua);let pa=class{constructor(e=0){this.value=e}};h([m({type:b.Integer})],pa.prototype,"value",void 0);pa=h([j({type:C.Choice})],pa);let _h=class extends pa{};_h=h([j({type:C.Choice})],_h);var cd;const ld=`${bn}.31`;var kt;(function(t){t[t.unused=1]="unused",t[t.keyCompromise=2]="keyCompromise",t[t.cACompromise=4]="cACompromise",t[t.affiliationChanged=8]="affiliationChanged",t[t.superseded=16]="superseded",t[t.cessationOfOperation=32]="cessationOfOperation",t[t.certificateHold=64]="certificateHold",t[t.privilegeWithdrawn=128]="privilegeWithdrawn",t[t.aACompromise=256]="aACompromise"})(kt||(kt={}));class Oy extends vc{toJSON(){const e=[],n=this.toNumber();return n&kt.aACompromise&&e.push("aACompromise"),n&kt.affiliationChanged&&e.push("affiliationChanged"),n&kt.cACompromise&&e.push("cACompromise"),n&kt.certificateHold&&e.push("certificateHold"),n&kt.cessationOfOperation&&e.push("cessationOfOperation"),n&kt.keyCompromise&&e.push("keyCompromise"),n&kt.privilegeWithdrawn&&e.push("privilegeWithdrawn"),n&kt.superseded&&e.push("superseded"),n&kt.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let ur=class{constructor(e={}){Object.assign(this,e)}};h([m({type:ee,context:0,repeated:"sequence",implicit:!0})],ur.prototype,"fullName",void 0);h([m({type:Qr,context:1,implicit:!0})],ur.prototype,"nameRelativeToCRLIssuer",void 0);ur=h([j({type:C.Choice})],ur);class yi{constructor(e={}){Object.assign(this,e)}}h([m({type:ur,context:0,optional:!0})],yi.prototype,"distributionPoint",void 0);h([m({type:Oy,context:1,optional:!0,implicit:!0})],yi.prototype,"reasons",void 0);h([m({type:ee,context:2,optional:!0,repeated:"sequence",implicit:!0})],yi.prototype,"cRLIssuer",void 0);let Vr=cd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,cd.prototype)}};Vr=cd=h([j({type:C.Sequence,itemType:yi})],Vr);var dd;let yh=dd=class extends Vr{constructor(e){super(e),Object.setPrototypeOf(this,dd.prototype)}};yh=dd=h([j({type:C.Sequence,itemType:yi})],yh);class Ge{constructor(e={}){this.onlyContainsUserCerts=Ge.ONLY,this.onlyContainsCACerts=Ge.ONLY,this.indirectCRL=Ge.ONLY,this.onlyContainsAttributeCerts=Ge.ONLY,Object.assign(this,e)}}Ge.ONLY=!1;h([m({type:ur,context:0,optional:!0})],Ge.prototype,"distributionPoint",void 0);h([m({type:b.Boolean,context:1,defaultValue:Ge.ONLY,implicit:!0})],Ge.prototype,"onlyContainsUserCerts",void 0);h([m({type:b.Boolean,context:2,defaultValue:Ge.ONLY,implicit:!0})],Ge.prototype,"onlyContainsCACerts",void 0);h([m({type:Oy,context:3,optional:!0,implicit:!0})],Ge.prototype,"onlySomeReasons",void 0);h([m({type:b.Boolean,context:4,defaultValue:Ge.ONLY,implicit:!0})],Ge.prototype,"indirectCRL",void 0);h([m({type:b.Boolean,context:5,defaultValue:Ge.ONLY,implicit:!0})],Ge.prototype,"onlyContainsAttributeCerts",void 0);var co;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(co||(co={}));let ud=class{constructor(e=co.unspecified){this.reason=co.unspecified,this.reason=e}toJSON(){return co[this.reason]}toString(){return this.toJSON()}};h([m({type:b.Enumerated})],ud.prototype,"reason",void 0);ud=h([j({type:C.Choice})],ud);var pd;const Ty=`${bn}.37`;let fa=pd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,pd.prototype)}};fa=pd=h([j({type:C.Sequence,itemType:b.ObjectIdentifier})],fa);const C4=`${_i}.1`,N4=`${_i}.2`,I4=`${_i}.3`,j4=`${_i}.4`,P4=`${_i}.8`,O4=`${_i}.9`;let fd=class{constructor(e=new ArrayBuffer(0)){this.value=e}};h([m({type:b.Integer,converter:_e})],fd.prototype,"value",void 0);fd=h([j({type:C.Choice})],fd);let hd=class{constructor(e){this.value=new Date,e&&(this.value=e)}};h([m({type:b.GeneralizedTime})],hd.prototype,"value",void 0);hd=h([j({type:C.Choice})],hd);var gd;const Ry=`${bn}.18`;let wh=gd=class extends We{constructor(e){super(e),Object.setPrototypeOf(this,gd.prototype)}};wh=gd=h([j({type:C.Sequence})],wh);const By=`${bn}.15`;var xt;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(xt||(xt={}));class hl extends vc{toJSON(){const e=this.toNumber(),n=[];return e&xt.cRLSign&&n.push("crlSign"),e&xt.dataEncipherment&&n.push("dataEncipherment"),e&xt.decipherOnly&&n.push("decipherOnly"),e&xt.digitalSignature&&n.push("digitalSignature"),e&xt.encipherOnly&&n.push("encipherOnly"),e&xt.keyAgreement&&n.push("keyAgreement"),e&xt.keyCertSign&&n.push("keyCertSign"),e&xt.keyEncipherment&&n.push("keyEncipherment"),e&xt.nonRepudiation&&n.push("nonRepudiation"),n}toString(){return`[${this.toJSON().join(", ")}]`}}var md;class Sc{constructor(e={}){this.base=new ee,this.minimum=0,Object.assign(this,e)}}h([m({type:ee})],Sc.prototype,"base",void 0);h([m({type:b.Integer,context:0,defaultValue:0,implicit:!0})],Sc.prototype,"minimum",void 0);h([m({type:b.Integer,context:1,optional:!0,implicit:!0})],Sc.prototype,"maximum",void 0);let ha=md=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,md.prototype)}};ha=md=h([j({type:C.Sequence,itemType:Sc})],ha);class Ly{constructor(e={}){Object.assign(this,e)}}h([m({type:ha,context:0,optional:!0,implicit:!0})],Ly.prototype,"permittedSubtrees",void 0);h([m({type:ha,context:1,optional:!0,implicit:!0})],Ly.prototype,"excludedSubtrees",void 0);class Uy{constructor(e={}){Object.assign(this,e)}}h([m({type:b.Integer,context:0,implicit:!0,optional:!0,converter:_e})],Uy.prototype,"requireExplicitPolicy",void 0);h([m({type:b.Integer,context:1,implicit:!0,optional:!0,converter:_e})],Uy.prototype,"inhibitPolicyMapping",void 0);var _d;class lp{constructor(e={}){this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],lp.prototype,"issuerDomainPolicy",void 0);h([m({type:b.ObjectIdentifier})],lp.prototype,"subjectDomainPolicy",void 0);let bh=_d=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,_d.prototype)}};bh=_d=h([j({type:C.Sequence,itemType:lp})],bh);var yd;const Dy=`${bn}.17`;let wd=yd=class extends We{constructor(e){super(e),Object.setPrototypeOf(this,yd.prototype)}};wd=yd=h([j({type:C.Sequence})],wd);let pn=class{constructor(e={}){this.type="",this.values=[],Object.assign(this,e)}};h([m({type:b.ObjectIdentifier})],pn.prototype,"type",void 0);h([m({type:b.Any,repeated:"set"})],pn.prototype,"values",void 0);var bd;let vh=bd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,bd.prototype)}};vh=bd=h([j({type:C.Sequence,itemType:pn})],vh);const My=`${bn}.14`;class jn extends op{}class qy{constructor(e={}){Object.assign(this,e)}}h([m({type:b.GeneralizedTime,context:0,implicit:!0,optional:!0})],qy.prototype,"notBefore",void 0);h([m({type:b.GeneralizedTime,context:1,implicit:!0,optional:!0})],qy.prototype,"notAfter",void 0);var lo;(function(t){t[t.keyUpdateAllowed=1]="keyUpdateAllowed",t[t.newExtensions=2]="newExtensions",t[t.pKIXCertificate=4]="pKIXCertificate"})(lo||(lo={}));class Fy extends vc{toJSON(){const e=[],n=this.toNumber();return n&lo.pKIXCertificate&&e.push("pKIXCertificate"),n&lo.newExtensions&&e.push("newExtensions"),n&lo.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class Hy{constructor(e={}){this.entrustVers="",this.entrustInfoFlags=new Fy,Object.assign(this,e)}}h([m({type:b.GeneralString})],Hy.prototype,"entrustVers",void 0);h([m({type:Fy})],Hy.prototype,"entrustInfoFlags",void 0);var vd;let $h=vd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,vd.prototype)}};$h=vd=h([j({type:C.Sequence,itemType:Jo})],$h);class U{constructor(e={}){this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof U&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&P_(e.parameters,this.parameters)||e.parameters===this.parameters)}}h([m({type:b.ObjectIdentifier})],U.prototype,"algorithm",void 0);h([m({type:b.Any,optional:!0})],U.prototype,"parameters",void 0);class At{constructor(e={}){this.algorithm=new U,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:U})],At.prototype,"algorithm",void 0);h([m({type:b.BitString})],At.prototype,"subjectPublicKey",void 0);let Ue=class{constructor(e){if(e)if(typeof e=="string"||typeof e=="number"||e instanceof Date){const n=new Date(e);n.getUTCFullYear()>2049?this.generalTime=n:this.utcTime=n}else Object.assign(this,e)}getTime(){const e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};h([m({type:b.UTCTime})],Ue.prototype,"utcTime",void 0);h([m({type:b.GeneralizedTime})],Ue.prototype,"generalTime",void 0);Ue=h([j({type:C.Choice})],Ue);class Xo{constructor(e){this.notBefore=new Ue(new Date),this.notAfter=new Ue(new Date),e&&(this.notBefore=new Ue(e.notBefore),this.notAfter=new Ue(e.notAfter))}}h([m({type:Ue})],Xo.prototype,"notBefore",void 0);h([m({type:Ue})],Xo.prototype,"notAfter",void 0);var $d;let yt=class Vy{constructor(e={}){this.extnID="",this.critical=Vy.CRITICAL,this.extnValue=new ae,Object.assign(this,e)}};yt.CRITICAL=!1;h([m({type:b.ObjectIdentifier})],yt.prototype,"extnID",void 0);h([m({type:b.Boolean,defaultValue:yt.CRITICAL})],yt.prototype,"critical",void 0);h([m({type:ae})],yt.prototype,"extnValue",void 0);let Tn=$d=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,$d.prototype)}};Tn=$d=h([j({type:C.Sequence,itemType:yt})],Tn);var pr;(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2",t[t.v3=2]="v3"})(pr||(pr={}));class ut{constructor(e={}){this.version=pr.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new U,this.issuer=new Ce,this.validity=new Xo,this.subject=new Ce,this.subjectPublicKeyInfo=new At,Object.assign(this,e)}}h([m({type:b.Integer,context:0,defaultValue:pr.v1})],ut.prototype,"version",void 0);h([m({type:b.Integer,converter:_e})],ut.prototype,"serialNumber",void 0);h([m({type:U})],ut.prototype,"signature",void 0);h([m({type:Ce})],ut.prototype,"issuer",void 0);h([m({type:Xo})],ut.prototype,"validity",void 0);h([m({type:Ce})],ut.prototype,"subject",void 0);h([m({type:At})],ut.prototype,"subjectPublicKeyInfo",void 0);h([m({type:b.BitString,context:1,implicit:!0,optional:!0})],ut.prototype,"issuerUniqueID",void 0);h([m({type:b.BitString,context:2,implicit:!0,optional:!0})],ut.prototype,"subjectUniqueID",void 0);h([m({type:Tn,context:3,optional:!0})],ut.prototype,"extensions",void 0);class fr{constructor(e={}){this.tbsCertificate=new ut,this.signatureAlgorithm=new U,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:ut,raw:!0})],fr.prototype,"tbsCertificate",void 0);h([m({type:U})],fr.prototype,"signatureAlgorithm",void 0);h([m({type:b.BitString})],fr.prototype,"signatureValue",void 0);class zc{constructor(e={}){this.userCertificate=new ArrayBuffer(0),this.revocationDate=new Ue,Object.assign(this,e)}}h([m({type:b.Integer,converter:_e})],zc.prototype,"userCertificate",void 0);h([m({type:Ue})],zc.prototype,"revocationDate",void 0);h([m({type:yt,optional:!0,repeated:"sequence"})],zc.prototype,"crlEntryExtensions",void 0);class vn{constructor(e={}){this.signature=new U,this.issuer=new Ce,this.thisUpdate=new Ue,Object.assign(this,e)}}h([m({type:b.Integer,optional:!0})],vn.prototype,"version",void 0);h([m({type:U})],vn.prototype,"signature",void 0);h([m({type:Ce})],vn.prototype,"issuer",void 0);h([m({type:Ue})],vn.prototype,"thisUpdate",void 0);h([m({type:Ue,optional:!0})],vn.prototype,"nextUpdate",void 0);h([m({type:zc,repeated:"sequence",optional:!0})],vn.prototype,"revokedCertificates",void 0);h([m({type:yt,optional:!0,context:0,repeated:"sequence"})],vn.prototype,"crlExtensions",void 0);class dp{constructor(e={}){this.tbsCertList=new vn,this.signatureAlgorithm=new U,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:vn,raw:!0})],dp.prototype,"tbsCertList",void 0);h([m({type:U})],dp.prototype,"signatureAlgorithm",void 0);h([m({type:b.BitString})],dp.prototype,"signature",void 0);class wi{constructor(e={}){this.issuer=new Ce,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:Ce})],wi.prototype,"issuer",void 0);h([m({type:b.Integer,converter:_e})],wi.prototype,"serialNumber",void 0);let ei=class{constructor(e={}){Object.assign(this,e)}};h([m({type:jn,context:0,implicit:!0})],ei.prototype,"subjectKeyIdentifier",void 0);h([m({type:wi})],ei.prototype,"issuerAndSerialNumber",void 0);ei=h([j({type:C.Choice})],ei);var fn;(function(t){t[t.v0=0]="v0",t[t.v1=1]="v1",t[t.v2=2]="v2",t[t.v3=3]="v3",t[t.v4=4]="v4",t[t.v5=5]="v5"})(fn||(fn={}));let xo=class extends U{};xo=h([j({type:C.Sequence})],xo);let ga=class extends U{};ga=h([j({type:C.Sequence})],ga);let Wt=class extends U{};Wt=h([j({type:C.Sequence})],Wt);let ma=class extends U{};ma=h([j({type:C.Sequence})],ma);let kh=class extends U{};kh=h([j({type:C.Sequence})],kh);let kd=class extends U{};kd=h([j({type:C.Sequence})],kd);let bi=class{constructor(e={}){this.attrType="",this.attrValues=[],Object.assign(this,e)}};h([m({type:b.ObjectIdentifier})],bi.prototype,"attrType",void 0);h([m({type:b.Any,repeated:"set"})],bi.prototype,"attrValues",void 0);var xd;class Yt{constructor(e={}){this.version=fn.v0,this.sid=new ei,this.digestAlgorithm=new xo,this.signatureAlgorithm=new ga,this.signature=new ae,Object.assign(this,e)}}h([m({type:b.Integer})],Yt.prototype,"version",void 0);h([m({type:ei})],Yt.prototype,"sid",void 0);h([m({type:xo})],Yt.prototype,"digestAlgorithm",void 0);h([m({type:bi,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],Yt.prototype,"signedAttrs",void 0);h([m({type:ga})],Yt.prototype,"signatureAlgorithm",void 0);h([m({type:ae})],Yt.prototype,"signature",void 0);h([m({type:bi,repeated:"set",context:1,implicit:!0,optional:!0})],Yt.prototype,"unsignedAttrs",void 0);let _a=xd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,xd.prototype)}};_a=xd=h([j({type:C.Set,itemType:Yt})],_a);let xh=class extends Yt{};xh=h([j({type:C.Sequence})],xh);let Sh=class extends Ue{};Sh=h([j({type:C.Choice})],Sh);class up{constructor(e={}){this.acIssuer=new ee,this.acSerial=0,this.attrs=[],Object.assign(this,e)}}h([m({type:ee})],up.prototype,"acIssuer",void 0);h([m({type:b.Integer})],up.prototype,"acSerial",void 0);h([m({type:pn,repeated:"sequence"})],up.prototype,"attrs",void 0);var Sd;let ya=Sd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Sd.prototype)}};ya=Sd=h([j({type:C.Sequence,itemType:b.ObjectIdentifier})],ya);class Ac{constructor(e={}){this.permitUnSpecified=!0,Object.assign(this,e)}}h([m({type:b.Integer,optional:!0})],Ac.prototype,"pathLenConstraint",void 0);h([m({type:ya,implicit:!0,context:0,optional:!0})],Ac.prototype,"permittedAttrs",void 0);h([m({type:ya,implicit:!0,context:1,optional:!0})],Ac.prototype,"excludedAttrs",void 0);h([m({type:b.Boolean,defaultValue:!0})],Ac.prototype,"permitUnSpecified",void 0);class Sr{constructor(e={}){this.issuer=new We,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:We})],Sr.prototype,"issuer",void 0);h([m({type:b.Integer,converter:_e})],Sr.prototype,"serial",void 0);h([m({type:b.BitString,optional:!0})],Sr.prototype,"issuerUID",void 0);var zd;(function(t){t[t.publicKey=0]="publicKey",t[t.publicKeyCert=1]="publicKeyCert",t[t.otherObjectTypes=2]="otherObjectTypes"})(zd||(zd={}));class zr{constructor(e={}){this.digestedObjectType=zd.publicKey,this.digestAlgorithm=new U,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.Enumerated})],zr.prototype,"digestedObjectType",void 0);h([m({type:b.ObjectIdentifier,optional:!0})],zr.prototype,"otherObjectTypeID",void 0);h([m({type:U})],zr.prototype,"digestAlgorithm",void 0);h([m({type:b.BitString})],zr.prototype,"objectDigest",void 0);class Ec{constructor(e={}){Object.assign(this,e)}}h([m({type:We,optional:!0})],Ec.prototype,"issuerName",void 0);h([m({type:Sr,context:0,implicit:!0,optional:!0})],Ec.prototype,"baseCertificateID",void 0);h([m({type:zr,context:1,implicit:!0,optional:!0})],Ec.prototype,"objectDigestInfo",void 0);let ti=class{constructor(e={}){Object.assign(this,e)}};h([m({type:ee,repeated:"sequence"})],ti.prototype,"v1Form",void 0);h([m({type:Ec,context:0,implicit:!0})],ti.prototype,"v2Form",void 0);ti=h([j({type:C.Choice})],ti);class Cc{constructor(e={}){this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}}h([m({type:b.GeneralizedTime})],Cc.prototype,"notBeforeTime",void 0);h([m({type:b.GeneralizedTime})],Cc.prototype,"notAfterTime",void 0);class Zo{constructor(e={}){Object.assign(this,e)}}h([m({type:Sr,implicit:!0,context:0,optional:!0})],Zo.prototype,"baseCertificateID",void 0);h([m({type:We,implicit:!0,context:1,optional:!0})],Zo.prototype,"entityName",void 0);h([m({type:zr,implicit:!0,context:2,optional:!0})],Zo.prototype,"objectDigestInfo",void 0);var Ad;(function(t){t[t.v2=1]="v2"})(Ad||(Ad={}));class Tt{constructor(e={}){this.version=Ad.v2,this.holder=new Zo,this.issuer=new ti,this.signature=new U,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new Cc,this.attributes=[],Object.assign(this,e)}}h([m({type:b.Integer})],Tt.prototype,"version",void 0);h([m({type:Zo})],Tt.prototype,"holder",void 0);h([m({type:ti})],Tt.prototype,"issuer",void 0);h([m({type:U})],Tt.prototype,"signature",void 0);h([m({type:b.Integer,converter:_e})],Tt.prototype,"serialNumber",void 0);h([m({type:Cc})],Tt.prototype,"attrCertValidityPeriod",void 0);h([m({type:pn,repeated:"sequence"})],Tt.prototype,"attributes",void 0);h([m({type:b.BitString,optional:!0})],Tt.prototype,"issuerUniqueID",void 0);h([m({type:Tn,optional:!0})],Tt.prototype,"extensions",void 0);class Nc{constructor(e={}){this.acinfo=new Tt,this.signatureAlgorithm=new U,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:Tt})],Nc.prototype,"acinfo",void 0);h([m({type:U})],Nc.prototype,"signatureAlgorithm",void 0);h([m({type:b.BitString})],Nc.prototype,"signatureValue",void 0);var wa;(function(t){t[t.unmarked=1]="unmarked",t[t.unclassified=2]="unclassified",t[t.restricted=4]="restricted",t[t.confidential=8]="confidential",t[t.secret=16]="secret",t[t.topSecret=32]="topSecret"})(wa||(wa={}));class Ed extends vc{}class pp{constructor(e={}){this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier,implicit:!0,context:0})],pp.prototype,"type",void 0);h([m({type:b.Any,implicit:!0,context:1})],pp.prototype,"value",void 0);class fp{constructor(e={}){this.policyId="",this.classList=new Ed(wa.unclassified),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],fp.prototype,"policyId",void 0);h([m({type:Ed,defaultValue:new Ed(wa.unclassified)})],fp.prototype,"classList",void 0);h([m({type:pp,repeated:"set"})],fp.prototype,"securityCategories",void 0);class Ic{constructor(e={}){Object.assign(this,e)}}h([m({type:ae})],Ic.prototype,"cotets",void 0);h([m({type:b.ObjectIdentifier})],Ic.prototype,"oid",void 0);h([m({type:b.Utf8String})],Ic.prototype,"string",void 0);class Ky{constructor(e={}){this.values=[],Object.assign(this,e)}}h([m({type:We,implicit:!0,context:0,optional:!0})],Ky.prototype,"policyAuthority",void 0);h([m({type:Ic,repeated:"sequence"})],Ky.prototype,"values",void 0);var Cd;class jc{constructor(e={}){this.targetCertificate=new Sr,Object.assign(this,e)}}h([m({type:Sr})],jc.prototype,"targetCertificate",void 0);h([m({type:ee,optional:!0})],jc.prototype,"targetName",void 0);h([m({type:zr,optional:!0})],jc.prototype,"certDigestInfo",void 0);let ni=class{constructor(e={}){Object.assign(this,e)}};h([m({type:ee,context:0,implicit:!0})],ni.prototype,"targetName",void 0);h([m({type:ee,context:1,implicit:!0})],ni.prototype,"targetGroup",void 0);h([m({type:jc,context:2,implicit:!0})],ni.prototype,"targetCert",void 0);ni=h([j({type:C.Choice})],ni);let Nd=Cd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Cd.prototype)}};Nd=Cd=h([j({type:C.Sequence,itemType:ni})],Nd);var Id;let zh=Id=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Id.prototype)}};zh=Id=h([j({type:C.Sequence,itemType:Nd})],zh);class Gy{constructor(e={}){Object.assign(this,e)}}h([m({type:We,implicit:!0,context:0,optional:!0})],Gy.prototype,"roleAuthority",void 0);h([m({type:ee,implicit:!0,context:1})],Gy.prototype,"roleName",void 0);class hp{constructor(e={}){this.service=new ee,this.ident=new ee,Object.assign(this,e)}}h([m({type:ee})],hp.prototype,"service",void 0);h([m({type:ee})],hp.prototype,"ident",void 0);h([m({type:ae,optional:!0})],hp.prototype,"authInfo",void 0);var jd;class gp{constructor(e={}){this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],gp.prototype,"otherCertFormat",void 0);h([m({type:b.Any})],gp.prototype,"otherCert",void 0);let ri=class{constructor(e={}){Object.assign(this,e)}};h([m({type:fr})],ri.prototype,"certificate",void 0);h([m({type:Nc,context:2,implicit:!0})],ri.prototype,"v2AttrCert",void 0);h([m({type:gp,context:3,implicit:!0})],ri.prototype,"other",void 0);ri=h([j({type:C.Choice})],ri);let ba=jd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,jd.prototype)}};ba=jd=h([j({type:C.Set,itemType:ri})],ba);class vi{constructor(e={}){this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],vi.prototype,"contentType",void 0);h([m({type:b.Any,context:0})],vi.prototype,"content",void 0);let So=class{constructor(e={}){Object.assign(this,e)}};h([m({type:ae})],So.prototype,"single",void 0);h([m({type:b.Any})],So.prototype,"any",void 0);So=h([j({type:C.Choice})],So);class Pc{constructor(e={}){this.eContentType="",Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],Pc.prototype,"eContentType",void 0);h([m({type:So,context:0,optional:!0})],Pc.prototype,"eContent",void 0);let zo=class{constructor(e={}){Object.assign(this,e)}};h([m({type:ae,context:0,implicit:!0,optional:!0})],zo.prototype,"value",void 0);h([m({type:ae,converter:l4,context:0,implicit:!0,optional:!0,repeated:"sequence"})],zo.prototype,"constructedValue",void 0);zo=h([j({type:C.Choice})],zo);class Yo{constructor(e={}){this.contentType="",this.contentEncryptionAlgorithm=new ma,Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],Yo.prototype,"contentType",void 0);h([m({type:ma})],Yo.prototype,"contentEncryptionAlgorithm",void 0);h([m({type:zo,optional:!0})],Yo.prototype,"encryptedContent",void 0);class Oc{constructor(e={}){this.keyAttrId="",Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],Oc.prototype,"keyAttrId",void 0);h([m({type:b.Any,optional:!0})],Oc.prototype,"keyAttr",void 0);var Pd;class Tc{constructor(e={}){this.subjectKeyIdentifier=new jn,Object.assign(this,e)}}h([m({type:jn})],Tc.prototype,"subjectKeyIdentifier",void 0);h([m({type:b.GeneralizedTime,optional:!0})],Tc.prototype,"date",void 0);h([m({type:Oc,optional:!0})],Tc.prototype,"other",void 0);let ii=class{constructor(e={}){Object.assign(this,e)}};h([m({type:Tc,context:0,implicit:!0,optional:!0})],ii.prototype,"rKeyId",void 0);h([m({type:wi,optional:!0})],ii.prototype,"issuerAndSerialNumber",void 0);ii=h([j({type:C.Choice})],ii);class mp{constructor(e={}){this.rid=new ii,this.encryptedKey=new ae,Object.assign(this,e)}}h([m({type:ii})],mp.prototype,"rid",void 0);h([m({type:ae})],mp.prototype,"encryptedKey",void 0);let va=Pd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Pd.prototype)}};va=Pd=h([j({type:C.Sequence,itemType:mp})],va);class _p{constructor(e={}){this.algorithm=new U,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:U})],_p.prototype,"algorithm",void 0);h([m({type:b.BitString})],_p.prototype,"publicKey",void 0);let hr=class{constructor(e={}){Object.assign(this,e)}};h([m({type:jn,context:0,implicit:!0,optional:!0})],hr.prototype,"subjectKeyIdentifier",void 0);h([m({type:_p,context:1,implicit:!0,optional:!0})],hr.prototype,"originatorKey",void 0);h([m({type:wi,optional:!0})],hr.prototype,"issuerAndSerialNumber",void 0);hr=h([j({type:C.Choice})],hr);class $i{constructor(e={}){this.version=fn.v3,this.originator=new hr,this.keyEncryptionAlgorithm=new Wt,this.recipientEncryptedKeys=new va,Object.assign(this,e)}}h([m({type:b.Integer})],$i.prototype,"version",void 0);h([m({type:hr,context:0})],$i.prototype,"originator",void 0);h([m({type:ae,context:1,optional:!0})],$i.prototype,"ukm",void 0);h([m({type:Wt})],$i.prototype,"keyEncryptionAlgorithm",void 0);h([m({type:va})],$i.prototype,"recipientEncryptedKeys",void 0);let oi=class{constructor(e={}){Object.assign(this,e)}};h([m({type:jn,context:0,implicit:!0})],oi.prototype,"subjectKeyIdentifier",void 0);h([m({type:wi})],oi.prototype,"issuerAndSerialNumber",void 0);oi=h([j({type:C.Choice})],oi);class Qo{constructor(e={}){this.version=fn.v0,this.rid=new oi,this.keyEncryptionAlgorithm=new Wt,this.encryptedKey=new ae,Object.assign(this,e)}}h([m({type:b.Integer})],Qo.prototype,"version",void 0);h([m({type:oi})],Qo.prototype,"rid",void 0);h([m({type:Wt})],Qo.prototype,"keyEncryptionAlgorithm",void 0);h([m({type:ae})],Qo.prototype,"encryptedKey",void 0);class es{constructor(e={}){this.keyIdentifier=new ae,Object.assign(this,e)}}h([m({type:ae})],es.prototype,"keyIdentifier",void 0);h([m({type:b.GeneralizedTime,optional:!0})],es.prototype,"date",void 0);h([m({type:Oc,optional:!0})],es.prototype,"other",void 0);class ts{constructor(e={}){this.version=fn.v4,this.kekid=new es,this.keyEncryptionAlgorithm=new Wt,this.encryptedKey=new ae,Object.assign(this,e)}}h([m({type:b.Integer})],ts.prototype,"version",void 0);h([m({type:es})],ts.prototype,"kekid",void 0);h([m({type:Wt})],ts.prototype,"keyEncryptionAlgorithm",void 0);h([m({type:ae})],ts.prototype,"encryptedKey",void 0);class ns{constructor(e={}){this.version=fn.v0,this.keyEncryptionAlgorithm=new Wt,this.encryptedKey=new ae,Object.assign(this,e)}}h([m({type:b.Integer})],ns.prototype,"version",void 0);h([m({type:kd,context:0,optional:!0})],ns.prototype,"keyDerivationAlgorithm",void 0);h([m({type:Wt})],ns.prototype,"keyEncryptionAlgorithm",void 0);h([m({type:ae})],ns.prototype,"encryptedKey",void 0);class yp{constructor(e={}){this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],yp.prototype,"oriType",void 0);h([m({type:b.Any})],yp.prototype,"oriValue",void 0);let Rn=class{constructor(e={}){Object.assign(this,e)}};h([m({type:Qo,optional:!0})],Rn.prototype,"ktri",void 0);h([m({type:$i,context:1,implicit:!0,optional:!0})],Rn.prototype,"kari",void 0);h([m({type:ts,context:2,implicit:!0,optional:!0})],Rn.prototype,"kekri",void 0);h([m({type:ns,context:3,implicit:!0,optional:!0})],Rn.prototype,"pwri",void 0);h([m({type:yp,context:4,implicit:!0,optional:!0})],Rn.prototype,"ori",void 0);Rn=h([j({type:C.Choice})],Rn);var Od;let $a=Od=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Od.prototype)}};$a=Od=h([j({type:C.Set,itemType:Rn})],$a);var Td;class Rc{constructor(e={}){this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],Rc.prototype,"otherRevInfoFormat",void 0);h([m({type:b.Any})],Rc.prototype,"otherRevInfo",void 0);let ka=class{constructor(e={}){this.other=new Rc,Object.assign(this,e)}};h([m({type:Rc,context:1,implicit:!0})],ka.prototype,"other",void 0);ka=h([j({type:C.Choice})],ka);let xa=Td=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Td.prototype)}};xa=Td=h([j({type:C.Set,itemType:ka})],xa);class wp{constructor(e={}){Object.assign(this,e)}}h([m({type:ba,context:0,implicit:!0,optional:!0})],wp.prototype,"certs",void 0);h([m({type:xa,context:1,implicit:!0,optional:!0})],wp.prototype,"crls",void 0);var Rd;let Bd=Rd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Rd.prototype)}};Bd=Rd=h([j({type:C.Set,itemType:bi})],Bd);class rs{constructor(e={}){this.version=fn.v0,this.recipientInfos=new $a,this.encryptedContentInfo=new Yo,Object.assign(this,e)}}h([m({type:b.Integer})],rs.prototype,"version",void 0);h([m({type:wp,context:0,implicit:!0,optional:!0})],rs.prototype,"originatorInfo",void 0);h([m({type:$a})],rs.prototype,"recipientInfos",void 0);h([m({type:Yo})],rs.prototype,"encryptedContentInfo",void 0);h([m({type:Bd,context:1,implicit:!0,optional:!0})],rs.prototype,"unprotectedAttrs",void 0);const T4="1.2.840.113549.1.7.2";var Ld;let Sa=Ld=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Ld.prototype)}};Sa=Ld=h([j({type:C.Set,itemType:xo})],Sa);class ki{constructor(e={}){this.version=fn.v0,this.digestAlgorithms=new Sa,this.encapContentInfo=new Pc,this.signerInfos=new _a,Object.assign(this,e)}}h([m({type:b.Integer})],ki.prototype,"version",void 0);h([m({type:Sa})],ki.prototype,"digestAlgorithms",void 0);h([m({type:Pc})],ki.prototype,"encapContentInfo",void 0);h([m({type:ba,context:0,implicit:!0,optional:!0})],ki.prototype,"certificates",void 0);h([m({type:xa,context:1,implicit:!0,optional:!0})],ki.prototype,"crls",void 0);h([m({type:_a})],ki.prototype,"signerInfos",void 0);const Ao="1.2.840.10045.2.1",bp="1.2.840.10045.4.1",Wy="1.2.840.10045.4.3.1",vp="1.2.840.10045.4.3.2",$p="1.2.840.10045.4.3.3",kp="1.2.840.10045.4.3.4",Ah="1.2.840.10045.3.1.7",Eh="1.3.132.0.34",Ch="1.3.132.0.35";function is(t){return new U({algorithm:t})}const R4=is(bp);is(Wy);const B4=is(vp),L4=is($p),U4=is(kp);let Eo=class{constructor(e={}){Object.assign(this,e)}};h([m({type:b.ObjectIdentifier})],Eo.prototype,"fieldType",void 0);h([m({type:b.Any})],Eo.prototype,"parameters",void 0);Eo=h([j({type:C.Sequence})],Eo);class D4 extends ae{}let si=class{constructor(e={}){Object.assign(this,e)}};h([m({type:b.OctetString})],si.prototype,"a",void 0);h([m({type:b.OctetString})],si.prototype,"b",void 0);h([m({type:b.BitString,optional:!0})],si.prototype,"seed",void 0);si=h([j({type:C.Sequence})],si);var Ud;(function(t){t[t.ecpVer1=1]="ecpVer1"})(Ud||(Ud={}));let hn=class{constructor(e={}){this.version=Ud.ecpVer1,Object.assign(this,e)}};h([m({type:b.Integer})],hn.prototype,"version",void 0);h([m({type:Eo})],hn.prototype,"fieldID",void 0);h([m({type:si})],hn.prototype,"curve",void 0);h([m({type:D4})],hn.prototype,"base",void 0);h([m({type:b.Integer,converter:_e})],hn.prototype,"order",void 0);h([m({type:b.Integer,optional:!0})],hn.prototype,"cofactor",void 0);hn=h([j({type:C.Sequence})],hn);let Bn=class{constructor(e={}){Object.assign(this,e)}};h([m({type:b.ObjectIdentifier})],Bn.prototype,"namedCurve",void 0);h([m({type:b.Null})],Bn.prototype,"implicitCurve",void 0);h([m({type:hn})],Bn.prototype,"specifiedCurve",void 0);Bn=h([j({type:C.Choice})],Bn);class Bc{constructor(e={}){this.version=1,this.privateKey=new ae,Object.assign(this,e)}}h([m({type:b.Integer})],Bc.prototype,"version",void 0);h([m({type:ae})],Bc.prototype,"privateKey",void 0);h([m({type:Bn,context:0,optional:!0})],Bc.prototype,"parameters",void 0);h([m({type:b.BitString,context:1,optional:!0})],Bc.prototype,"publicKey",void 0);class za{constructor(e={}){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.Integer,converter:_e})],za.prototype,"r",void 0);h([m({type:b.Integer,converter:_e})],za.prototype,"s",void 0);const ot="1.2.840.113549.1.1",gr=`${ot}.1`,M4=`${ot}.7`,q4=`${ot}.9`,uo=`${ot}.10`,F4=`${ot}.2`,H4=`${ot}.4`,Aa=`${ot}.5`,V4=`${ot}.14`,Dd=`${ot}.11`,Ea=`${ot}.12`,Ca=`${ot}.13`,Jy=`${ot}.15`,Xy=`${ot}.16`,Na="1.3.14.3.2.26",Zy="2.16.840.1.101.3.4.2.4",Ia="2.16.840.1.101.3.4.2.1",ja="2.16.840.1.101.3.4.2.2",Pa="2.16.840.1.101.3.4.2.3",K4="2.16.840.1.101.3.4.2.5",G4="2.16.840.1.101.3.4.2.6",W4="1.2.840.113549.2.2",J4="1.2.840.113549.2.5",Lc=`${ot}.8`;function je(t){return new U({algorithm:t,parameters:null})}je(W4);je(J4);const mr=je(Na);je(Zy);je(Ia);je(ja);je(Pa);je(K4);je(G4);const Yy=new U({algorithm:Lc,parameters:O.serialize(mr)}),Qy=new U({algorithm:q4,parameters:O.serialize(ca.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});je(gr);je(F4);je(H4);je(Aa);je(Jy);je(Xy);je(Ea);je(Ca);je(Jy);je(Xy);class Uc{constructor(e={}){this.hashAlgorithm=new U(mr),this.maskGenAlgorithm=new U({algorithm:Lc,parameters:O.serialize(mr)}),this.pSourceAlgorithm=new U(Qy),Object.assign(this,e)}}h([m({type:U,context:0,defaultValue:mr})],Uc.prototype,"hashAlgorithm",void 0);h([m({type:U,context:1,defaultValue:Yy})],Uc.prototype,"maskGenAlgorithm",void 0);h([m({type:U,context:2,defaultValue:Qy})],Uc.prototype,"pSourceAlgorithm",void 0);new U({algorithm:M4,parameters:O.serialize(new Uc)});class _r{constructor(e={}){this.hashAlgorithm=new U(mr),this.maskGenAlgorithm=new U({algorithm:Lc,parameters:O.serialize(mr)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}}h([m({type:U,context:0,defaultValue:mr})],_r.prototype,"hashAlgorithm",void 0);h([m({type:U,context:1,defaultValue:Yy})],_r.prototype,"maskGenAlgorithm",void 0);h([m({type:b.Integer,context:2,defaultValue:20})],_r.prototype,"saltLength",void 0);h([m({type:b.Integer,context:3,defaultValue:1})],_r.prototype,"trailerField",void 0);new U({algorithm:uo,parameters:O.serialize(new _r)});class Dc{constructor(e={}){this.digestAlgorithm=new U,this.digest=new ae,Object.assign(this,e)}}h([m({type:U})],Dc.prototype,"digestAlgorithm",void 0);h([m({type:ae})],Dc.prototype,"digest",void 0);var Md;class Mc{constructor(e={}){this.prime=new ArrayBuffer(0),this.exponent=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.Integer,converter:_e})],Mc.prototype,"prime",void 0);h([m({type:b.Integer,converter:_e})],Mc.prototype,"exponent",void 0);h([m({type:b.Integer,converter:_e})],Mc.prototype,"coefficient",void 0);let qd=Md=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Md.prototype)}};qd=Md=h([j({type:C.Sequence,itemType:Mc})],qd);class Qt{constructor(e={}){this.version=0,this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),this.privateExponent=new ArrayBuffer(0),this.prime1=new ArrayBuffer(0),this.prime2=new ArrayBuffer(0),this.exponent1=new ArrayBuffer(0),this.exponent2=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.Integer})],Qt.prototype,"version",void 0);h([m({type:b.Integer,converter:_e})],Qt.prototype,"modulus",void 0);h([m({type:b.Integer,converter:_e})],Qt.prototype,"publicExponent",void 0);h([m({type:b.Integer,converter:_e})],Qt.prototype,"privateExponent",void 0);h([m({type:b.Integer,converter:_e})],Qt.prototype,"prime1",void 0);h([m({type:b.Integer,converter:_e})],Qt.prototype,"prime2",void 0);h([m({type:b.Integer,converter:_e})],Qt.prototype,"exponent1",void 0);h([m({type:b.Integer,converter:_e})],Qt.prototype,"exponent2",void 0);h([m({type:b.Integer,converter:_e})],Qt.prototype,"coefficient",void 0);h([m({type:qd,optional:!0})],Qt.prototype,"otherPrimeInfos",void 0);class xp{constructor(e={}){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.Integer,converter:_e})],xp.prototype,"modulus",void 0);h([m({type:b.Integer,converter:_e})],xp.prototype,"publicExponent",void 0);var Fd;(function(t){t[t.Transient=0]="Transient",t[t.Singleton=1]="Singleton",t[t.ResolutionScoped=2]="ResolutionScoped",t[t.ContainerScoped=3]="ContainerScoped"})(Fd||(Fd={}));const tt=Fd;var Hd=function(t,e){return Hd=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},Hd(t,e)};function Sp(t,e){Hd(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function X4(t,e,n,r){function i(s){return s instanceof n?s:new n(function(a){a(s)})}return new(n||(n=Promise))(function(s,a){function c(u){try{d(r.next(u))}catch(f){a(f)}}function l(u){try{d(r.throw(u))}catch(f){a(f)}}function d(u){u.done?s(u.value):i(u.value).then(c,l)}d((r=r.apply(t,[])).next())})}function Z4(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,a;return a={next:c(0),throw:c(1),return:c(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function c(d){return function(u){return l([d,u])}}function l(d){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(s=d[0]&2?i.return:d[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,d[1])).done)return s;switch(i=0,s&&(d=[d[0]&2,s.value]),d[0]){case 0:case 1:s=d;break;case 4:return n.label++,{value:d[1],done:!1};case 5:n.label++,i=d[1],d=[0];continue;case 7:d=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(d[0]===6||d[0]===2)){n=0;continue}if(d[0]===3&&(!s||d[1]>s[0]&&d[1]<s[3])){n.label=d[1];break}if(d[0]===6&&n.label<s[1]){n.label=s[1],s=d;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(d);break}s[2]&&n.ops.pop(),n.trys.pop();continue}d=e.call(t,n)}catch(u){d=[6,u],i=0}finally{r=s=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}function _s(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Oa(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,s=[],a;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(c){a={error:c}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s}function Wn(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Oa(arguments[e]));return t}var Y4="injectionTokens";function Q4(t){var e=Reflect.getMetadata("design:paramtypes",t)||[],n=Reflect.getOwnMetadata(Y4,t)||{};return Object.keys(n).forEach(function(r){e[+r]=n[r]}),e}function e1(t){return!!t.useClass}function Vd(t){return!!t.useFactory}var t1=(function(){function t(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return t.prototype.createProxy=function(e){var n=this,r={},i=!1,s,a=function(){return i||(s=e(n.wrap()),i=!0),s};return new Proxy(r,this.createHandler(a))},t.prototype.createHandler=function(e){var n={},r=function(i){n[i]=function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];s[0]=e();var c=Reflect[i];return c.apply(void 0,Wn(s))}};return this.reflectMethods.forEach(r),n},t})();function Cr(t){return typeof t=="string"||typeof t=="symbol"}function e$(t){return typeof t=="object"&&"token"in t&&"multiple"in t}function Nh(t){return typeof t=="object"&&"token"in t&&"transform"in t}function t$(t){return typeof t=="function"||t instanceof t1}function Is(t){return!!t.useToken}function js(t){return t.useValue!=null}function n$(t){return e1(t)||js(t)||Is(t)||Vd(t)}var zp=(function(){function t(){this._registryMap=new Map}return t.prototype.entries=function(){return this._registryMap.entries()},t.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},t.prototype.get=function(e){this.ensure(e);var n=this._registryMap.get(e);return n[n.length-1]||null},t.prototype.set=function(e,n){this.ensure(e),this._registryMap.get(e).push(n)},t.prototype.setAll=function(e,n){this._registryMap.set(e,n)},t.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},t.prototype.clear=function(){this._registryMap.clear()},t.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},t})(),r$=(function(t){Sp(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(zp),ys=(function(){function t(){this.scopedResolutions=new Map}return t})();function i$(t,e){if(t===null)return"at position #"+e;var n=t.split(",")[e].trim();return'"'+n+'" at position #'+e}function o$(t,e,n){return n===void 0&&(n=" "),Wn([t],e.message.split(`
71
+ `)}`:`${n} :`}}q_=Ze;D.Constructed=q_;Ze.NAME="CONSTRUCTED";class F_ extends Ye{fromBER(e,n,r){return n}toBER(e){return Xt}}F_.override="EndOfContentValueBlock";var H_;class Ku extends Me{constructor(e={}){super(e,F_),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}H_=Ku;D.EndOfContent=H_;Ku.NAME=$o;var V_;class lr extends Me{constructor(e={}){super(e,Ye),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,n,r){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=r,n+r>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):n+r}toBER(e,n){const r=new ArrayBuffer(2);if(!e){const i=new Uint8Array(r);i[0]=5,i[1]=0}return n&&n.write(r),r}onAsciiEncoding(){return`${this.constructor.NAME}`}}V_=lr;D.Null=V_;lr.NAME="NULL";class K_ extends Zt(Ye){get value(){for(const e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...n}={}){super(n),n.valueHex?this.valueHexView=T.toUint8Array(n.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,n,r){const i=T.toUint8Array(e);return yn(this,i,n,r)?(this.valueHexView=i.subarray(n,n+r),r>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,O_.call(this),this.blockLength=r,n+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}K_.NAME="BooleanValueBlock";var G_;let ac=class extends Me{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,K_),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};G_=ac;D.Boolean=G_;ac.NAME="BOOLEAN";class W_ extends Zt(In){constructor({isConstructed:e=!1,...n}={}){super(n),this.isConstructed=e}fromBER(e,n,r){let i=0;if(this.isConstructed){if(this.isHexOnly=!1,i=In.prototype.fromBER.call(this,e,n,r),i===-1)return i;for(let s=0;s<this.value.length;s++){const a=this.value[s].constructor.NAME;if(a===$o){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==T_)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,i=super.fromBER(e,n,r),this.blockLength=r;return i}toBER(e,n){return this.isConstructed?In.prototype.toBER.call(this,e,n):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}W_.NAME="OctetStringValueBlock";var Gu;let rr=class extends Me{constructor({idBlock:e={},lenBlock:n={},...r}={}){var i,s;(i=r.isConstructed)!==null&&i!==void 0||(r.isConstructed=!!(!((s=r.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...n,isIndefiniteForm:!!r.isIndefiniteForm},...r},W_),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,n,r){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,r===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),n;if(!this.valueBlock.isConstructed){const s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(n,n+r);try{if(s.byteLength){const a=mi(s,0,s.byteLength);a.offset!==-1&&a.offset===r&&(this.valueBlock.value=[a.result])}}catch{}}return super.fromBER(e,n,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Ze.prototype.onAsciiEncoding.call(this);const e=this.constructor.NAME,n=F.ToHex(this.valueBlock.valueHexView);return`${e} : ${n}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;const e=[];for(const n of this.valueBlock.value)n instanceof Gu&&e.push(n.valueBlock.valueHexView);return T.concat(e)}};Gu=rr;D.OctetString=Gu;rr.NAME=T_;class J_ extends Zt(In){constructor({unusedBits:e=0,isConstructed:n=!1,...r}={}){super(r),this.unusedBits=e,this.isConstructed=n,this.blockLength=this.valueHexView.byteLength}fromBER(e,n,r){if(!r)return n;let i=-1;if(this.isConstructed){if(i=In.prototype.fromBER.call(this,e,n,r),i===-1)return i;for(const c of this.value){const l=c.constructor.NAME;if(l===$o){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(l!==R_)return this.error="BIT STRING may consists of BIT STRINGs only",-1;const d=c.valueBlock;if(this.unusedBits>0&&d.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=d.unusedBits}return i}const s=T.toUint8Array(e);if(!yn(this,s,n,r))return-1;const a=s.subarray(n,n+r);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const c=a.subarray(1);try{if(c.byteLength){const l=mi(c,0,c.byteLength);l.offset!==-1&&l.offset===r-1&&(this.value=[l.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,n+r}toBER(e,n){if(this.isConstructed)return In.prototype.toBER.call(this,e,n);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){const i=new Uint8Array(1);return i[0]=0,i.buffer}const r=new Uint8Array(this.valueHexView.length+1);return r[0]=this.unusedBits,r.set(this.valueHexView,1),r.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}J_.NAME="BitStringValueBlock";var X_;let ir=class extends Me{constructor({idBlock:e={},lenBlock:n={},...r}={}){var i,s;(i=r.isConstructed)!==null&&i!==void 0||(r.isConstructed=!!(!((s=r.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...n,isIndefiniteForm:!!r.isIndefiniteForm},...r},J_),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,n,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,n,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Ze.prototype.onAsciiEncoding.call(this);{const e=[],n=this.valueBlock.valueHexView;for(const a of n)e.push(a.toString(2).padStart(8,"0"));const r=e.join(""),i=this.constructor.NAME,s=r.substring(0,r.length-this.valueBlock.unusedBits);return`${i} : ${s}`}}};X_=ir;D.BitString=X_;ir.NAME=R_;var Z_;function Q3(t,e){const n=new Uint8Array([0]),r=new Uint8Array(t),i=new Uint8Array(e);let s=r.slice(0);const a=s.length-1,c=i.slice(0),l=c.length-1;let d=0;const u=l<a?a:l;let f=0;for(let g=u;g>=0;g--,f++)!0===f<c.length?d=s[a-f]+c[l-f]+n[0]:d=s[a-f]+n[0],n[0]=d/10,!0===f>=s.length?s=Jl(new Uint8Array([d%10]),s):s[a-f]=d%10;return n[0]>0&&(s=Jl(n,s)),s}function dh(t){if(t>=Ii.length)for(let e=Ii.length;e<=t;e++){const n=new Uint8Array([0]);let r=Ii[e-1].slice(0);for(let i=r.length-1;i>=0;i--){const s=new Uint8Array([(r[i]<<1)+n[0]]);n[0]=s[0]/10,r[i]=s[0]%10}n[0]>0&&(r=Jl(n,r)),Ii.push(r)}return Ii[t]}function e4(t,e){let n=0;const r=new Uint8Array(t),i=new Uint8Array(e),s=r.slice(0),a=s.length-1,c=i.slice(0),l=c.length-1;let d,u=0;for(let f=l;f>=0;f--,u++)d=s[a-u]-c[l-u]-n,!0===d<0?(n=1,s[a-u]=d+10):(n=0,s[a-u]=d);if(n>0)for(let f=a-l+1;f>=0;f--,u++)if(d=s[a-u]-n,d<0)n=1,s[a-u]=d+10;else{n=0,s[a-u]=d;break}return s.slice()}class Wu extends Zt(Ye){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=O_.call(this)))}constructor({value:e,...n}={}){super(n),this._valueDec=0,n.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(M3(e))}get valueDec(){return this._valueDec}fromDER(e,n,r,i=0){const s=this.fromBER(e,n,r);if(s===-1)return s;const a=this.valueHexView;return a[0]===0&&(a[1]&128)!==0?this.valueHexView=a.subarray(1):i!==0&&a.length<i&&(i-a.length>1&&(i=a.length+1),this.valueHexView=a.subarray(i-a.length)),s}toDER(e=!1){const n=this.valueHexView;switch(!0){case(n[0]&128)!==0:{const r=new Uint8Array(this.valueHexView.length+1);r[0]=0,r.set(n,1),this.valueHexView=r}break;case(n[0]===0&&(n[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,n,r){const i=super.fromBER(e,n,r);return i===-1||this.setValueHex(),i}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){const e=this.valueHexView.length*8-1;let n=new Uint8Array(this.valueHexView.length*8/3),r=0,i;const s=this.valueHexView;let a="",c=!1;for(let l=s.byteLength-1;l>=0;l--){i=s[l];for(let d=0;d<8;d++)(i&1)===1&&(r===e?(n=e4(dh(r),n),a="-"):n=Q3(n,dh(r))),r++,i>>=1}for(let l=0;l<n.length;l++)n[l]&&(c=!0),c&&(a+=ch.charAt(n[l]));return c===!1&&(a+=ch.charAt(0)),a}}Z_=Wu;Wu.NAME="IntegerValueBlock";Object.defineProperty(Z_.prototype,"valueHex",{set:function(t){this.valueHexView=new Uint8Array(t),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var ao;class _i extends Me{constructor(e={}){super(e,Wu),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return sa(),BigInt(this.valueBlock.toString())}static fromBigInt(e){sa();const n=BigInt(e),r=new oc,i=n.toString(16).replace(/^-/,""),s=new Uint8Array(F.FromHex(i));if(n<0){const c=new Uint8Array(s.length+(s[0]&128?1:0));c[0]|=128;const d=BigInt(`0x${F.ToHex(c)}`)+n,u=T.toUint8Array(F.FromHex(d.toString(16)));u[0]|=128,r.write(u)}else s[0]&128&&r.write(new Uint8Array([0])),r.write(s);return new ao({valueHex:r.final()})}convertToDER(){const e=new ao({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new ao({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}ao=_i;D.Integer=ao;_i.NAME="INTEGER";var Y_;class cc extends _i{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}Y_=cc;D.Enumerated=Y_;cc.NAME="ENUMERATED";class Xl extends Zt(Ye){constructor({valueDec:e=-1,isFirstSid:n=!1,...r}={}){super(r),this.valueDec=e,this.isFirstSid=n}fromBER(e,n,r){if(!r)return n;const i=T.toUint8Array(e);if(!yn(this,i,n,r))return-1;const s=i.subarray(n,n+r);this.valueHexView=new Uint8Array(r);for(let c=0;c<r&&(this.valueHexView[c]=s[c]&127,this.blockLength++,(s[c]&128)!==0);c++);const a=new Uint8Array(this.blockLength);for(let c=0;c<this.blockLength;c++)a[c]=this.valueHexView[c];return this.valueHexView=a,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Yr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),n+this.blockLength)}set valueBigInt(e){sa();let n=BigInt(e).toString(2);for(;n.length%7;)n="0"+n;const r=new Uint8Array(n.length/7);for(let i=0;i<r.length;i++)r[i]=parseInt(n.slice(i*7,i*7+7),2)+(i+1<r.length?128:0);this.fromBER(r.buffer,0,r.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const i=this.valueHexView,s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength-1;a++)s[a]=i[a]|128;return s[this.blockLength-1]=i[this.blockLength-1],s.buffer}const n=cr(this.valueDec,7);if(n.byteLength===0)return this.error="Error during encoding SID value",Xt;const r=new Uint8Array(n.byteLength);if(!e){const i=new Uint8Array(n),s=n.byteLength-1;for(let a=0;a<s;a++)r[a]=i[a]|128;r[s]=i[s]}return r}toString(){let e="";if(this.isHexOnly)e=F.ToHex(this.valueHexView);else if(this.isFirstSid){let n=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",n-=40):(e="2.",n-=80),e+=n.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}}Xl.NAME="sidBlock";class Q_ extends Ye{constructor({value:e=nt,...n}={}){super(n),this.value=[],e&&this.fromString(e)}fromBER(e,n,r){let i=n;for(;r>0;){const s=new Xl;if(i=s.fromBER(e,i,r),i===-1)return this.blockLength=0,this.error=s.error,i;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,r-=s.blockLength,this.value.push(s)}return i}toBER(e){const n=[];for(let r=0;r<this.value.length;r++){const i=this.value[r].toBER(e);if(i.byteLength===0)return this.error=this.value[r].error,Xt;n.push(i)}return Hu(n)}fromString(e){this.value=[];let n=0,r=0,i="",s=!1;do if(r=e.indexOf(".",n),r===-1?i=e.substring(n):i=e.substring(n,r),n=r+1,s){const a=this.value[0];let c=0;switch(a.valueDec){case 0:break;case 1:c=40;break;case 2:c=80;break;default:this.value=[];return}const l=parseInt(i,10);if(isNaN(l))return;a.valueDec=l+c,s=!1}else{const a=new Xl;if(i>Number.MAX_SAFE_INTEGER){sa();const c=BigInt(i);a.valueBigInt=c}else if(a.valueDec=parseInt(i,10),isNaN(a.valueDec))return;this.value.length||(a.isFirstSid=!0,s=!0),this.value.push(a)}while(r!==-1)}toString(){let e="",n=!1;for(let r=0;r<this.value.length;r++){n=this.value[r].isHexOnly;let i=this.value[r].toString();r!==0&&(e=`${e}.`),n?(i=`{${i}}`,this.value[r].isFirstSid?e=`2.{${i} - 80}`:e+=i):e+=i}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let n=0;n<this.value.length;n++)e.sidArray.push(this.value[n].toJSON());return e}}Q_.NAME="ObjectIdentifierValueBlock";var ey;class lc extends Me{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Q_),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}ey=lc;D.ObjectIdentifier=ey;lc.NAME="OBJECT IDENTIFIER";class Zl extends Zt(xr){constructor({valueDec:e=0,...n}={}){super(n),this.valueDec=e}fromBER(e,n,r){if(r===0)return n;const i=T.toUint8Array(e);if(!yn(this,i,n,r))return-1;const s=i.subarray(n,n+r);this.valueHexView=new Uint8Array(r);for(let c=0;c<r&&(this.valueHexView[c]=s[c]&127,this.blockLength++,(s[c]&128)!==0);c++);const a=new Uint8Array(this.blockLength);for(let c=0;c<this.blockLength;c++)a[c]=this.valueHexView[c];return this.valueHexView=a,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Yr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),n+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const i=this.valueHexView,s=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength-1;a++)s[a]=i[a]|128;return s[this.blockLength-1]=i[this.blockLength-1],s.buffer}const n=cr(this.valueDec,7);if(n.byteLength===0)return this.error="Error during encoding SID value",Xt;const r=new Uint8Array(n.byteLength);if(!e){const i=new Uint8Array(n),s=n.byteLength-1;for(let a=0;a<s;a++)r[a]=i[a]|128;r[s]=i[s]}return r.buffer}toString(){let e="";return this.isHexOnly?e=F.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Zl.NAME="relativeSidBlock";class ty extends Ye{constructor({value:e=nt,...n}={}){super(n),this.value=[],e&&this.fromString(e)}fromBER(e,n,r){let i=n;for(;r>0;){const s=new Zl;if(i=s.fromBER(e,i,r),i===-1)return this.blockLength=0,this.error=s.error,i;this.blockLength+=s.blockLength,r-=s.blockLength,this.value.push(s)}return i}toBER(e,n){const r=[];for(let i=0;i<this.value.length;i++){const s=this.value[i].toBER(e);if(s.byteLength===0)return this.error=this.value[i].error,Xt;r.push(s)}return Hu(r)}fromString(e){this.value=[];let n=0,r=0,i="";do{r=e.indexOf(".",n),r===-1?i=e.substring(n):i=e.substring(n,r),n=r+1;const s=new Zl;if(s.valueDec=parseInt(i,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(r!==-1);return!0}toString(){let e="",n=!1;for(let r=0;r<this.value.length;r++){n=this.value[r].isHexOnly;let i=this.value[r].toString();r!==0&&(e=`${e}.`),n&&(i=`{${i}}`),e+=i}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let n=0;n<this.value.length;n++)e.sidArray.push(this.value[n].toJSON());return e}}ty.NAME="RelativeObjectIdentifierValueBlock";var ny;class Ju extends Me{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,ty),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}ny=Ju;D.RelativeObjectIdentifier=ny;Ju.NAME="RelativeObjectIdentifier";var ry;class It extends Ze{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}ry=It;D.Sequence=ry;It.NAME="SEQUENCE";var iy;let Kt=class extends Ze{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};iy=Kt;D.Set=iy;Kt.NAME="SET";class oy extends Zt(Ye){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=nt}toJSON(){return{...super.toJSON(),value:this.value}}}oy.NAME="StringValueBlock";class sy extends oy{}sy.NAME="SimpleStringValueBlock";class dt extends Vu{constructor({...e}={}){super(e,sy)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,T.toUint8Array(e))}fromString(e){const n=e.length,r=this.valueBlock.valueHexView=new Uint8Array(n);for(let i=0;i<n;i++)r[i]=e.charCodeAt(i);this.valueBlock.value=e}}dt.NAME="SIMPLE STRING";class ay extends dt{fromBuffer(e){this.valueBlock.valueHexView=T.toUint8Array(e);try{this.valueBlock.value=F.ToUtf8String(e)}catch(n){this.warnings.push(`Error during "decodeURIComponent": ${n}, using raw string`),this.valueBlock.value=F.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(F.FromUtf8String(e)),this.valueBlock.value=e}}ay.NAME="Utf8StringValueBlock";var cy;class wn extends ay{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}cy=wn;D.Utf8String=cy;wn.NAME="UTF8String";class ly extends dt{fromBuffer(e){this.valueBlock.value=F.ToUtf16String(e),this.valueBlock.valueHexView=T.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(F.FromUtf16String(e))}}ly.NAME="BmpStringValueBlock";var dy;class dc extends ly{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}dy=dc;D.BmpString=dy;dc.NAME="BMPString";class uy extends dt{fromBuffer(e){const n=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),r=new Uint8Array(n);for(let i=0;i<r.length;i+=4)r[i]=r[i+3],r[i+1]=r[i+2],r[i+2]=0,r[i+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(n))}fromString(e){const n=e.length,r=this.valueBlock.valueHexView=new Uint8Array(n*4);for(let i=0;i<n;i++){const s=cr(e.charCodeAt(i),8),a=new Uint8Array(s);if(a.length>4)continue;const c=4-a.length;for(let l=a.length-1;l>=0;l--)r[i*4+l+c]=a[l]}this.valueBlock.value=e}}uy.NAME="UniversalStringValueBlock";var py;class uc extends uy{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}py=uc;D.UniversalString=py;uc.NAME="UniversalString";var fy;class pc extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}fy=pc;D.NumericString=fy;pc.NAME="NumericString";var hy;class fc extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}hy=fc;D.PrintableString=hy;fc.NAME="PrintableString";var gy;class hc extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}gy=hc;D.TeletexString=gy;hc.NAME="TeletexString";var my;class gc extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}my=gc;D.VideotexString=my;gc.NAME="VideotexString";var _y;class mc extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}_y=mc;D.IA5String=_y;mc.NAME="IA5String";var yy;class _c extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}yy=_c;D.GraphicString=yy;_c.NAME="GraphicString";var wy;class Go extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}wy=Go;D.VisibleString=wy;Go.NAME="VisibleString";var by;class yc extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}by=yc;D.GeneralString=by;yc.NAME="GeneralString";var vy;class wc extends dt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}vy=wc;D.CharacterString=vy;wc.NAME="CharacterString";var $y;class Wo extends Go{constructor({value:e,valueDate:n,...r}={}){if(super(r),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let i=0;i<e.length;i++)this.valueBlock.valueHexView[i]=e.charCodeAt(i)}n&&(this.fromDate(n),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,T.toUint8Array(e)))}toBuffer(){const e=this.toString(),n=new ArrayBuffer(e.length),r=new Uint8Array(n);for(let i=0;i<e.length;i++)r[i]=e.charCodeAt(i);return n}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){const r=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(r===null){this.error="Wrong input string for conversion";return}const i=parseInt(r[1],10);i>=50?this.year=1900+i:this.year=2e3+i,this.month=parseInt(r[2],10),this.day=parseInt(r[3],10),this.hour=parseInt(r[4],10),this.minute=parseInt(r[5],10),this.second=parseInt(r[6],10)}toString(e="iso"){if(e==="iso"){const n=new Array(7);return n[0]=at(this.year<2e3?this.year-1900:this.year-2e3,2),n[1]=at(this.month,2),n[2]=at(this.day,2),n[3]=at(this.hour,2),n[4]=at(this.minute,2),n[5]=at(this.second,2),n[6]="Z",n.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}}$y=Wo;D.UTCTime=$y;Wo.NAME="UTCTime";var ky;class bc extends Wo{constructor(e={}){var n;super(e),(n=this.millisecond)!==null&&n!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){const e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let n=!1,r="",i="",s=0,a,c=0,l=0;if(e[e.length-1]==="Z")r=e.substring(0,e.length-1),n=!0;else{const f=new Number(e[e.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");r=e}if(n){if(r.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(r.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,g=r.indexOf("+"),_="";if(g===-1&&(g=r.indexOf("-"),f=-1),g!==-1){if(_=r.substring(g+1),r=r.substring(0,g),_.length!==2&&_.length!==4)throw new Error("Wrong input string for conversion");let w=parseInt(_.substring(0,2),10);if(isNaN(w.valueOf()))throw new Error("Wrong input string for conversion");if(c=f*w,_.length===4){if(w=parseInt(_.substring(2,4),10),isNaN(w.valueOf()))throw new Error("Wrong input string for conversion");l=f*w}}}let d=r.indexOf(".");if(d===-1&&(d=r.indexOf(",")),d!==-1){const f=new Number(`0${r.substring(d)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");s=f.valueOf(),i=r.substring(0,d)}else i=r;switch(!0){case i.length===8:if(a=/(\d{4})(\d{2})(\d{2})/ig,d!==-1)throw new Error("Wrong input string for conversion");break;case i.length===10:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,d!==-1){let f=60*s;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case i.length===12:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,d!==-1){let f=60*s;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case i.length===14:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,d!==-1){const f=1e3*s;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}const u=a.exec(i);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+c;break;case 5:this.minute=parseInt(u[f],10)+l;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(n===!1){const f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){const n=[];return n.push(at(this.year,4)),n.push(at(this.month,2)),n.push(at(this.day,2)),n.push(at(this.hour,2)),n.push(at(this.minute,2)),n.push(at(this.second,2)),this.millisecond!==0&&(n.push("."),n.push(at(this.millisecond,3))),n.push("Z"),n.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}ky=bc;D.GeneralizedTime=ky;bc.NAME="GeneralizedTime";var xy;class Xu extends wn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}xy=Xu;D.DATE=xy;Xu.NAME="DATE";var Sy;class Zu extends wn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}Sy=Zu;D.TimeOfDay=Sy;Zu.NAME="TimeOfDay";var zy;class Yu extends wn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}zy=Yu;D.DateTime=zy;Yu.NAME="DateTime";var Ay;class Qu extends wn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}Ay=Qu;D.Duration=Ay;Qu.NAME="Duration";var Ey;class ep extends wn{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}Ey=ep;D.TIME=Ey;ep.NAME="TIME";class dr{constructor({name:e=nt,optional:n=!1}={}){this.name=e,this.optional=n}}class tp extends dr{constructor({value:e=[],...n}={}){super(n),this.value=e}}class aa extends dr{constructor({value:e=new dr,local:n=!1,...r}={}){super(r),this.value=e,this.local=n}}class t4{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=T.toUint8Array(e)}constructor({data:e=sc}={}){this.dataView=T.toUint8Array(e)}fromBER(e,n,r){const i=n+r;return this.dataView=T.toUint8Array(e).subarray(n,i),i}toBER(e){return this.dataView.slice().buffer}}function An(t,e,n){if(n instanceof tp){for(const s of n.value)if(An(t,e,s).verified)return{verified:!0,result:t};{const s={verified:!1,result:{error:"Wrong values for Choice type"}};return n.hasOwnProperty(fl)&&(s.name=n.name),s}}if(n instanceof dr)return n.hasOwnProperty(fl)&&(t[n.name]=e),{verified:!0,result:t};if(!(t instanceof Object))return{verified:!1,result:{error:"Wrong root object"}};if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(!(n instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(H3 in n))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(W3 in n.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(J3 in n.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const r=n.idBlock.toBER(!1);if(r.byteLength===0)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(n.idBlock.fromBER(r,0,r.byteLength)===-1)return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(n.idBlock.hasOwnProperty(V3)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(n.idBlock.tagClass!==e.idBlock.tagClass)return{verified:!1,result:t};if(n.idBlock.hasOwnProperty(K3)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(n.idBlock.tagNumber!==e.idBlock.tagNumber)return{verified:!1,result:t};if(n.idBlock.hasOwnProperty(G3)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(n.idBlock.isConstructed!==e.idBlock.isConstructed)return{verified:!1,result:t};if(!(F3 in n.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(n.idBlock.isHexOnly!==e.idBlock.isHexOnly)return{verified:!1,result:t};if(n.idBlock.isHexOnly){if(!(lh in n.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const s=n.idBlock.valueHexView,a=e.idBlock.valueHexView;if(s.length!==a.length)return{verified:!1,result:t};for(let c=0;c<s.length;c++)if(s[c]!==a[1])return{verified:!1,result:t}}if(n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,nt),n.name&&(t[n.name]=e)),n instanceof D.Constructed){let s=0,a={verified:!1,result:{error:"Unknown error"}},c=n.valueBlock.value.length;if(c>0&&n.valueBlock.value[0]instanceof aa&&(c=e.valueBlock.value.length),c===0)return{verified:!0,result:t};if(e.valueBlock.value.length===0&&n.valueBlock.value.length!==0){let l=!0;for(let d=0;d<n.valueBlock.value.length;d++)l=l&&(n.valueBlock.value[d].optional||!1);return l?{verified:!0,result:t}:(n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,nt),n.name&&delete t[n.name]),t.error="Inconsistent object length",{verified:!1,result:t})}for(let l=0;l<c;l++)if(l-s>=e.valueBlock.value.length){if(n.valueBlock.value[l].optional===!1){const d={verified:!1,result:t};return t.error="Inconsistent length between ASN.1 data and schema",n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,nt),n.name&&(delete t[n.name],d.name=n.name)),d}}else if(n.valueBlock.value[0]instanceof aa){if(a=An(t,e.valueBlock.value[l],n.valueBlock.value[0].value),a.verified===!1)if(n.valueBlock.value[0].optional)s++;else return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,nt),n.name&&delete t[n.name]),a;if(fl in n.valueBlock.value[0]&&n.valueBlock.value[0].name.length>0){let d={};X3 in n.valueBlock.value[0]&&n.valueBlock.value[0].local?d=e:d=t,typeof d[n.valueBlock.value[0].name]>"u"&&(d[n.valueBlock.value[0].name]=[]),d[n.valueBlock.value[0].name].push(e.valueBlock.value[l])}}else if(a=An(t,e.valueBlock.value[l-s],n.valueBlock.value[l]),a.verified===!1)if(n.valueBlock.value[l].optional)s++;else return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,nt),n.name&&delete t[n.name]),a;if(a.verified===!1){const l={verified:!1,result:t};return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,nt),n.name&&(delete t[n.name],l.name=n.name)),l}return{verified:!0,result:t}}if(n.primitiveSchema&&lh in e.valueBlock){const s=mi(e.valueBlock.valueHexView);if(s.offset===-1){const a={verified:!1,result:s.result};return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,nt),n.name&&(delete t[n.name],a.name=n.name)),a}return An(t,s.result,n.primitiveSchema)}return{verified:!0,result:t}}function n4(t,e){if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const n=mi(T.toUint8Array(t));return n.offset===-1?{verified:!1,result:n.result}:An(n.result,n.result,e)}const Cy=Object.freeze(Object.defineProperty({__proto__:null,Any:dr,BaseBlock:Me,BaseStringBlock:Vu,BitString:ir,BmpString:dc,Boolean:ac,CharacterString:wc,Choice:tp,Constructed:Ze,DATE:Xu,DateTime:Yu,Duration:Qu,EndOfContent:Ku,Enumerated:cc,GeneralString:yc,GeneralizedTime:bc,GraphicString:_c,HexBlock:Zt,IA5String:mc,Integer:_i,Null:lr,NumericString:pc,ObjectIdentifier:lc,OctetString:rr,Primitive:Ko,PrintableString:fc,RawData:t4,RelativeObjectIdentifier:Ju,Repeated:aa,Sequence:It,Set:Kt,TIME:ep,TeletexString:hc,TimeOfDay:Zu,UTCTime:Wo,UniversalString:uc,Utf8String:wn,ValueBlock:Ye,VideotexString:gc,ViewWriter:oc,VisibleString:Go,compareSchema:An,fromBER:Hr,verifySchema:n4},Symbol.toStringTag,{value:"Module"}));var C;(function(t){t[t.Sequence=0]="Sequence",t[t.Set=1]="Set",t[t.Choice=2]="Choice"})(C||(C={}));var b;(function(t){t[t.Any=1]="Any",t[t.Boolean=2]="Boolean",t[t.OctetString=3]="OctetString",t[t.BitString=4]="BitString",t[t.Integer=5]="Integer",t[t.Enumerated=6]="Enumerated",t[t.ObjectIdentifier=7]="ObjectIdentifier",t[t.Utf8String=8]="Utf8String",t[t.BmpString=9]="BmpString",t[t.UniversalString=10]="UniversalString",t[t.NumericString=11]="NumericString",t[t.PrintableString=12]="PrintableString",t[t.TeletexString=13]="TeletexString",t[t.VideotexString=14]="VideotexString",t[t.IA5String=15]="IA5String",t[t.GraphicString=16]="GraphicString",t[t.VisibleString=17]="VisibleString",t[t.GeneralString=18]="GeneralString",t[t.CharacterString=19]="CharacterString",t[t.UTCTime=20]="UTCTime",t[t.GeneralizedTime=21]="GeneralizedTime",t[t.DATE=22]="DATE",t[t.TimeOfDay=23]="TimeOfDay",t[t.DateTime=24]="DateTime",t[t.Duration=25]="Duration",t[t.TIME=26]="TIME",t[t.Null=27]="Null"})(b||(b={}));class vc{constructor(e,n=0){if(this.unusedBits=0,this.value=new ArrayBuffer(0),e)if(typeof e=="number")this.fromNumber(e);else if(T.isBufferSource(e))this.unusedBits=n,this.value=T.toArrayBuffer(e);else throw TypeError("Unsupported type of 'params' argument for BitString")}fromASN(e){if(!(e instanceof ir))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=e.valueBlock.valueHex,this}toASN(){return new ir({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new ir({name:e})}toNumber(){let e="";const n=new Uint8Array(this.value);for(const r of n)e+=r.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let n=e.toString(2);const r=n.length+7>>3;this.unusedBits=(r<<3)-n.length;const i=new Uint8Array(r);n=n.padStart(r<<3,"0").split("").reverse().join("");let s=0;for(;s<r;)i[s]=parseInt(n.slice(s<<3,(s<<3)+8),2),s++;this.value=i.buffer}}class ae{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){typeof e=="number"?this.buffer=new ArrayBuffer(e):T.isBufferSource(e)?this.buffer=T.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof rr))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new rr({valueHex:this.buffer})}toSchema(e){return new rr({name:e})}}const r4={fromASN:t=>t instanceof lr?null:t.valueBeforeDecodeView,toASN:t=>{if(t===null)return new lr;const e=Hr(t);if(e.result.error)throw new Error(e.result.error);return e.result}},i4={fromASN:t=>t.valueBlock.valueHexView.byteLength>=4?t.valueBlock.toString():t.valueBlock.valueDec,toASN:t=>new _i({value:+t})},o4={fromASN:t=>t.valueBlock.valueDec,toASN:t=>new cc({value:t})},_e={fromASN:t=>t.valueBlock.valueHexView,toASN:t=>new _i({valueHex:t})},s4={fromASN:t=>t.valueBlock.valueHexView,toASN:t=>new ir({valueHex:t})},a4={fromASN:t=>t.valueBlock.toString(),toASN:t=>new lc({value:t})},c4={fromASN:t=>t.valueBlock.value,toASN:t=>new ac({value:t})},ca={fromASN:t=>t.valueBlock.valueHexView,toASN:t=>new rr({valueHex:t})},l4={fromASN:t=>new ae(t.getValue()),toASN:t=>t.toASN()};function bt(t){return{fromASN:e=>e.valueBlock.value,toASN:e=>new t({value:e})}}const Ny=bt(wn),d4=bt(dc),u4=bt(uc),p4=bt(pc),f4=bt(fc),h4=bt(hc),g4=bt(gc),m4=bt(mc),_4=bt(_c),y4=bt(Go),w4=bt(yc),b4=bt(wc),v4={fromASN:t=>t.toDate(),toASN:t=>new Wo({valueDate:t})},$4={fromASN:t=>t.toDate(),toASN:t=>new bc({valueDate:t})},k4={fromASN:()=>null,toASN:()=>new lr};function co(t){switch(t){case b.Any:return r4;case b.BitString:return s4;case b.BmpString:return d4;case b.Boolean:return c4;case b.CharacterString:return b4;case b.Enumerated:return o4;case b.GeneralString:return w4;case b.GeneralizedTime:return $4;case b.GraphicString:return _4;case b.IA5String:return m4;case b.Integer:return i4;case b.Null:return k4;case b.NumericString:return p4;case b.ObjectIdentifier:return a4;case b.OctetString:return ca;case b.PrintableString:return f4;case b.TeletexString:return h4;case b.UTCTime:return v4;case b.UniversalString:return u4;case b.Utf8String:return Ny;case b.VideotexString:return g4;case b.VisibleString:return y4;default:return null}}function ln(t){return typeof t=="function"&&t.prototype?t.prototype.toASN&&t.prototype.fromASN?!0:ln(t.prototype):!!(t&&typeof t=="object"&&"toASN"in t&&"fromASN"in t)}function Iy(t){var e;if(t){const n=Object.getPrototypeOf(t);return((e=n?.prototype)===null||e===void 0?void 0:e.constructor)===Array?!0:Iy(n)}return!1}function x4(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;const n=new Uint8Array(t),r=new Uint8Array(e);for(let i=0;i<t.byteLength;i++)if(n[i]!==r[i])return!1;return!0}class S4{constructor(){this.items=new WeakMap}has(e){return this.items.has(e)}get(e,n=!1){const r=this.items.get(e);if(!r)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(n&&!r.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return r}cache(e){const n=this.get(e);n.schema||(n.schema=this.create(e,!0))}createDefault(e){const n={type:C.Sequence,items:{}},r=this.findParentSchema(e);return r&&(Object.assign(n,r),n.items=Object.assign({},n.items,r.items)),n}create(e,n){const r=this.items.get(e)||this.createDefault(e),i=[];for(const s in r.items){const a=r.items[s],c=n?s:"";let l;if(typeof a.type=="number"){const u=b[a.type],f=Cy[u];if(!f)throw new Error(`Cannot get ASN1 class by name '${u}'`);l=new f({name:c})}else ln(a.type)?l=new a.type().toSchema(c):a.optional?this.get(a.type).type===C.Choice?l=new dr({name:c}):(l=this.create(a.type,!1),l.name=c):l=new dr({name:c});const d=!!a.optional||a.defaultValue!==void 0;if(a.repeated){l.name="";const u=a.repeated==="set"?Kt:It;l=new u({name:"",value:[new aa({name:c,value:l})]})}if(a.context!==null&&a.context!==void 0)if(a.implicit)if(typeof a.type=="number"||ln(a.type)){const u=a.repeated?Ze:Ko;i.push(new u({name:c,optional:d,idBlock:{tagClass:3,tagNumber:a.context}}))}else{this.cache(a.type);const u=!!a.repeated;let f=u?l:this.get(a.type,!0).schema;f="valueBlock"in f?f.valueBlock.value:f.value,i.push(new Ze({name:u?"":c,optional:d,idBlock:{tagClass:3,tagNumber:a.context},value:f}))}else i.push(new Ze({optional:d,idBlock:{tagClass:3,tagNumber:a.context},value:[l]}));else l.optional=d,i.push(l)}switch(r.type){case C.Sequence:return new It({value:i,name:""});case C.Set:return new Kt({value:i,name:""});case C.Choice:return new tp({value:i,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,n){return this.items.set(e,n),this}findParentSchema(e){const n=Object.getPrototypeOf(e);return n?this.items.get(n)||this.findParentSchema(n):null}}const Le=new S4,j=t=>e=>{let n;Le.has(e)?n=Le.get(e):(n=Le.createDefault(e),Le.set(e,n)),Object.assign(n,t)},m=t=>(e,n)=>{let r;Le.has(e.constructor)?r=Le.get(e.constructor):(r=Le.createDefault(e.constructor),Le.set(e.constructor,r));const i=Object.assign({},t);if(typeof i.type=="number"&&!i.converter){const s=co(t.type);if(!s)throw new Error(`Cannot get default converter for property '${n}' of ${e.constructor.name}`);i.converter=s}i.raw=t.raw,r.items[n]=i};class ji extends Error{constructor(){super(...arguments),this.schemas=[]}}class z4{static parse(e,n){const r=Hr(e);if(r.result.error)throw new Error(r.result.error);return this.fromASN(r.result,n)}static fromASN(e,n){try{if(ln(n))return new n().fromASN(e);const r=Le.get(n);Le.cache(n);let i=r.schema;const s=this.handleChoiceTypes(e,r,n,i);if(s?.result)return s.result;s?.targetSchema&&(i=s.targetSchema);const a=this.handleSequenceTypes(e,r,n,i),c=new n;return Iy(n)?this.handleArrayTypes(e,r,n):(this.processSchemaItems(r,a,c),c)}catch(r){throw r instanceof ji&&r.schemas.push(n.name),r}}static handleChoiceTypes(e,n,r,i){if(e.constructor===Ze&&n.type===C.Choice&&e.idBlock.tagClass===3)for(const s in n.items){const a=n.items[s];if(a.context===e.idBlock.tagNumber&&a.implicit&&typeof a.type=="function"&&Le.has(a.type)){const c=Le.get(a.type);if(c&&c.type===C.Sequence){const l=new It;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in l.valueBlock){l.valueBlock.value=e.valueBlock.value;const d=this.fromASN(l,a.type),u=new r;return u[s]=d,{result:u}}}}}else if(e.constructor===Ze&&n.type!==C.Choice){const s=new Ze({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:n.schema.valueBlock.value});for(const a in n.items)delete e[a];return{targetSchema:s}}return null}static handleSequenceTypes(e,n,r,i){if(n.type===C.Sequence){const s=An({},e,i);if(!s.verified)throw new ji(`Data does not match to ${r.name} ASN1 schema.${s.result.error?` ${s.result.error}`:""}`);return s}else{const s=An({},e,i);if(!s.verified)throw new ji(`Data does not match to ${r.name} ASN1 schema.${s.result.error?` ${s.result.error}`:""}`);return s}}static processRepeatedField(e,n,r){let i=e.slice(n);if(i.length===1&&i[0].constructor.name==="Sequence"){const s=i[0];s.valueBlock&&s.valueBlock.value&&Array.isArray(s.valueBlock.value)&&(i=s.valueBlock.value)}if(typeof r.type=="number"){const s=co(r.type);if(!s)throw new Error(`No converter for ASN.1 type ${r.type}`);return i.filter(a=>a&&a.valueBlock).map(a=>{try{return s.fromASN(a)}catch{return}}).filter(a=>a!==void 0)}else return i.filter(s=>s&&s.valueBlock).map(s=>{try{return this.fromASN(s,r.type)}catch{return}}).filter(s=>s!==void 0)}static processPrimitiveField(e,n){const r=co(n.type);if(!r)throw new Error(`No converter for ASN.1 type ${n.type}`);return r.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type=="function"&&Le.has(e.type)&&Le.get(e.type).type===C.Choice}static processOptionalChoiceField(e,n){try{return{processed:!0,value:this.fromASN(e,n.type)}}catch(r){if(r instanceof ji&&/Wrong values for Choice type/.test(r.message))return{processed:!1};throw r}}static handleArrayTypes(e,n,r){if(!("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const i=n.itemType;if(typeof i=="number"){const s=co(i);if(!s)throw new Error(`Cannot get default converter for array item of ${r.name} ASN1 schema`);return r.from(e.valueBlock.value,a=>s.fromASN(a))}else return r.from(e.valueBlock.value,s=>this.fromASN(s,i))}static processSchemaItems(e,n,r){for(const i in e.items){const s=n.result[i];if(!s)continue;const a=e.items[i],c=a.type;let l;typeof c=="number"||ln(c)?l=this.processPrimitiveSchemaItem(s,a,c):l=this.processComplexSchemaItem(s,a,c),l&&typeof l=="object"&&"value"in l&&"raw"in l?(r[i]=l.value,r[`${i}Raw`]=l.raw):r[i]=l}}static processPrimitiveSchemaItem(e,n,r){var i;const s=(i=n.converter)!==null&&i!==void 0?i:ln(r)?new r:null;if(!s)throw new Error("Converter is empty");return n.repeated?this.processRepeatedPrimitiveItem(e,n,s):this.processSinglePrimitiveItem(e,n,r,s)}static processRepeatedPrimitiveItem(e,n,r){if(n.implicit){const i=n.repeated==="sequence"?It:Kt,s=new i;s.valueBlock=e.valueBlock;const a=Hr(s.toBER(!1));if(a.offset===-1)throw new Error(`Cannot parse the child item. ${a.result.error}`);if(!("value"in a.result.valueBlock&&Array.isArray(a.result.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const c=a.result.valueBlock.value;return Array.from(c,l=>r.fromASN(l))}else return Array.from(e,i=>r.fromASN(i))}static processSinglePrimitiveItem(e,n,r,i){let s=e;if(n.implicit){let a;if(ln(r))a=new r().toSchema("");else{const c=b[r],l=Cy[c];if(!l)throw new Error(`Cannot get '${c}' class from asn1js module`);a=new l}a.valueBlock=s.valueBlock,s=Hr(a.toBER(!1)).result}return i.fromASN(s)}static processComplexSchemaItem(e,n,r){if(n.repeated){if(!Array.isArray(e))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");return Array.from(e,i=>this.fromASN(i,r))}else{const i=this.handleImplicitTagging(e,n,r);if(this.isOptionalChoiceField(n))try{return this.fromASN(i,r)}catch(s){if(s instanceof ji&&/Wrong values for Choice type/.test(s.message))return;throw s}else{const s=this.fromASN(i,r);return n.raw?{value:s,raw:e.valueBeforeDecodeView}:s}}}static handleImplicitTagging(e,n,r){if(n.implicit&&typeof n.context=="number"){const i=Le.get(r);if(i.type===C.Sequence){const s=new It;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in s.valueBlock)return s.valueBlock.value=e.valueBlock.value,s}else if(i.type===C.Set){const s=new Kt;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in s.valueBlock)return s.valueBlock.value=e.valueBlock.value,s}}return e}}class np{static serialize(e){return e instanceof Me?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&typeof e=="object"&&ln(e))return e.toASN();if(!(e&&typeof e=="object"))throw new TypeError("Parameter 1 should be type of Object.");const n=e.constructor,r=Le.get(n);Le.cache(n);let i=[];if(r.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if(typeof r.itemType=="number"){const a=co(r.itemType);if(!a)throw new Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);i=e.map(c=>a.toASN(c))}else i=e.map(a=>this.toAsnItem({type:r.itemType},"[]",n,a))}else for(const a in r.items){const c=r.items[a],l=e[a];if(l===void 0||c.defaultValue===l||typeof c.defaultValue=="object"&&typeof l=="object"&&x4(this.serialize(c.defaultValue),this.serialize(l)))continue;const d=np.toAsnItem(c,a,n,l);if(typeof c.context=="number")if(c.implicit)if(!c.repeated&&(typeof c.type=="number"||ln(c.type))){const u={};u.valueHex=d instanceof lr?d.valueBeforeDecodeView:d.valueBlock.toBER(),i.push(new Ko({optional:c.optional,idBlock:{tagClass:3,tagNumber:c.context},...u}))}else i.push(new Ze({optional:c.optional,idBlock:{tagClass:3,tagNumber:c.context},value:d.valueBlock.value}));else i.push(new Ze({optional:c.optional,idBlock:{tagClass:3,tagNumber:c.context},value:[d]}));else c.repeated?i=i.concat(d):i.push(d)}let s;switch(r.type){case C.Sequence:s=new It({value:i});break;case C.Set:s=new Kt({value:i});break;case C.Choice:if(!i[0])throw new Error(`Schema '${n.name}' has wrong data. Choice cannot be empty.`);s=i[0];break}return s}static toAsnItem(e,n,r,i){let s;if(typeof e.type=="number"){const a=e.converter;if(!a)throw new Error(`Property '${n}' doesn't have converter for type ${b[e.type]} in schema '${r.name}'`);if(e.repeated){if(!Array.isArray(i))throw new TypeError("Parameter 'objProp' should be type of Array.");const c=Array.from(i,d=>a.toASN(d)),l=e.repeated==="sequence"?It:Kt;s=new l({value:c})}else s=a.toASN(i)}else if(e.repeated){if(!Array.isArray(i))throw new TypeError("Parameter 'objProp' should be type of Array.");const a=Array.from(i,l=>this.toASN(l)),c=e.repeated==="sequence"?It:Kt;s=new c({value:a})}else s=this.toASN(i);return s}}class ue extends Array{constructor(e=[]){if(typeof e=="number")super(e);else{super();for(const n of e)this.push(n)}}}class O{static serialize(e){return np.serialize(e)}static parse(e,n){return z4.parse(e,n)}static toString(e){const n=T.isBufferSource(e)?T.toArrayBuffer(e):O.serialize(e),r=Hr(n);if(r.offset===-1)throw new Error(`Cannot decode ASN.1 data. ${r.result.error}`);return r.result.toString()}}function h(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var c=t.length-1;c>=0;c--)(a=t[c])&&(s=(i<3?a(s):i>3?a(e,n,s):a(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s}function re(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}function ye(t,e,n,r,i){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?i.call(t,n):i?i.value=n:e.set(t,n),n}class uh{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){const n=e.split(".");if(n.length!==4)throw new Error("Invalid IPv4 address");return n.map(r=>{const i=parseInt(r,10);if(isNaN(i)||i<0||i>255)throw new Error("Invalid IPv4 address part");return i})}static parseIPv6(e){const r=this.expandIPv6(e).split(":");if(r.length!==8)throw new Error("Invalid IPv6 address");return r.reduce((i,s)=>{const a=parseInt(s,16);if(isNaN(a)||a<0||a>65535)throw new Error("Invalid IPv6 address part");return i.push(a>>8&255),i.push(a&255),i},[])}static expandIPv6(e){if(!e.includes("::"))return e;const n=e.split("::");if(n.length>2)throw new Error("Invalid IPv6 address");const r=n[0]?n[0].split(":"):[],i=n[1]?n[1].split(":"):[],s=8-(r.length+i.length);if(s<0)throw new Error("Invalid IPv6 address");return[...r,...Array(s).fill("0"),...i].join(":")}static formatIPv6(e){const n=[];for(let r=0;r<16;r+=2)n.push((e[r]<<8|e[r+1]).toString(16));return this.compressIPv6(n.join(":"))}static compressIPv6(e){const n=e.split(":");let r=-1,i=0,s=-1,a=0;for(let c=0;c<n.length;c++)n[c]==="0"?(s===-1&&(s=c),a++):(a>i&&(r=s,i=a),s=-1,a=0);if(a>i&&(r=s,i=a),i>1){const c=n.slice(0,r).join(":"),l=n.slice(r+i).join(":");return`${c}::${l}`}return e}static parseCIDR(e){const[n,r]=e.split("/"),i=parseInt(r,10);if(this.isIPv4(n)){if(i<0||i>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(n),i]}else{if(i<0||i>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(n),i]}}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return"::/0";if(e.length!==16)return e;const n=parseInt(e.slice(8),16).toString(2).split("").reduce((i,s)=>i+ +s,0);let r=e.slice(0,8).replace(/(.{2})/g,i=>`${parseInt(i,16)}.`);return r=r.slice(0,-1),`${r}/${n}`}static toString(e){const n=new Uint8Array(e);if(n.length===4)return Array.from(n).join(".");if(n.length===16)return this.formatIPv6(n);if(n.length===8||n.length===32){const r=n.length/2,i=n.slice(0,r),s=n.slice(r);if(n.every(l=>l===0))return n.length===8?"0.0.0.0/0":"::/0";const c=s.reduce((l,d)=>l+(d.toString(2).match(/1/g)||[]).length,0);return n.length===8?`${Array.from(i).join(".")}/${c}`:`${this.formatIPv6(i)}/${c}`}return this.decodeIP(F.ToHex(e))}static fromString(e){if(e.includes("/")){const[r,i]=this.parseCIDR(e),s=new Uint8Array(r.length);let a=i;for(let l=0;l<s.length;l++)a>=8?(s[l]=255,a-=8):a>0&&(s[l]=255<<8-a,a=0);const c=new Uint8Array(r.length*2);return c.set(r,0),c.set(s,r.length),c.buffer}const n=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(n).buffer}}var Yl,Ql,ed;let qe=class{constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};h([m({type:b.TeletexString})],qe.prototype,"teletexString",void 0);h([m({type:b.PrintableString})],qe.prototype,"printableString",void 0);h([m({type:b.UniversalString})],qe.prototype,"universalString",void 0);h([m({type:b.Utf8String})],qe.prototype,"utf8String",void 0);h([m({type:b.BmpString})],qe.prototype,"bmpString",void 0);qe=h([j({type:C.Choice})],qe);let Qr=class extends qe{constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?F.ToHex(this.anyValue):super.toString())}};h([m({type:b.IA5String})],Qr.prototype,"ia5String",void 0);h([m({type:b.Any})],Qr.prototype,"anyValue",void 0);Qr=h([j({type:C.Choice})],Qr);class $c{constructor(e={}){this.type="",this.value=new Qr,Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],$c.prototype,"type",void 0);h([m({type:Qr})],$c.prototype,"value",void 0);let ei=Yl=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Yl.prototype)}};ei=Yl=h([j({type:C.Set,itemType:$c})],ei);let td=Ql=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Ql.prototype)}};td=Ql=h([j({type:C.Sequence,itemType:ei})],td);let Ce=ed=class extends td{constructor(e){super(e),Object.setPrototypeOf(this,ed.prototype)}};Ce=ed=h([j({type:C.Sequence})],Ce);const A4={fromASN:t=>uh.toString(ca.fromASN(t)),toASN:t=>ca.toASN(uh.fromString(t))};class ko{constructor(e={}){this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],ko.prototype,"typeId",void 0);h([m({type:b.Any,context:0})],ko.prototype,"value",void 0);class rp{constructor(e={}){this.partyName=new qe,Object.assign(this,e)}}h([m({type:qe,optional:!0,context:0,implicit:!0})],rp.prototype,"nameAssigner",void 0);h([m({type:qe,context:1,implicit:!0})],rp.prototype,"partyName",void 0);let ee=class{constructor(e={}){Object.assign(this,e)}};h([m({type:ko,context:0,implicit:!0})],ee.prototype,"otherName",void 0);h([m({type:b.IA5String,context:1,implicit:!0})],ee.prototype,"rfc822Name",void 0);h([m({type:b.IA5String,context:2,implicit:!0})],ee.prototype,"dNSName",void 0);h([m({type:b.Any,context:3,implicit:!0})],ee.prototype,"x400Address",void 0);h([m({type:Ce,context:4,implicit:!1})],ee.prototype,"directoryName",void 0);h([m({type:rp,context:5})],ee.prototype,"ediPartyName",void 0);h([m({type:b.IA5String,context:6,implicit:!0})],ee.prototype,"uniformResourceIdentifier",void 0);h([m({type:b.OctetString,context:7,implicit:!0,converter:A4})],ee.prototype,"iPAddress",void 0);h([m({type:b.ObjectIdentifier,context:8,implicit:!0})],ee.prototype,"registeredID",void 0);ee=h([j({type:C.Choice})],ee);const ip="1.3.6.1.5.5.7",E4=`${ip}.1`,yi=`${ip}.3`,kc=`${ip}.48`,ph=`${kc}.1`,fh=`${kc}.2`,hh=`${kc}.3`,gh=`${kc}.5`,bn="2.5.29";var nd;const rd=`${E4}.1`;class Jo{constructor(e={}){this.accessMethod="",this.accessLocation=new ee,Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],Jo.prototype,"accessMethod",void 0);h([m({type:ee})],Jo.prototype,"accessLocation",void 0);let Ur=nd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,nd.prototype)}};Ur=nd=h([j({type:C.Sequence,itemType:Jo})],Ur);const id=`${bn}.35`;class op extends ae{}class Qn{constructor(e={}){e&&Object.assign(this,e)}}h([m({type:op,context:0,optional:!0,implicit:!0})],Qn.prototype,"keyIdentifier",void 0);h([m({type:ee,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Qn.prototype,"authorityCertIssuer",void 0);h([m({type:b.Integer,context:2,optional:!0,implicit:!0,converter:_e})],Qn.prototype,"authorityCertSerialNumber",void 0);const jy=`${bn}.19`;class la{constructor(e={}){this.cA=!1,Object.assign(this,e)}}h([m({type:b.Boolean,defaultValue:!1})],la.prototype,"cA",void 0);h([m({type:b.Integer,optional:!0})],la.prototype,"pathLenConstraint",void 0);var od;let We=od=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,od.prototype)}};We=od=h([j({type:C.Sequence,itemType:ee})],We);var sd;let mh=sd=class extends We{constructor(e){super(e),Object.setPrototypeOf(this,sd.prototype)}};mh=sd=h([j({type:C.Sequence})],mh);var ad;const Py=`${bn}.32`;let un=class{constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};h([m({type:b.IA5String})],un.prototype,"ia5String",void 0);h([m({type:b.VisibleString})],un.prototype,"visibleString",void 0);h([m({type:b.BmpString})],un.prototype,"bmpString",void 0);h([m({type:b.Utf8String})],un.prototype,"utf8String",void 0);un=h([j({type:C.Choice})],un);class sp{constructor(e={}){this.organization=new un,this.noticeNumbers=[],Object.assign(this,e)}}h([m({type:un})],sp.prototype,"organization",void 0);h([m({type:b.Integer,repeated:"sequence"})],sp.prototype,"noticeNumbers",void 0);class ap{constructor(e={}){Object.assign(this,e)}}h([m({type:sp,optional:!0})],ap.prototype,"noticeRef",void 0);h([m({type:un,optional:!0})],ap.prototype,"explicitText",void 0);let da=class{constructor(e={}){Object.assign(this,e)}};h([m({type:b.IA5String})],da.prototype,"cPSuri",void 0);h([m({type:ap})],da.prototype,"userNotice",void 0);da=h([j({type:C.Choice})],da);class cp{constructor(e={}){this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],cp.prototype,"policyQualifierId",void 0);h([m({type:b.Any})],cp.prototype,"qualifier",void 0);class xc{constructor(e={}){this.policyIdentifier="",Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],xc.prototype,"policyIdentifier",void 0);h([m({type:cp,repeated:"sequence",optional:!0})],xc.prototype,"policyQualifiers",void 0);let ua=ad=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,ad.prototype)}};ua=ad=h([j({type:C.Sequence,itemType:xc})],ua);let pa=class{constructor(e=0){this.value=e}};h([m({type:b.Integer})],pa.prototype,"value",void 0);pa=h([j({type:C.Choice})],pa);let _h=class extends pa{};_h=h([j({type:C.Choice})],_h);var cd;const ld=`${bn}.31`;var kt;(function(t){t[t.unused=1]="unused",t[t.keyCompromise=2]="keyCompromise",t[t.cACompromise=4]="cACompromise",t[t.affiliationChanged=8]="affiliationChanged",t[t.superseded=16]="superseded",t[t.cessationOfOperation=32]="cessationOfOperation",t[t.certificateHold=64]="certificateHold",t[t.privilegeWithdrawn=128]="privilegeWithdrawn",t[t.aACompromise=256]="aACompromise"})(kt||(kt={}));class Oy extends vc{toJSON(){const e=[],n=this.toNumber();return n&kt.aACompromise&&e.push("aACompromise"),n&kt.affiliationChanged&&e.push("affiliationChanged"),n&kt.cACompromise&&e.push("cACompromise"),n&kt.certificateHold&&e.push("certificateHold"),n&kt.cessationOfOperation&&e.push("cessationOfOperation"),n&kt.keyCompromise&&e.push("keyCompromise"),n&kt.privilegeWithdrawn&&e.push("privilegeWithdrawn"),n&kt.superseded&&e.push("superseded"),n&kt.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let ur=class{constructor(e={}){Object.assign(this,e)}};h([m({type:ee,context:0,repeated:"sequence",implicit:!0})],ur.prototype,"fullName",void 0);h([m({type:ei,context:1,implicit:!0})],ur.prototype,"nameRelativeToCRLIssuer",void 0);ur=h([j({type:C.Choice})],ur);class wi{constructor(e={}){Object.assign(this,e)}}h([m({type:ur,context:0,optional:!0})],wi.prototype,"distributionPoint",void 0);h([m({type:Oy,context:1,optional:!0,implicit:!0})],wi.prototype,"reasons",void 0);h([m({type:ee,context:2,optional:!0,repeated:"sequence",implicit:!0})],wi.prototype,"cRLIssuer",void 0);let Vr=cd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,cd.prototype)}};Vr=cd=h([j({type:C.Sequence,itemType:wi})],Vr);var dd;let yh=dd=class extends Vr{constructor(e){super(e),Object.setPrototypeOf(this,dd.prototype)}};yh=dd=h([j({type:C.Sequence,itemType:wi})],yh);class Ge{constructor(e={}){this.onlyContainsUserCerts=Ge.ONLY,this.onlyContainsCACerts=Ge.ONLY,this.indirectCRL=Ge.ONLY,this.onlyContainsAttributeCerts=Ge.ONLY,Object.assign(this,e)}}Ge.ONLY=!1;h([m({type:ur,context:0,optional:!0})],Ge.prototype,"distributionPoint",void 0);h([m({type:b.Boolean,context:1,defaultValue:Ge.ONLY,implicit:!0})],Ge.prototype,"onlyContainsUserCerts",void 0);h([m({type:b.Boolean,context:2,defaultValue:Ge.ONLY,implicit:!0})],Ge.prototype,"onlyContainsCACerts",void 0);h([m({type:Oy,context:3,optional:!0,implicit:!0})],Ge.prototype,"onlySomeReasons",void 0);h([m({type:b.Boolean,context:4,defaultValue:Ge.ONLY,implicit:!0})],Ge.prototype,"indirectCRL",void 0);h([m({type:b.Boolean,context:5,defaultValue:Ge.ONLY,implicit:!0})],Ge.prototype,"onlyContainsAttributeCerts",void 0);var lo;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(lo||(lo={}));let ud=class{constructor(e=lo.unspecified){this.reason=lo.unspecified,this.reason=e}toJSON(){return lo[this.reason]}toString(){return this.toJSON()}};h([m({type:b.Enumerated})],ud.prototype,"reason",void 0);ud=h([j({type:C.Choice})],ud);var pd;const Ty=`${bn}.37`;let fa=pd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,pd.prototype)}};fa=pd=h([j({type:C.Sequence,itemType:b.ObjectIdentifier})],fa);const C4=`${yi}.1`,N4=`${yi}.2`,I4=`${yi}.3`,j4=`${yi}.4`,P4=`${yi}.8`,O4=`${yi}.9`;let fd=class{constructor(e=new ArrayBuffer(0)){this.value=e}};h([m({type:b.Integer,converter:_e})],fd.prototype,"value",void 0);fd=h([j({type:C.Choice})],fd);let hd=class{constructor(e){this.value=new Date,e&&(this.value=e)}};h([m({type:b.GeneralizedTime})],hd.prototype,"value",void 0);hd=h([j({type:C.Choice})],hd);var gd;const Ry=`${bn}.18`;let wh=gd=class extends We{constructor(e){super(e),Object.setPrototypeOf(this,gd.prototype)}};wh=gd=h([j({type:C.Sequence})],wh);const By=`${bn}.15`;var xt;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(xt||(xt={}));class hl extends vc{toJSON(){const e=this.toNumber(),n=[];return e&xt.cRLSign&&n.push("crlSign"),e&xt.dataEncipherment&&n.push("dataEncipherment"),e&xt.decipherOnly&&n.push("decipherOnly"),e&xt.digitalSignature&&n.push("digitalSignature"),e&xt.encipherOnly&&n.push("encipherOnly"),e&xt.keyAgreement&&n.push("keyAgreement"),e&xt.keyCertSign&&n.push("keyCertSign"),e&xt.keyEncipherment&&n.push("keyEncipherment"),e&xt.nonRepudiation&&n.push("nonRepudiation"),n}toString(){return`[${this.toJSON().join(", ")}]`}}var md;class Sc{constructor(e={}){this.base=new ee,this.minimum=0,Object.assign(this,e)}}h([m({type:ee})],Sc.prototype,"base",void 0);h([m({type:b.Integer,context:0,defaultValue:0,implicit:!0})],Sc.prototype,"minimum",void 0);h([m({type:b.Integer,context:1,optional:!0,implicit:!0})],Sc.prototype,"maximum",void 0);let ha=md=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,md.prototype)}};ha=md=h([j({type:C.Sequence,itemType:Sc})],ha);class Ly{constructor(e={}){Object.assign(this,e)}}h([m({type:ha,context:0,optional:!0,implicit:!0})],Ly.prototype,"permittedSubtrees",void 0);h([m({type:ha,context:1,optional:!0,implicit:!0})],Ly.prototype,"excludedSubtrees",void 0);class Uy{constructor(e={}){Object.assign(this,e)}}h([m({type:b.Integer,context:0,implicit:!0,optional:!0,converter:_e})],Uy.prototype,"requireExplicitPolicy",void 0);h([m({type:b.Integer,context:1,implicit:!0,optional:!0,converter:_e})],Uy.prototype,"inhibitPolicyMapping",void 0);var _d;class lp{constructor(e={}){this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],lp.prototype,"issuerDomainPolicy",void 0);h([m({type:b.ObjectIdentifier})],lp.prototype,"subjectDomainPolicy",void 0);let bh=_d=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,_d.prototype)}};bh=_d=h([j({type:C.Sequence,itemType:lp})],bh);var yd;const Dy=`${bn}.17`;let wd=yd=class extends We{constructor(e){super(e),Object.setPrototypeOf(this,yd.prototype)}};wd=yd=h([j({type:C.Sequence})],wd);let pn=class{constructor(e={}){this.type="",this.values=[],Object.assign(this,e)}};h([m({type:b.ObjectIdentifier})],pn.prototype,"type",void 0);h([m({type:b.Any,repeated:"set"})],pn.prototype,"values",void 0);var bd;let vh=bd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,bd.prototype)}};vh=bd=h([j({type:C.Sequence,itemType:pn})],vh);const My=`${bn}.14`;class jn extends op{}class qy{constructor(e={}){Object.assign(this,e)}}h([m({type:b.GeneralizedTime,context:0,implicit:!0,optional:!0})],qy.prototype,"notBefore",void 0);h([m({type:b.GeneralizedTime,context:1,implicit:!0,optional:!0})],qy.prototype,"notAfter",void 0);var uo;(function(t){t[t.keyUpdateAllowed=1]="keyUpdateAllowed",t[t.newExtensions=2]="newExtensions",t[t.pKIXCertificate=4]="pKIXCertificate"})(uo||(uo={}));class Fy extends vc{toJSON(){const e=[],n=this.toNumber();return n&uo.pKIXCertificate&&e.push("pKIXCertificate"),n&uo.newExtensions&&e.push("newExtensions"),n&uo.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class Hy{constructor(e={}){this.entrustVers="",this.entrustInfoFlags=new Fy,Object.assign(this,e)}}h([m({type:b.GeneralString})],Hy.prototype,"entrustVers",void 0);h([m({type:Fy})],Hy.prototype,"entrustInfoFlags",void 0);var vd;let $h=vd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,vd.prototype)}};$h=vd=h([j({type:C.Sequence,itemType:Jo})],$h);class U{constructor(e={}){this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof U&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&P_(e.parameters,this.parameters)||e.parameters===this.parameters)}}h([m({type:b.ObjectIdentifier})],U.prototype,"algorithm",void 0);h([m({type:b.Any,optional:!0})],U.prototype,"parameters",void 0);class At{constructor(e={}){this.algorithm=new U,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:U})],At.prototype,"algorithm",void 0);h([m({type:b.BitString})],At.prototype,"subjectPublicKey",void 0);let Ue=class{constructor(e){if(e)if(typeof e=="string"||typeof e=="number"||e instanceof Date){const n=new Date(e);n.getUTCFullYear()>2049?this.generalTime=n:this.utcTime=n}else Object.assign(this,e)}getTime(){const e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};h([m({type:b.UTCTime})],Ue.prototype,"utcTime",void 0);h([m({type:b.GeneralizedTime})],Ue.prototype,"generalTime",void 0);Ue=h([j({type:C.Choice})],Ue);class Xo{constructor(e){this.notBefore=new Ue(new Date),this.notAfter=new Ue(new Date),e&&(this.notBefore=new Ue(e.notBefore),this.notAfter=new Ue(e.notAfter))}}h([m({type:Ue})],Xo.prototype,"notBefore",void 0);h([m({type:Ue})],Xo.prototype,"notAfter",void 0);var $d;let yt=class Vy{constructor(e={}){this.extnID="",this.critical=Vy.CRITICAL,this.extnValue=new ae,Object.assign(this,e)}};yt.CRITICAL=!1;h([m({type:b.ObjectIdentifier})],yt.prototype,"extnID",void 0);h([m({type:b.Boolean,defaultValue:yt.CRITICAL})],yt.prototype,"critical",void 0);h([m({type:ae})],yt.prototype,"extnValue",void 0);let Tn=$d=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,$d.prototype)}};Tn=$d=h([j({type:C.Sequence,itemType:yt})],Tn);var pr;(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2",t[t.v3=2]="v3"})(pr||(pr={}));class ut{constructor(e={}){this.version=pr.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new U,this.issuer=new Ce,this.validity=new Xo,this.subject=new Ce,this.subjectPublicKeyInfo=new At,Object.assign(this,e)}}h([m({type:b.Integer,context:0,defaultValue:pr.v1})],ut.prototype,"version",void 0);h([m({type:b.Integer,converter:_e})],ut.prototype,"serialNumber",void 0);h([m({type:U})],ut.prototype,"signature",void 0);h([m({type:Ce})],ut.prototype,"issuer",void 0);h([m({type:Xo})],ut.prototype,"validity",void 0);h([m({type:Ce})],ut.prototype,"subject",void 0);h([m({type:At})],ut.prototype,"subjectPublicKeyInfo",void 0);h([m({type:b.BitString,context:1,implicit:!0,optional:!0})],ut.prototype,"issuerUniqueID",void 0);h([m({type:b.BitString,context:2,implicit:!0,optional:!0})],ut.prototype,"subjectUniqueID",void 0);h([m({type:Tn,context:3,optional:!0})],ut.prototype,"extensions",void 0);class fr{constructor(e={}){this.tbsCertificate=new ut,this.signatureAlgorithm=new U,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:ut,raw:!0})],fr.prototype,"tbsCertificate",void 0);h([m({type:U})],fr.prototype,"signatureAlgorithm",void 0);h([m({type:b.BitString})],fr.prototype,"signatureValue",void 0);class zc{constructor(e={}){this.userCertificate=new ArrayBuffer(0),this.revocationDate=new Ue,Object.assign(this,e)}}h([m({type:b.Integer,converter:_e})],zc.prototype,"userCertificate",void 0);h([m({type:Ue})],zc.prototype,"revocationDate",void 0);h([m({type:yt,optional:!0,repeated:"sequence"})],zc.prototype,"crlEntryExtensions",void 0);class vn{constructor(e={}){this.signature=new U,this.issuer=new Ce,this.thisUpdate=new Ue,Object.assign(this,e)}}h([m({type:b.Integer,optional:!0})],vn.prototype,"version",void 0);h([m({type:U})],vn.prototype,"signature",void 0);h([m({type:Ce})],vn.prototype,"issuer",void 0);h([m({type:Ue})],vn.prototype,"thisUpdate",void 0);h([m({type:Ue,optional:!0})],vn.prototype,"nextUpdate",void 0);h([m({type:zc,repeated:"sequence",optional:!0})],vn.prototype,"revokedCertificates",void 0);h([m({type:yt,optional:!0,context:0,repeated:"sequence"})],vn.prototype,"crlExtensions",void 0);class dp{constructor(e={}){this.tbsCertList=new vn,this.signatureAlgorithm=new U,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:vn,raw:!0})],dp.prototype,"tbsCertList",void 0);h([m({type:U})],dp.prototype,"signatureAlgorithm",void 0);h([m({type:b.BitString})],dp.prototype,"signature",void 0);class bi{constructor(e={}){this.issuer=new Ce,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:Ce})],bi.prototype,"issuer",void 0);h([m({type:b.Integer,converter:_e})],bi.prototype,"serialNumber",void 0);let ti=class{constructor(e={}){Object.assign(this,e)}};h([m({type:jn,context:0,implicit:!0})],ti.prototype,"subjectKeyIdentifier",void 0);h([m({type:bi})],ti.prototype,"issuerAndSerialNumber",void 0);ti=h([j({type:C.Choice})],ti);var fn;(function(t){t[t.v0=0]="v0",t[t.v1=1]="v1",t[t.v2=2]="v2",t[t.v3=3]="v3",t[t.v4=4]="v4",t[t.v5=5]="v5"})(fn||(fn={}));let xo=class extends U{};xo=h([j({type:C.Sequence})],xo);let ga=class extends U{};ga=h([j({type:C.Sequence})],ga);let Wt=class extends U{};Wt=h([j({type:C.Sequence})],Wt);let ma=class extends U{};ma=h([j({type:C.Sequence})],ma);let kh=class extends U{};kh=h([j({type:C.Sequence})],kh);let kd=class extends U{};kd=h([j({type:C.Sequence})],kd);let vi=class{constructor(e={}){this.attrType="",this.attrValues=[],Object.assign(this,e)}};h([m({type:b.ObjectIdentifier})],vi.prototype,"attrType",void 0);h([m({type:b.Any,repeated:"set"})],vi.prototype,"attrValues",void 0);var xd;class Yt{constructor(e={}){this.version=fn.v0,this.sid=new ti,this.digestAlgorithm=new xo,this.signatureAlgorithm=new ga,this.signature=new ae,Object.assign(this,e)}}h([m({type:b.Integer})],Yt.prototype,"version",void 0);h([m({type:ti})],Yt.prototype,"sid",void 0);h([m({type:xo})],Yt.prototype,"digestAlgorithm",void 0);h([m({type:vi,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],Yt.prototype,"signedAttrs",void 0);h([m({type:ga})],Yt.prototype,"signatureAlgorithm",void 0);h([m({type:ae})],Yt.prototype,"signature",void 0);h([m({type:vi,repeated:"set",context:1,implicit:!0,optional:!0})],Yt.prototype,"unsignedAttrs",void 0);let _a=xd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,xd.prototype)}};_a=xd=h([j({type:C.Set,itemType:Yt})],_a);let xh=class extends Yt{};xh=h([j({type:C.Sequence})],xh);let Sh=class extends Ue{};Sh=h([j({type:C.Choice})],Sh);class up{constructor(e={}){this.acIssuer=new ee,this.acSerial=0,this.attrs=[],Object.assign(this,e)}}h([m({type:ee})],up.prototype,"acIssuer",void 0);h([m({type:b.Integer})],up.prototype,"acSerial",void 0);h([m({type:pn,repeated:"sequence"})],up.prototype,"attrs",void 0);var Sd;let ya=Sd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Sd.prototype)}};ya=Sd=h([j({type:C.Sequence,itemType:b.ObjectIdentifier})],ya);class Ac{constructor(e={}){this.permitUnSpecified=!0,Object.assign(this,e)}}h([m({type:b.Integer,optional:!0})],Ac.prototype,"pathLenConstraint",void 0);h([m({type:ya,implicit:!0,context:0,optional:!0})],Ac.prototype,"permittedAttrs",void 0);h([m({type:ya,implicit:!0,context:1,optional:!0})],Ac.prototype,"excludedAttrs",void 0);h([m({type:b.Boolean,defaultValue:!0})],Ac.prototype,"permitUnSpecified",void 0);class Sr{constructor(e={}){this.issuer=new We,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:We})],Sr.prototype,"issuer",void 0);h([m({type:b.Integer,converter:_e})],Sr.prototype,"serial",void 0);h([m({type:b.BitString,optional:!0})],Sr.prototype,"issuerUID",void 0);var zd;(function(t){t[t.publicKey=0]="publicKey",t[t.publicKeyCert=1]="publicKeyCert",t[t.otherObjectTypes=2]="otherObjectTypes"})(zd||(zd={}));class zr{constructor(e={}){this.digestedObjectType=zd.publicKey,this.digestAlgorithm=new U,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.Enumerated})],zr.prototype,"digestedObjectType",void 0);h([m({type:b.ObjectIdentifier,optional:!0})],zr.prototype,"otherObjectTypeID",void 0);h([m({type:U})],zr.prototype,"digestAlgorithm",void 0);h([m({type:b.BitString})],zr.prototype,"objectDigest",void 0);class Ec{constructor(e={}){Object.assign(this,e)}}h([m({type:We,optional:!0})],Ec.prototype,"issuerName",void 0);h([m({type:Sr,context:0,implicit:!0,optional:!0})],Ec.prototype,"baseCertificateID",void 0);h([m({type:zr,context:1,implicit:!0,optional:!0})],Ec.prototype,"objectDigestInfo",void 0);let ni=class{constructor(e={}){Object.assign(this,e)}};h([m({type:ee,repeated:"sequence"})],ni.prototype,"v1Form",void 0);h([m({type:Ec,context:0,implicit:!0})],ni.prototype,"v2Form",void 0);ni=h([j({type:C.Choice})],ni);class Cc{constructor(e={}){this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}}h([m({type:b.GeneralizedTime})],Cc.prototype,"notBeforeTime",void 0);h([m({type:b.GeneralizedTime})],Cc.prototype,"notAfterTime",void 0);class Zo{constructor(e={}){Object.assign(this,e)}}h([m({type:Sr,implicit:!0,context:0,optional:!0})],Zo.prototype,"baseCertificateID",void 0);h([m({type:We,implicit:!0,context:1,optional:!0})],Zo.prototype,"entityName",void 0);h([m({type:zr,implicit:!0,context:2,optional:!0})],Zo.prototype,"objectDigestInfo",void 0);var Ad;(function(t){t[t.v2=1]="v2"})(Ad||(Ad={}));class Tt{constructor(e={}){this.version=Ad.v2,this.holder=new Zo,this.issuer=new ni,this.signature=new U,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new Cc,this.attributes=[],Object.assign(this,e)}}h([m({type:b.Integer})],Tt.prototype,"version",void 0);h([m({type:Zo})],Tt.prototype,"holder",void 0);h([m({type:ni})],Tt.prototype,"issuer",void 0);h([m({type:U})],Tt.prototype,"signature",void 0);h([m({type:b.Integer,converter:_e})],Tt.prototype,"serialNumber",void 0);h([m({type:Cc})],Tt.prototype,"attrCertValidityPeriod",void 0);h([m({type:pn,repeated:"sequence"})],Tt.prototype,"attributes",void 0);h([m({type:b.BitString,optional:!0})],Tt.prototype,"issuerUniqueID",void 0);h([m({type:Tn,optional:!0})],Tt.prototype,"extensions",void 0);class Nc{constructor(e={}){this.acinfo=new Tt,this.signatureAlgorithm=new U,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:Tt})],Nc.prototype,"acinfo",void 0);h([m({type:U})],Nc.prototype,"signatureAlgorithm",void 0);h([m({type:b.BitString})],Nc.prototype,"signatureValue",void 0);var wa;(function(t){t[t.unmarked=1]="unmarked",t[t.unclassified=2]="unclassified",t[t.restricted=4]="restricted",t[t.confidential=8]="confidential",t[t.secret=16]="secret",t[t.topSecret=32]="topSecret"})(wa||(wa={}));class Ed extends vc{}class pp{constructor(e={}){this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier,implicit:!0,context:0})],pp.prototype,"type",void 0);h([m({type:b.Any,implicit:!0,context:1})],pp.prototype,"value",void 0);class fp{constructor(e={}){this.policyId="",this.classList=new Ed(wa.unclassified),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],fp.prototype,"policyId",void 0);h([m({type:Ed,defaultValue:new Ed(wa.unclassified)})],fp.prototype,"classList",void 0);h([m({type:pp,repeated:"set"})],fp.prototype,"securityCategories",void 0);class Ic{constructor(e={}){Object.assign(this,e)}}h([m({type:ae})],Ic.prototype,"cotets",void 0);h([m({type:b.ObjectIdentifier})],Ic.prototype,"oid",void 0);h([m({type:b.Utf8String})],Ic.prototype,"string",void 0);class Ky{constructor(e={}){this.values=[],Object.assign(this,e)}}h([m({type:We,implicit:!0,context:0,optional:!0})],Ky.prototype,"policyAuthority",void 0);h([m({type:Ic,repeated:"sequence"})],Ky.prototype,"values",void 0);var Cd;class jc{constructor(e={}){this.targetCertificate=new Sr,Object.assign(this,e)}}h([m({type:Sr})],jc.prototype,"targetCertificate",void 0);h([m({type:ee,optional:!0})],jc.prototype,"targetName",void 0);h([m({type:zr,optional:!0})],jc.prototype,"certDigestInfo",void 0);let ri=class{constructor(e={}){Object.assign(this,e)}};h([m({type:ee,context:0,implicit:!0})],ri.prototype,"targetName",void 0);h([m({type:ee,context:1,implicit:!0})],ri.prototype,"targetGroup",void 0);h([m({type:jc,context:2,implicit:!0})],ri.prototype,"targetCert",void 0);ri=h([j({type:C.Choice})],ri);let Nd=Cd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Cd.prototype)}};Nd=Cd=h([j({type:C.Sequence,itemType:ri})],Nd);var Id;let zh=Id=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Id.prototype)}};zh=Id=h([j({type:C.Sequence,itemType:Nd})],zh);class Gy{constructor(e={}){Object.assign(this,e)}}h([m({type:We,implicit:!0,context:0,optional:!0})],Gy.prototype,"roleAuthority",void 0);h([m({type:ee,implicit:!0,context:1})],Gy.prototype,"roleName",void 0);class hp{constructor(e={}){this.service=new ee,this.ident=new ee,Object.assign(this,e)}}h([m({type:ee})],hp.prototype,"service",void 0);h([m({type:ee})],hp.prototype,"ident",void 0);h([m({type:ae,optional:!0})],hp.prototype,"authInfo",void 0);var jd;class gp{constructor(e={}){this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],gp.prototype,"otherCertFormat",void 0);h([m({type:b.Any})],gp.prototype,"otherCert",void 0);let ii=class{constructor(e={}){Object.assign(this,e)}};h([m({type:fr})],ii.prototype,"certificate",void 0);h([m({type:Nc,context:2,implicit:!0})],ii.prototype,"v2AttrCert",void 0);h([m({type:gp,context:3,implicit:!0})],ii.prototype,"other",void 0);ii=h([j({type:C.Choice})],ii);let ba=jd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,jd.prototype)}};ba=jd=h([j({type:C.Set,itemType:ii})],ba);class $i{constructor(e={}){this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],$i.prototype,"contentType",void 0);h([m({type:b.Any,context:0})],$i.prototype,"content",void 0);let So=class{constructor(e={}){Object.assign(this,e)}};h([m({type:ae})],So.prototype,"single",void 0);h([m({type:b.Any})],So.prototype,"any",void 0);So=h([j({type:C.Choice})],So);class Pc{constructor(e={}){this.eContentType="",Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],Pc.prototype,"eContentType",void 0);h([m({type:So,context:0,optional:!0})],Pc.prototype,"eContent",void 0);let zo=class{constructor(e={}){Object.assign(this,e)}};h([m({type:ae,context:0,implicit:!0,optional:!0})],zo.prototype,"value",void 0);h([m({type:ae,converter:l4,context:0,implicit:!0,optional:!0,repeated:"sequence"})],zo.prototype,"constructedValue",void 0);zo=h([j({type:C.Choice})],zo);class Yo{constructor(e={}){this.contentType="",this.contentEncryptionAlgorithm=new ma,Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],Yo.prototype,"contentType",void 0);h([m({type:ma})],Yo.prototype,"contentEncryptionAlgorithm",void 0);h([m({type:zo,optional:!0})],Yo.prototype,"encryptedContent",void 0);class Oc{constructor(e={}){this.keyAttrId="",Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],Oc.prototype,"keyAttrId",void 0);h([m({type:b.Any,optional:!0})],Oc.prototype,"keyAttr",void 0);var Pd;class Tc{constructor(e={}){this.subjectKeyIdentifier=new jn,Object.assign(this,e)}}h([m({type:jn})],Tc.prototype,"subjectKeyIdentifier",void 0);h([m({type:b.GeneralizedTime,optional:!0})],Tc.prototype,"date",void 0);h([m({type:Oc,optional:!0})],Tc.prototype,"other",void 0);let oi=class{constructor(e={}){Object.assign(this,e)}};h([m({type:Tc,context:0,implicit:!0,optional:!0})],oi.prototype,"rKeyId",void 0);h([m({type:bi,optional:!0})],oi.prototype,"issuerAndSerialNumber",void 0);oi=h([j({type:C.Choice})],oi);class mp{constructor(e={}){this.rid=new oi,this.encryptedKey=new ae,Object.assign(this,e)}}h([m({type:oi})],mp.prototype,"rid",void 0);h([m({type:ae})],mp.prototype,"encryptedKey",void 0);let va=Pd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Pd.prototype)}};va=Pd=h([j({type:C.Sequence,itemType:mp})],va);class _p{constructor(e={}){this.algorithm=new U,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:U})],_p.prototype,"algorithm",void 0);h([m({type:b.BitString})],_p.prototype,"publicKey",void 0);let hr=class{constructor(e={}){Object.assign(this,e)}};h([m({type:jn,context:0,implicit:!0,optional:!0})],hr.prototype,"subjectKeyIdentifier",void 0);h([m({type:_p,context:1,implicit:!0,optional:!0})],hr.prototype,"originatorKey",void 0);h([m({type:bi,optional:!0})],hr.prototype,"issuerAndSerialNumber",void 0);hr=h([j({type:C.Choice})],hr);class ki{constructor(e={}){this.version=fn.v3,this.originator=new hr,this.keyEncryptionAlgorithm=new Wt,this.recipientEncryptedKeys=new va,Object.assign(this,e)}}h([m({type:b.Integer})],ki.prototype,"version",void 0);h([m({type:hr,context:0})],ki.prototype,"originator",void 0);h([m({type:ae,context:1,optional:!0})],ki.prototype,"ukm",void 0);h([m({type:Wt})],ki.prototype,"keyEncryptionAlgorithm",void 0);h([m({type:va})],ki.prototype,"recipientEncryptedKeys",void 0);let si=class{constructor(e={}){Object.assign(this,e)}};h([m({type:jn,context:0,implicit:!0})],si.prototype,"subjectKeyIdentifier",void 0);h([m({type:bi})],si.prototype,"issuerAndSerialNumber",void 0);si=h([j({type:C.Choice})],si);class Qo{constructor(e={}){this.version=fn.v0,this.rid=new si,this.keyEncryptionAlgorithm=new Wt,this.encryptedKey=new ae,Object.assign(this,e)}}h([m({type:b.Integer})],Qo.prototype,"version",void 0);h([m({type:si})],Qo.prototype,"rid",void 0);h([m({type:Wt})],Qo.prototype,"keyEncryptionAlgorithm",void 0);h([m({type:ae})],Qo.prototype,"encryptedKey",void 0);class es{constructor(e={}){this.keyIdentifier=new ae,Object.assign(this,e)}}h([m({type:ae})],es.prototype,"keyIdentifier",void 0);h([m({type:b.GeneralizedTime,optional:!0})],es.prototype,"date",void 0);h([m({type:Oc,optional:!0})],es.prototype,"other",void 0);class ts{constructor(e={}){this.version=fn.v4,this.kekid=new es,this.keyEncryptionAlgorithm=new Wt,this.encryptedKey=new ae,Object.assign(this,e)}}h([m({type:b.Integer})],ts.prototype,"version",void 0);h([m({type:es})],ts.prototype,"kekid",void 0);h([m({type:Wt})],ts.prototype,"keyEncryptionAlgorithm",void 0);h([m({type:ae})],ts.prototype,"encryptedKey",void 0);class ns{constructor(e={}){this.version=fn.v0,this.keyEncryptionAlgorithm=new Wt,this.encryptedKey=new ae,Object.assign(this,e)}}h([m({type:b.Integer})],ns.prototype,"version",void 0);h([m({type:kd,context:0,optional:!0})],ns.prototype,"keyDerivationAlgorithm",void 0);h([m({type:Wt})],ns.prototype,"keyEncryptionAlgorithm",void 0);h([m({type:ae})],ns.prototype,"encryptedKey",void 0);class yp{constructor(e={}){this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],yp.prototype,"oriType",void 0);h([m({type:b.Any})],yp.prototype,"oriValue",void 0);let Rn=class{constructor(e={}){Object.assign(this,e)}};h([m({type:Qo,optional:!0})],Rn.prototype,"ktri",void 0);h([m({type:ki,context:1,implicit:!0,optional:!0})],Rn.prototype,"kari",void 0);h([m({type:ts,context:2,implicit:!0,optional:!0})],Rn.prototype,"kekri",void 0);h([m({type:ns,context:3,implicit:!0,optional:!0})],Rn.prototype,"pwri",void 0);h([m({type:yp,context:4,implicit:!0,optional:!0})],Rn.prototype,"ori",void 0);Rn=h([j({type:C.Choice})],Rn);var Od;let $a=Od=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Od.prototype)}};$a=Od=h([j({type:C.Set,itemType:Rn})],$a);var Td;class Rc{constructor(e={}){this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],Rc.prototype,"otherRevInfoFormat",void 0);h([m({type:b.Any})],Rc.prototype,"otherRevInfo",void 0);let ka=class{constructor(e={}){this.other=new Rc,Object.assign(this,e)}};h([m({type:Rc,context:1,implicit:!0})],ka.prototype,"other",void 0);ka=h([j({type:C.Choice})],ka);let xa=Td=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Td.prototype)}};xa=Td=h([j({type:C.Set,itemType:ka})],xa);class wp{constructor(e={}){Object.assign(this,e)}}h([m({type:ba,context:0,implicit:!0,optional:!0})],wp.prototype,"certs",void 0);h([m({type:xa,context:1,implicit:!0,optional:!0})],wp.prototype,"crls",void 0);var Rd;let Bd=Rd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Rd.prototype)}};Bd=Rd=h([j({type:C.Set,itemType:vi})],Bd);class rs{constructor(e={}){this.version=fn.v0,this.recipientInfos=new $a,this.encryptedContentInfo=new Yo,Object.assign(this,e)}}h([m({type:b.Integer})],rs.prototype,"version",void 0);h([m({type:wp,context:0,implicit:!0,optional:!0})],rs.prototype,"originatorInfo",void 0);h([m({type:$a})],rs.prototype,"recipientInfos",void 0);h([m({type:Yo})],rs.prototype,"encryptedContentInfo",void 0);h([m({type:Bd,context:1,implicit:!0,optional:!0})],rs.prototype,"unprotectedAttrs",void 0);const T4="1.2.840.113549.1.7.2";var Ld;let Sa=Ld=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Ld.prototype)}};Sa=Ld=h([j({type:C.Set,itemType:xo})],Sa);class xi{constructor(e={}){this.version=fn.v0,this.digestAlgorithms=new Sa,this.encapContentInfo=new Pc,this.signerInfos=new _a,Object.assign(this,e)}}h([m({type:b.Integer})],xi.prototype,"version",void 0);h([m({type:Sa})],xi.prototype,"digestAlgorithms",void 0);h([m({type:Pc})],xi.prototype,"encapContentInfo",void 0);h([m({type:ba,context:0,implicit:!0,optional:!0})],xi.prototype,"certificates",void 0);h([m({type:xa,context:1,implicit:!0,optional:!0})],xi.prototype,"crls",void 0);h([m({type:_a})],xi.prototype,"signerInfos",void 0);const Ao="1.2.840.10045.2.1",bp="1.2.840.10045.4.1",Wy="1.2.840.10045.4.3.1",vp="1.2.840.10045.4.3.2",$p="1.2.840.10045.4.3.3",kp="1.2.840.10045.4.3.4",Ah="1.2.840.10045.3.1.7",Eh="1.3.132.0.34",Ch="1.3.132.0.35";function is(t){return new U({algorithm:t})}const R4=is(bp);is(Wy);const B4=is(vp),L4=is($p),U4=is(kp);let Eo=class{constructor(e={}){Object.assign(this,e)}};h([m({type:b.ObjectIdentifier})],Eo.prototype,"fieldType",void 0);h([m({type:b.Any})],Eo.prototype,"parameters",void 0);Eo=h([j({type:C.Sequence})],Eo);class D4 extends ae{}let ai=class{constructor(e={}){Object.assign(this,e)}};h([m({type:b.OctetString})],ai.prototype,"a",void 0);h([m({type:b.OctetString})],ai.prototype,"b",void 0);h([m({type:b.BitString,optional:!0})],ai.prototype,"seed",void 0);ai=h([j({type:C.Sequence})],ai);var Ud;(function(t){t[t.ecpVer1=1]="ecpVer1"})(Ud||(Ud={}));let hn=class{constructor(e={}){this.version=Ud.ecpVer1,Object.assign(this,e)}};h([m({type:b.Integer})],hn.prototype,"version",void 0);h([m({type:Eo})],hn.prototype,"fieldID",void 0);h([m({type:ai})],hn.prototype,"curve",void 0);h([m({type:D4})],hn.prototype,"base",void 0);h([m({type:b.Integer,converter:_e})],hn.prototype,"order",void 0);h([m({type:b.Integer,optional:!0})],hn.prototype,"cofactor",void 0);hn=h([j({type:C.Sequence})],hn);let Bn=class{constructor(e={}){Object.assign(this,e)}};h([m({type:b.ObjectIdentifier})],Bn.prototype,"namedCurve",void 0);h([m({type:b.Null})],Bn.prototype,"implicitCurve",void 0);h([m({type:hn})],Bn.prototype,"specifiedCurve",void 0);Bn=h([j({type:C.Choice})],Bn);class Bc{constructor(e={}){this.version=1,this.privateKey=new ae,Object.assign(this,e)}}h([m({type:b.Integer})],Bc.prototype,"version",void 0);h([m({type:ae})],Bc.prototype,"privateKey",void 0);h([m({type:Bn,context:0,optional:!0})],Bc.prototype,"parameters",void 0);h([m({type:b.BitString,context:1,optional:!0})],Bc.prototype,"publicKey",void 0);class za{constructor(e={}){this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.Integer,converter:_e})],za.prototype,"r",void 0);h([m({type:b.Integer,converter:_e})],za.prototype,"s",void 0);const ot="1.2.840.113549.1.1",gr=`${ot}.1`,M4=`${ot}.7`,q4=`${ot}.9`,po=`${ot}.10`,F4=`${ot}.2`,H4=`${ot}.4`,Aa=`${ot}.5`,V4=`${ot}.14`,Dd=`${ot}.11`,Ea=`${ot}.12`,Ca=`${ot}.13`,Jy=`${ot}.15`,Xy=`${ot}.16`,Na="1.3.14.3.2.26",Zy="2.16.840.1.101.3.4.2.4",Ia="2.16.840.1.101.3.4.2.1",ja="2.16.840.1.101.3.4.2.2",Pa="2.16.840.1.101.3.4.2.3",K4="2.16.840.1.101.3.4.2.5",G4="2.16.840.1.101.3.4.2.6",W4="1.2.840.113549.2.2",J4="1.2.840.113549.2.5",Lc=`${ot}.8`;function je(t){return new U({algorithm:t,parameters:null})}je(W4);je(J4);const mr=je(Na);je(Zy);je(Ia);je(ja);je(Pa);je(K4);je(G4);const Yy=new U({algorithm:Lc,parameters:O.serialize(mr)}),Qy=new U({algorithm:q4,parameters:O.serialize(ca.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});je(gr);je(F4);je(H4);je(Aa);je(Jy);je(Xy);je(Ea);je(Ca);je(Jy);je(Xy);class Uc{constructor(e={}){this.hashAlgorithm=new U(mr),this.maskGenAlgorithm=new U({algorithm:Lc,parameters:O.serialize(mr)}),this.pSourceAlgorithm=new U(Qy),Object.assign(this,e)}}h([m({type:U,context:0,defaultValue:mr})],Uc.prototype,"hashAlgorithm",void 0);h([m({type:U,context:1,defaultValue:Yy})],Uc.prototype,"maskGenAlgorithm",void 0);h([m({type:U,context:2,defaultValue:Qy})],Uc.prototype,"pSourceAlgorithm",void 0);new U({algorithm:M4,parameters:O.serialize(new Uc)});class _r{constructor(e={}){this.hashAlgorithm=new U(mr),this.maskGenAlgorithm=new U({algorithm:Lc,parameters:O.serialize(mr)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}}h([m({type:U,context:0,defaultValue:mr})],_r.prototype,"hashAlgorithm",void 0);h([m({type:U,context:1,defaultValue:Yy})],_r.prototype,"maskGenAlgorithm",void 0);h([m({type:b.Integer,context:2,defaultValue:20})],_r.prototype,"saltLength",void 0);h([m({type:b.Integer,context:3,defaultValue:1})],_r.prototype,"trailerField",void 0);new U({algorithm:po,parameters:O.serialize(new _r)});class Dc{constructor(e={}){this.digestAlgorithm=new U,this.digest=new ae,Object.assign(this,e)}}h([m({type:U})],Dc.prototype,"digestAlgorithm",void 0);h([m({type:ae})],Dc.prototype,"digest",void 0);var Md;class Mc{constructor(e={}){this.prime=new ArrayBuffer(0),this.exponent=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.Integer,converter:_e})],Mc.prototype,"prime",void 0);h([m({type:b.Integer,converter:_e})],Mc.prototype,"exponent",void 0);h([m({type:b.Integer,converter:_e})],Mc.prototype,"coefficient",void 0);let qd=Md=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Md.prototype)}};qd=Md=h([j({type:C.Sequence,itemType:Mc})],qd);class Qt{constructor(e={}){this.version=0,this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),this.privateExponent=new ArrayBuffer(0),this.prime1=new ArrayBuffer(0),this.prime2=new ArrayBuffer(0),this.exponent1=new ArrayBuffer(0),this.exponent2=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.Integer})],Qt.prototype,"version",void 0);h([m({type:b.Integer,converter:_e})],Qt.prototype,"modulus",void 0);h([m({type:b.Integer,converter:_e})],Qt.prototype,"publicExponent",void 0);h([m({type:b.Integer,converter:_e})],Qt.prototype,"privateExponent",void 0);h([m({type:b.Integer,converter:_e})],Qt.prototype,"prime1",void 0);h([m({type:b.Integer,converter:_e})],Qt.prototype,"prime2",void 0);h([m({type:b.Integer,converter:_e})],Qt.prototype,"exponent1",void 0);h([m({type:b.Integer,converter:_e})],Qt.prototype,"exponent2",void 0);h([m({type:b.Integer,converter:_e})],Qt.prototype,"coefficient",void 0);h([m({type:qd,optional:!0})],Qt.prototype,"otherPrimeInfos",void 0);class xp{constructor(e={}){this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.Integer,converter:_e})],xp.prototype,"modulus",void 0);h([m({type:b.Integer,converter:_e})],xp.prototype,"publicExponent",void 0);var Fd;(function(t){t[t.Transient=0]="Transient",t[t.Singleton=1]="Singleton",t[t.ResolutionScoped=2]="ResolutionScoped",t[t.ContainerScoped=3]="ContainerScoped"})(Fd||(Fd={}));const tt=Fd;var Hd=function(t,e){return Hd=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},Hd(t,e)};function Sp(t,e){Hd(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function X4(t,e,n,r){function i(s){return s instanceof n?s:new n(function(a){a(s)})}return new(n||(n=Promise))(function(s,a){function c(u){try{d(r.next(u))}catch(f){a(f)}}function l(u){try{d(r.throw(u))}catch(f){a(f)}}function d(u){u.done?s(u.value):i(u.value).then(c,l)}d((r=r.apply(t,[])).next())})}function Z4(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,a;return a={next:c(0),throw:c(1),return:c(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function c(d){return function(u){return l([d,u])}}function l(d){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(s=d[0]&2?i.return:d[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,d[1])).done)return s;switch(i=0,s&&(d=[d[0]&2,s.value]),d[0]){case 0:case 1:s=d;break;case 4:return n.label++,{value:d[1],done:!1};case 5:n.label++,i=d[1],d=[0];continue;case 7:d=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(d[0]===6||d[0]===2)){n=0;continue}if(d[0]===3&&(!s||d[1]>s[0]&&d[1]<s[3])){n.label=d[1];break}if(d[0]===6&&n.label<s[1]){n.label=s[1],s=d;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(d);break}s[2]&&n.ops.pop(),n.trys.pop();continue}d=e.call(t,n)}catch(u){d=[6,u],i=0}finally{r=s=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}function _s(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Oa(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,s=[],a;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(c){a={error:c}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return s}function Wn(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Oa(arguments[e]));return t}var Y4="injectionTokens";function Q4(t){var e=Reflect.getMetadata("design:paramtypes",t)||[],n=Reflect.getOwnMetadata(Y4,t)||{};return Object.keys(n).forEach(function(r){e[+r]=n[r]}),e}function e1(t){return!!t.useClass}function Vd(t){return!!t.useFactory}var t1=(function(){function t(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return t.prototype.createProxy=function(e){var n=this,r={},i=!1,s,a=function(){return i||(s=e(n.wrap()),i=!0),s};return new Proxy(r,this.createHandler(a))},t.prototype.createHandler=function(e){var n={},r=function(i){n[i]=function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];s[0]=e();var c=Reflect[i];return c.apply(void 0,Wn(s))}};return this.reflectMethods.forEach(r),n},t})();function Cr(t){return typeof t=="string"||typeof t=="symbol"}function e$(t){return typeof t=="object"&&"token"in t&&"multiple"in t}function Nh(t){return typeof t=="object"&&"token"in t&&"transform"in t}function t$(t){return typeof t=="function"||t instanceof t1}function Is(t){return!!t.useToken}function js(t){return t.useValue!=null}function n$(t){return e1(t)||js(t)||Is(t)||Vd(t)}var zp=(function(){function t(){this._registryMap=new Map}return t.prototype.entries=function(){return this._registryMap.entries()},t.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},t.prototype.get=function(e){this.ensure(e);var n=this._registryMap.get(e);return n[n.length-1]||null},t.prototype.set=function(e,n){this.ensure(e),this._registryMap.get(e).push(n)},t.prototype.setAll=function(e,n){this._registryMap.set(e,n)},t.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},t.prototype.clear=function(){this._registryMap.clear()},t.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},t})(),r$=(function(t){Sp(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(zp),ys=(function(){function t(){this.scopedResolutions=new Map}return t})();function i$(t,e){if(t===null)return"at position #"+e;var n=t.split(",")[e].trim();return'"'+n+'" at position #'+e}function o$(t,e,n){return n===void 0&&(n=" "),Wn([t],e.message.split(`
72
72
  `).map(function(r){return n+r})).join(`
73
- `)}function s$(t,e,n){var r=Oa(t.toString().match(/constructor\(([\w, ]+)\)/)||[],2),i=r[1],s=i===void 0?null:i,a=i$(s,e);return o$("Cannot inject the dependency "+a+' of "'+t.name+'" constructor. Reason:',n)}function a$(t){if(typeof t.dispose!="function")return!1;var e=t.dispose;return!(e.length>0)}var c$=(function(t){Sp(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(zp),l$=(function(t){Sp(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(zp),d$=(function(){function t(){this.preResolution=new c$,this.postResolution=new l$}return t})(),n1=new Map,u$=(function(){function t(e){this.parent=e,this._registry=new r$,this.interceptors=new d$,this.disposed=!1,this.disposables=new Set}return t.prototype.register=function(e,n,r){r===void 0&&(r={lifecycle:tt.Transient}),this.ensureNotDisposed();var i;if(n$(n)?i=n:i={useClass:n},Is(i))for(var s=[e],a=i;a!=null;){var c=a.useToken;if(s.includes(c))throw new Error("Token registration cycle detected! "+Wn(s,[c]).join(" -> "));s.push(c);var l=this._registry.get(c);l&&Is(l.provider)?a=l.provider:a=null}if((r.lifecycle===tt.Singleton||r.lifecycle==tt.ContainerScoped||r.lifecycle==tt.ResolutionScoped)&&(js(i)||Vd(i)))throw new Error('Cannot use lifecycle "'+tt[r.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:i,options:r}),this},t.prototype.registerType=function(e,n){return this.ensureNotDisposed(),Cr(n)?this.register(e,{useToken:n}):this.register(e,{useClass:n})},t.prototype.registerInstance=function(e,n){return this.ensureNotDisposed(),this.register(e,{useValue:n})},t.prototype.registerSingleton=function(e,n){if(this.ensureNotDisposed(),Cr(e)){if(Cr(n))return this.register(e,{useToken:n},{lifecycle:tt.Singleton});if(n)return this.register(e,{useClass:n},{lifecycle:tt.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var r=e;return n&&!Cr(n)&&(r=n),this.register(e,{useClass:r},{lifecycle:tt.Singleton})},t.prototype.resolve=function(e,n,r){n===void 0&&(n=new ys),r===void 0&&(r=!1),this.ensureNotDisposed();var i=this.getRegistration(e);if(!i&&Cr(e)){if(r)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),i){var s=this.resolveRegistration(i,n);return this.executePostResolutionInterceptor(e,s,"Single"),s}if(t$(e)){var s=this.construct(e,n);return this.executePostResolutionInterceptor(e,s,"Single"),s}throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},t.prototype.executePreResolutionInterceptor=function(e,n){var r,i;if(this.interceptors.preResolution.has(e)){var s=[];try{for(var a=_s(this.interceptors.preResolution.getAll(e)),c=a.next();!c.done;c=a.next()){var l=c.value;l.options.frequency!="Once"&&s.push(l),l.callback(e,n)}}catch(d){r={error:d}}finally{try{c&&!c.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}this.interceptors.preResolution.setAll(e,s)}},t.prototype.executePostResolutionInterceptor=function(e,n,r){var i,s;if(this.interceptors.postResolution.has(e)){var a=[];try{for(var c=_s(this.interceptors.postResolution.getAll(e)),l=c.next();!l.done;l=c.next()){var d=l.value;d.options.frequency!="Once"&&a.push(d),d.callback(e,n,r)}}catch(u){i={error:u}}finally{try{l&&!l.done&&(s=c.return)&&s.call(c)}finally{if(i)throw i.error}}this.interceptors.postResolution.setAll(e,a)}},t.prototype.resolveRegistration=function(e,n){if(this.ensureNotDisposed(),e.options.lifecycle===tt.ResolutionScoped&&n.scopedResolutions.has(e))return n.scopedResolutions.get(e);var r=e.options.lifecycle===tt.Singleton,i=e.options.lifecycle===tt.ContainerScoped,s=r||i,a;return js(e.provider)?a=e.provider.useValue:Is(e.provider)?a=s?e.instance||(e.instance=this.resolve(e.provider.useToken,n)):this.resolve(e.provider.useToken,n):e1(e.provider)?a=s?e.instance||(e.instance=this.construct(e.provider.useClass,n)):this.construct(e.provider.useClass,n):Vd(e.provider)?a=e.provider.useFactory(this):a=this.construct(e.provider,n),e.options.lifecycle===tt.ResolutionScoped&&n.scopedResolutions.set(e,a),a},t.prototype.resolveAll=function(e,n,r){var i=this;n===void 0&&(n=new ys),r===void 0&&(r=!1),this.ensureNotDisposed();var s=this.getAllRegistrations(e);if(!s&&Cr(e)){if(r)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),s){var a=s.map(function(l){return i.resolveRegistration(l,n)});return this.executePostResolutionInterceptor(e,a,"All"),a}var c=[this.construct(e,n)];return this.executePostResolutionInterceptor(e,c,"All"),c},t.prototype.isRegistered=function(e,n){return n===void 0&&(n=!1),this.ensureNotDisposed(),this._registry.has(e)||n&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},t.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},t.prototype.clearInstances=function(){var e,n;this.ensureNotDisposed();try{for(var r=_s(this._registry.entries()),i=r.next();!i.done;i=r.next()){var s=Oa(i.value,2),a=s[0],c=s[1];this._registry.setAll(a,c.filter(function(l){return!js(l.provider)}).map(function(l){return l.instance=void 0,l}))}}catch(l){e={error:l}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(e)throw e.error}}},t.prototype.createChildContainer=function(){var e,n;this.ensureNotDisposed();var r=new t(this);try{for(var i=_s(this._registry.entries()),s=i.next();!s.done;s=i.next()){var a=Oa(s.value,2),c=a[0],l=a[1];l.some(function(d){var u=d.options;return u.lifecycle===tt.ContainerScoped})&&r._registry.setAll(c,l.map(function(d){return d.options.lifecycle===tt.ContainerScoped?{provider:d.provider,options:d.options}:d}))}}catch(d){e={error:d}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(e)throw e.error}}return r},t.prototype.beforeResolution=function(e,n,r){r===void 0&&(r={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:n,options:r})},t.prototype.afterResolution=function(e,n,r){r===void 0&&(r={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:n,options:r})},t.prototype.dispose=function(){return X4(this,void 0,void 0,function(){var e;return Z4(this,function(n){switch(n.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(r){var i=r.dispose();i&&e.push(i)}),[4,Promise.all(e)];case 1:return n.sent(),[2]}})})},t.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},t.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},t.prototype.construct=function(e,n){var r=this;if(e instanceof t1)return e.createProxy(function(s){return r.resolve(s,n)});var i=(function(){var s=n1.get(e);if(!s||s.length===0){if(e.length===0)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var a=s.map(r.resolveParams(n,e));return new(e.bind.apply(e,Wn([void 0],a)))})();return a$(i)&&this.disposables.add(i),i},t.prototype.resolveParams=function(e,n){var r=this;return function(i,s){var a,c,l;try{return e$(i)?Nh(i)?i.multiple?(a=r.resolve(i.transform)).transform.apply(a,Wn([r.resolveAll(i.token,new ys,i.isOptional)],i.transformArgs)):(c=r.resolve(i.transform)).transform.apply(c,Wn([r.resolve(i.token,e,i.isOptional)],i.transformArgs)):i.multiple?r.resolveAll(i.token,new ys,i.isOptional):r.resolve(i.token,e,i.isOptional):Nh(i)?(l=r.resolve(i.transform,e)).transform.apply(l,Wn([r.resolve(i.token,e)],i.transformArgs)):r.resolve(i,e)}catch(d){throw new Error(s$(n,s,d))}}},t.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},t})(),Fe=new u$;function qc(t){return function(e){n1.set(e,Q4(e))}}if(typeof Reflect>"u"||!Reflect.getMetadata)throw new Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`);var Kd;class Fc{constructor(e={}){this.attrId="",this.attrValues=[],Object.assign(e)}}h([m({type:b.ObjectIdentifier})],Fc.prototype,"attrId",void 0);h([m({type:b.Any,repeated:"set"})],Fc.prototype,"attrValues",void 0);let Ih=Kd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Kd.prototype)}};Ih=Kd=h([j({type:C.Sequence,itemType:Fc})],Ih);var Gd;let jh=Gd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Gd.prototype)}};jh=Gd=h([j({type:C.Sequence,itemType:vi})],jh);class r1{constructor(e={}){this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],r1.prototype,"certId",void 0);h([m({type:b.Any,context:0})],r1.prototype,"certValue",void 0);class i1{constructor(e={}){this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],i1.prototype,"crlId",void 0);h([m({type:b.Any,context:0})],i1.prototype,"crltValue",void 0);class o1 extends ae{}let Hc=class{constructor(e={}){this.encryptionAlgorithm=new U,this.encryptedData=new o1,Object.assign(this,e)}};h([m({type:U})],Hc.prototype,"encryptionAlgorithm",void 0);h([m({type:o1})],Hc.prototype,"encryptedData",void 0);var Wd,Jd;(function(t){t[t.v1=0]="v1"})(Jd||(Jd={}));class s1 extends ae{}let Xd=Wd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Wd.prototype)}};Xd=Wd=h([j({type:C.Sequence,itemType:pn})],Xd);class os{constructor(e={}){this.version=Jd.v1,this.privateKeyAlgorithm=new U,this.privateKey=new s1,Object.assign(this,e)}}h([m({type:b.Integer})],os.prototype,"version",void 0);h([m({type:U})],os.prototype,"privateKeyAlgorithm",void 0);h([m({type:s1})],os.prototype,"privateKey",void 0);h([m({type:Xd,implicit:!0,context:0,optional:!0})],os.prototype,"attributes",void 0);let Ph=class extends os{};Ph=h([j({type:C.Sequence})],Ph);let Oh=class extends Hc{};Oh=h([j({type:C.Sequence})],Oh);class a1{constructor(e={}){this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],a1.prototype,"secretTypeId",void 0);h([m({type:b.Any,context:0})],a1.prototype,"secretValue",void 0);class ss{constructor(e={}){this.mac=new Dc,this.macSalt=new ae,this.iterations=1,Object.assign(this,e)}}h([m({type:Dc})],ss.prototype,"mac",void 0);h([m({type:ae})],ss.prototype,"macSalt",void 0);h([m({type:b.Integer,defaultValue:1})],ss.prototype,"iterations",void 0);class Vc{constructor(e={}){this.version=3,this.authSafe=new vi,this.macData=new ss,Object.assign(this,e)}}h([m({type:b.Integer})],Vc.prototype,"version",void 0);h([m({type:vi})],Vc.prototype,"authSafe",void 0);h([m({type:ss,optional:!0})],Vc.prototype,"macData",void 0);var Zd;class Kc{constructor(e={}){this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],Kc.prototype,"bagId",void 0);h([m({type:b.Any,context:0})],Kc.prototype,"bagValue",void 0);h([m({type:Fc,repeated:"set",optional:!0})],Kc.prototype,"bagAttributes",void 0);let Th=Zd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Zd.prototype)}};Th=Zd=h([j({type:C.Sequence,itemType:Kc})],Th);var Yd,Qd,eu;const c1="1.2.840.113549.1.9",l1=`${c1}.7`,Ap=`${c1}.14`;let Ta=class extends qe{constructor(e={}){super(e)}toString(){return this.ia5String||super.toString()}};h([m({type:b.IA5String})],Ta.prototype,"ia5String",void 0);Ta=h([j({type:C.Choice})],Ta);let Rh=class extends vi{};Rh=h([j({type:C.Sequence})],Rh);let Bh=class extends Vc{};Bh=h([j({type:C.Sequence})],Bh);let Lh=class extends Hc{};Lh=h([j({type:C.Sequence})],Lh);let tu=class{constructor(e=""){this.value=e}toString(){return this.value}};h([m({type:b.IA5String})],tu.prototype,"value",void 0);tu=h([j({type:C.Choice})],tu);let Uh=class extends Ta{};Uh=h([j({type:C.Choice})],Uh);let Dh=class extends qe{};Dh=h([j({type:C.Choice})],Dh);let nu=class{constructor(e=new Date){this.value=e}};h([m({type:b.GeneralizedTime})],nu.prototype,"value",void 0);nu=h([j({type:C.Choice})],nu);let Mh=class extends qe{};Mh=h([j({type:C.Choice})],Mh);let ru=class{constructor(e="M"){this.value=e}toString(){return this.value}};h([m({type:b.PrintableString})],ru.prototype,"value",void 0);ru=h([j({type:C.Choice})],ru);let Ra=class{constructor(e=""){this.value=e}toString(){return this.value}};h([m({type:b.PrintableString})],Ra.prototype,"value",void 0);Ra=h([j({type:C.Choice})],Ra);let qh=class extends Ra{};qh=h([j({type:C.Choice})],qh);let Fh=class extends qe{};Fh=h([j({type:C.Choice})],Fh);let iu=class{constructor(e=""){this.value=e}toString(){return this.value}};h([m({type:b.ObjectIdentifier})],iu.prototype,"value",void 0);iu=h([j({type:C.Choice})],iu);let Hh=class extends Ue{};Hh=h([j({type:C.Choice})],Hh);let ou=class{constructor(e=0){this.value=e}toString(){return this.value.toString()}};h([m({type:b.Integer})],ou.prototype,"value",void 0);ou=h([j({type:C.Choice})],ou);let Vh=class extends Yt{};Vh=h([j({type:C.Sequence})],Vh);let Ba=class extends qe{};Ba=h([j({type:C.Choice})],Ba);let Kh=Yd=class extends Tn{constructor(e){super(e),Object.setPrototypeOf(this,Yd.prototype)}};Kh=Yd=h([j({type:C.Sequence})],Kh);let Gh=Qd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Qd.prototype)}};Gh=Qd=h([j({type:C.Set,itemType:bi})],Gh);let su=class{constructor(e=""){this.value=e}toString(){return this.value}};h([m({type:b.BmpString})],su.prototype,"value",void 0);su=h([j({type:C.Choice})],su);let au=class extends U{};au=h([j({type:C.Sequence})],au);let Wh=eu=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,eu.prototype)}};Wh=eu=h([j({type:C.Sequence,itemType:au})],Wh);var cu;let La=cu=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,cu.prototype)}};La=cu=h([j({type:C.Sequence,itemType:pn})],La);class xi{constructor(e={}){this.version=0,this.subject=new Ce,this.subjectPKInfo=new At,this.attributes=new La,Object.assign(this,e)}}h([m({type:b.Integer})],xi.prototype,"version",void 0);h([m({type:Ce})],xi.prototype,"subject",void 0);h([m({type:At})],xi.prototype,"subjectPKInfo",void 0);h([m({type:La,implicit:!0,context:0,optional:!0})],xi.prototype,"attributes",void 0);class Co{constructor(e={}){this.certificationRequestInfo=new xi,this.signatureAlgorithm=new U,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:xi,raw:!0})],Co.prototype,"certificationRequestInfo",void 0);h([m({type:U})],Co.prototype,"signatureAlgorithm",void 0);h([m({type:b.BitString})],Co.prototype,"signature",void 0);const as="crypto.algorithm";class p${getAlgorithms(){return Fe.resolveAll(as)}toAsnAlgorithm(e){({...e});for(const n of this.getAlgorithms()){const r=n.toAsnAlgorithm(e);if(r)return r}if(/^[0-9.]+$/.test(e.name)){const n=new U({algorithm:e.name});if("parameters"in e){const r=e;n.parameters=r.parameters}return n}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(const r of this.getAlgorithms()){const i=r.toWebAlgorithm(e);if(i)return i}return{name:e.algorithm,parameters:e.parameters}}}const yr="crypto.algorithmProvider";Fe.registerSingleton(yr,p$);var Ps;const st="1.3.36.3.3.2.8.1.1",Jh=`${st}.1`,Xh=`${st}.2`,Zh=`${st}.3`,Yh=`${st}.4`,Qh=`${st}.5`,eg=`${st}.6`,tg=`${st}.7`,ng=`${st}.8`,rg=`${st}.9`,ig=`${st}.10`,og=`${st}.11`,sg=`${st}.12`,ag=`${st}.13`,cg=`${st}.14`,lg="brainpoolP160r1",dg="brainpoolP160t1",ug="brainpoolP192r1",pg="brainpoolP192t1",fg="brainpoolP224r1",hg="brainpoolP224t1",gg="brainpoolP256r1",mg="brainpoolP256t1",_g="brainpoolP320r1",yg="brainpoolP320t1",wg="brainpoolP384r1",bg="brainpoolP384t1",vg="brainpoolP512r1",$g="brainpoolP512t1",ve="ECDSA";let No=Ps=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case ve.toLowerCase():if("hash"in e)switch((typeof e.hash=="string"?e.hash:e.hash.name).toLowerCase()){case"sha-1":return R4;case"sha-256":return B4;case"sha-384":return L4;case"sha-512":return U4}else if("namedCurve"in e){let n="";switch(e.namedCurve){case"P-256":n=Ah;break;case"K-256":n=Ps.SECP256K1;break;case"P-384":n=Eh;break;case"P-521":n=Ch;break;case lg:n=Jh;break;case dg:n=Xh;break;case ug:n=Zh;break;case pg:n=Yh;break;case fg:n=Qh;break;case hg:n=eg;break;case gg:n=tg;break;case mg:n=ng;break;case _g:n=rg;break;case yg:n=ig;break;case wg:n=og;break;case bg:n=sg;break;case vg:n=ag;break;case $g:n=cg;break}if(n)return new U({algorithm:Ao,parameters:O.serialize(new Bn({namedCurve:n}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case bp:return{name:ve,hash:{name:"SHA-1"}};case vp:return{name:ve,hash:{name:"SHA-256"}};case $p:return{name:ve,hash:{name:"SHA-384"}};case kp:return{name:ve,hash:{name:"SHA-512"}};case Ao:{if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(O.parse(e.parameters,Bn).namedCurve){case Ah:return{name:ve,namedCurve:"P-256"};case Ps.SECP256K1:return{name:ve,namedCurve:"K-256"};case Eh:return{name:ve,namedCurve:"P-384"};case Ch:return{name:ve,namedCurve:"P-521"};case Jh:return{name:ve,namedCurve:lg};case Xh:return{name:ve,namedCurve:dg};case Zh:return{name:ve,namedCurve:ug};case Yh:return{name:ve,namedCurve:pg};case Qh:return{name:ve,namedCurve:fg};case eg:return{name:ve,namedCurve:hg};case tg:return{name:ve,namedCurve:gg};case ng:return{name:ve,namedCurve:mg};case rg:return{name:ve,namedCurve:_g};case ig:return{name:ve,namedCurve:yg};case og:return{name:ve,namedCurve:wg};case sg:return{name:ve,namedCurve:bg};case ag:return{name:ve,namedCurve:vg};case cg:return{name:ve,namedCurve:$g}}}}return null}};No.SECP256K1="1.3.132.0.10";No=Ps=h([qc()],No);Fe.registerSingleton(as,No);const d1=Symbol("name"),u1=Symbol("value");class de{constructor(e,n={},r=""){this[d1]=e,this[u1]=r;for(const i in n)this[i]=n[i]}}de.NAME=d1;de.VALUE=u1;class f${static toTextObject(e){const n=new de("Algorithm Identifier",{},Mn.toString(e.algorithm));if(e.parameters)if(e.algorithm===Ao){const r=new No().toWebAlgorithm(e);r&&"namedCurve"in r?n["Named Curve"]=r.namedCurve:n.Parameters=e.parameters}else n.Parameters=e.parameters;return n}}class Mn{static toString(e){const n=this.items[e];return n||e}}Mn.items={[Na]:"sha1",[Zy]:"sha224",[Ia]:"sha256",[ja]:"sha384",[Pa]:"sha512",[gr]:"rsaEncryption",[Aa]:"sha1WithRSAEncryption",[V4]:"sha224WithRSAEncryption",[Dd]:"sha256WithRSAEncryption",[Ea]:"sha384WithRSAEncryption",[Ca]:"sha512WithRSAEncryption",[Ao]:"ecPublicKey",[bp]:"ecdsaWithSHA1",[Wy]:"ecdsaWithSHA224",[vp]:"ecdsaWithSHA256",[$p]:"ecdsaWithSHA384",[kp]:"ecdsaWithSHA512",[C4]:"TLS WWW server authentication",[N4]:"TLS WWW client authentication",[I4]:"Code Signing",[j4]:"E-mail Protection",[P4]:"Time Stamping",[O4]:"OCSP Signing",[T4]:"Signed Data"};class wr{static serialize(e){return this.serializeObj(e).join(`
74
- `)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,n=0){const r=[];let i=this.pad(n++),s="";const a=e[de.VALUE];a&&(s=` ${a}`),r.push(`${i}${e[de.NAME]}:${s}`),i=this.pad(n);for(const c in e){if(typeof c=="symbol")continue;const l=e[c],d=c?`${c}: `:"";if(typeof l=="string"||typeof l=="number"||typeof l=="boolean")r.push(`${i}${d}${l}`);else if(l instanceof Date)r.push(`${i}${d}${l.toUTCString()}`);else if(Array.isArray(l))for(const u of l)u[de.NAME]=c,r.push(...this.serializeObj(u,n));else if(l instanceof de)l[de.NAME]=c,r.push(...this.serializeObj(l,n));else if(T.isBufferSource(l))c?(r.push(`${i}${d}`),r.push(...this.serializeBufferSource(l,n+1))):r.push(...this.serializeBufferSource(l,n));else if("toTextObject"in l){const u=l.toTextObject();u[de.NAME]=c,r.push(...this.serializeObj(u,n))}else throw new TypeError("Cannot serialize data in text format. Unsupported type.")}return r}static serializeBufferSource(e,n=0){const r=this.pad(n),i=T.toUint8Array(e),s=[];for(let a=0;a<i.length;){const c=[];for(let l=0;l<16&&a<i.length;l++){l===8&&c.push("");const d=i[a++].toString(16).padStart(2,"0");c.push(d)}s.push(`${r}${c.join(" ")}`)}return s}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}}wr.oidSerializer=Mn;wr.algorithmSerializer=f$;var jr;class qn{get rawData(){return re(this,jr,"f")||ye(this,jr,O.serialize(this.asn),"f"),re(this,jr,"f")}constructor(...e){jr.set(this,void 0),T.isBufferSource(e[0])?(this.asn=O.parse(e[0],e[1]),ye(this,jr,T.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof qn?P_(e.rawData,this.rawData):!1}toString(e="text"){switch(e){case"asn":return O.toString(this.rawData);case"text":return wr.serialize(this.toTextObject());case"hex":return F.ToHex(this.rawData);case"base64":return F.ToBase64(this.rawData);case"base64url":return F.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){const e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new de(this.getTextName(),{},e)}}jr=new WeakMap;qn.NAME="ASN";class pt extends qn{constructor(...e){let n;T.isBufferSource(e[0])?n=T.toArrayBuffer(e[0]):n=O.serialize(new yt({extnID:e[0],critical:e[1],extnValue:new ae(T.toArrayBuffer(e[2]))})),super(n,yt)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[de.NAME]===pt.NAME&&(e[de.NAME]=Mn.toString(this.type)),e}}var p1;class En{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&e.extractable!==void 0}constructor(){this.items=new Map,this[p1]="CryptoProvider",typeof self<"u"&&typeof crypto<"u"?this.set(En.DEFAULT,crypto):typeof global<"u"&&global.crypto&&global.crypto.subtle&&this.set(En.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,n){return this.items.forEach(e,n)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=En.DEFAULT){const n=this.items.get(e.toLowerCase());if(!n)throw new Error(`Cannot get Crypto by name '${e}'`);return n}set(e,n){if(typeof e=="string"){if(!n)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),n)}else this.items.set(En.DEFAULT,e);return this}}p1=Symbol.toStringTag;En.DEFAULT="default";const Oe=new En,h$=/^[0-2](?:\.[1-9][0-9]*)+$/;function g$(t){return new RegExp(h$).test(t)}class f1{constructor(e={}){this.items={};for(const n in e)this.register(n,e[n])}get(e){return this.items[e]||null}findId(e){return g$(e)?e:this.get(e)}register(e,n){this.items[e]=n,this.items[n]=e}}const rt=new f1;rt.register("CN","2.5.4.3");rt.register("L","2.5.4.7");rt.register("ST","2.5.4.8");rt.register("O","2.5.4.10");rt.register("OU","2.5.4.11");rt.register("C","2.5.4.6");rt.register("DC","0.9.2342.19200300.100.1.25");rt.register("E","1.2.840.113549.1.9.1");rt.register("G","2.5.4.42");rt.register("I","2.5.4.43");rt.register("SN","2.5.4.4");rt.register("T","2.5.4.12");function m$(t,e){return`\\${F.ToHex(F.FromUtf8String(e)).toUpperCase()}`}function _$(t){return t.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,m$)}class Et{static isASCII(e){for(let n=0;n<e.length;n++)if(e.charCodeAt(n)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,n={}){this.extraNames=new f1,this.asn=new Ce;for(const r in n)if(Object.prototype.hasOwnProperty.call(n,r)){const i=n[r];this.extraNames.register(r,i)}typeof e=="string"?this.asn=this.fromString(e):e instanceof Ce?this.asn=e:T.isBufferSource(e)?this.asn=O.parse(e,Ce):this.asn=this.fromJSON(e)}getField(e){const n=this.extraNames.findId(e)||rt.findId(e),r=[];for(const i of this.asn)for(const s of i)s.type===n&&r.push(s.value.toString());return r}getName(e){return this.extraNames.get(e)||rt.get(e)}toString(){return this.asn.map(e=>e.map(n=>{const r=this.getName(n.type)||n.type,i=n.value.anyValue?`#${F.ToHex(n.value.anyValue)}`:_$(n.value.toString());return`${r}=${i}`}).join("+")).join(", ")}toJSON(){var e;const n=[];for(const r of this.asn){const i={};for(const s of r){const a=this.getName(s.type)||s.type;(e=i[a])!==null&&e!==void 0||(i[a]=[]),i[a].push(s.value.anyValue?`#${F.ToHex(s.value.anyValue)}`:s.value.toString())}n.push(i)}return n}fromString(e){const n=new Ce,r=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;let i=null,s=",";for(;i=r.exec(`${e},`);){let[,a,c]=i;const l=c[c.length-1];(l===","||l==="+")&&(c=c.slice(0,c.length-1),i[3]=l);const d=i[3];a=this.getTypeOid(a);const u=this.createAttribute(a,c);s==="+"?n[n.length-1].push(u):n.push(new Qr([u])),s=d}return n}fromJSON(e){const n=new Ce;for(const r of e){const i=new Qr;for(const s in r){const a=this.getTypeOid(s),c=r[s];for(const l of c){const d=this.createAttribute(a,l);i.push(d)}}n.push(i)}return n}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,n){const r=new $c({type:e});if(typeof n=="object")for(const i in n)switch(i){case"ia5String":r.value.ia5String=n[i];break;case"utf8String":r.value.utf8String=n[i];break;case"universalString":r.value.universalString=n[i];break;case"bmpString":r.value.bmpString=n[i];break;case"printableString":r.value.printableString=n[i];break}else if(n[0]==="#")r.value.anyValue=F.FromHex(n.slice(1));else{const i=this.processStringValue(n);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=i:Et.isPrintableString(i)?r.value.printableString=i:r.value.utf8String=i}return r}processStringValue(e){const n=/"(.*?[^\\])?"/.exec(e);return n&&(e=n[1]),e.replace(/\\0a/ig,`
75
- `).replace(/\\0d/ig,"\r").replace(/\\0g/ig," ").replace(/\\(.)/g,"$1")}toArrayBuffer(){return O.serialize(this.asn)}async getThumbprint(...e){var n;let r,i="SHA-1";return e.length>=1&&!(!((n=e[0])===null||n===void 0)&&n.subtle)?(i=e[0]||i,r=e[1]||Oe.get()):r=e[0]||Oe.get(),await r.subtle.digest(i,this.toArrayBuffer())}}const h1="Cannot initialize GeneralName from ASN.1 data.",kg=`${h1} Unsupported string format in use.`,y$=`${h1} Value doesn't match to GUID regular expression.`,xg=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Sg="1.3.6.1.4.1.311.25.1",zg="1.3.6.1.4.1.311.20.2.3",gl="dns",ml="dn",_l="email",yl="ip",wl="url",bl="guid",vl="upn",ws="id";class Cn extends qn{constructor(...e){let n;if(e.length===2)switch(e[0]){case ml:{const r=new Et(e[1]).toArrayBuffer(),i=O.parse(r,Ce);n=new ee({directoryName:i});break}case gl:n=new ee({dNSName:e[1]});break;case _l:n=new ee({rfc822Name:e[1]});break;case bl:{const r=new RegExp(xg,"i").exec(e[1]);if(!r)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");const i=r.slice(1).map((s,a)=>a<3?F.ToHex(new Uint8Array(F.FromHex(s)).reverse()):s).join("");n=new ee({otherName:new ko({typeId:Sg,value:O.serialize(new ae(F.FromHex(i)))})});break}case yl:n=new ee({iPAddress:e[1]});break;case ws:n=new ee({registeredID:e[1]});break;case vl:{n=new ee({otherName:new ko({typeId:zg,value:O.serialize(Ny.toASN(e[1]))})});break}case wl:n=new ee({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else T.isBufferSource(e[0])?n=O.parse(e[0],ee):n=e[0];super(n)}onInit(e){if(e.dNSName!=null)this.type=gl,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=_l,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=yl,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=wl,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=ws,this.value=e.registeredID;else if(e.directoryName!=null)this.type=ml,this.value=new Et(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===Sg){this.type=bl;const n=O.parse(e.otherName.value,ae),r=new RegExp(xg,"i").exec(F.ToHex(n));if(!r)throw new Error(y$);this.value=r.slice(1).map((i,s)=>s<3?F.ToHex(new Uint8Array(F.FromHex(i)).reverse()):i).join("-")}else if(e.otherName.typeId===zg)this.type=vl,this.value=O.parse(e.otherName.value,qe).toString();else throw new Error(kg);else throw new Error(kg)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case ml:case gl:case bl:case yl:case ws:case vl:case wl:e=this.type.toUpperCase();break;case _l:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let n=this.value;return this.type===ws&&(n=Mn.toString(n)),new de(e,void 0,n)}}class br extends qn{constructor(e){let n;if(e instanceof We)n=e;else if(Array.isArray(e)){const r=[];for(const i of e)if(i instanceof ee)r.push(i);else{const s=O.parse(new Cn(i.type,i.value).rawData,ee);r.push(s)}n=new We(r)}else if(T.isBufferSource(e))n=O.parse(e,We);else throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");super(n)}onInit(e){const n=[];for(const r of e){let i=null;try{i=new Cn(r)}catch{continue}n.push(i)}this.items=n}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){const e=super.toTextObjectEmpty();for(const n of this.items){const r=n.toTextObject();let i=e[r[de.NAME]];Array.isArray(i)||(i=[],e[r[de.NAME]]=i),i.push(r)}return e}}br.NAME="GeneralNames";const po="-{5}",Io="\\n",w$=`[^${Io}]+`,b$=`${po}BEGIN (${w$}(?=${po}))${po}`,v$=`${po}END \\1${po}`,ai="\\n",$$=`[^:${Io}]+`,k$=`(?:[^${Io}]+${ai}(?: +[^${Io}]+${ai})*)`,x$="[a-zA-Z0-9=+/]+",S$=`(?:${x$}${ai})+`,Ag=`${b$}${ai}(?:((?:${$$}: ${k$})+))?${ai}?(${S$})${v$}`;class ct{static isPem(e){return typeof e=="string"&&new RegExp(Ag,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const n=new RegExp(Ag,"g"),r=[];let i=null;for(;i=n.exec(e);){const s=i[3].replace(new RegExp(`[${Io}]+`,"g"),""),a={type:i[1],headers:[],rawData:F.FromBase64(s)},c=i[2];if(c){const l=c.split(new RegExp(ai,"g"));let d=null;for(const u of l){const[f,g]=u.split(/:(.*)/);if(g===void 0){if(!d)throw new Error("Cannot parse PEM string. Incorrect header value");d.value+=f.trim()}else d&&a.headers.push(d),d={key:f,value:g.trim()}}d&&a.headers.push(d)}r.push(a)}return r}static decode(e){return this.decodeWithHeaders(e).map(r=>r.rawData)}static decodeFirst(e){const n=this.decode(e);if(!n.length)throw new RangeError("PEM string doesn't contain any objects");return n[0]}static encode(e,n){if(Array.isArray(e)){const r=new Array;return n?e.forEach(i=>{if(!T.isBufferSource(i))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");r.push(this.encodeStruct({type:n,rawData:T.toArrayBuffer(i)}))}):e.forEach(i=>{if(!("type"in i))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");r.push(this.encodeStruct(i))}),r.join(`
73
+ `)}function s$(t,e,n){var r=Oa(t.toString().match(/constructor\(([\w, ]+)\)/)||[],2),i=r[1],s=i===void 0?null:i,a=i$(s,e);return o$("Cannot inject the dependency "+a+' of "'+t.name+'" constructor. Reason:',n)}function a$(t){if(typeof t.dispose!="function")return!1;var e=t.dispose;return!(e.length>0)}var c$=(function(t){Sp(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(zp),l$=(function(t){Sp(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(zp),d$=(function(){function t(){this.preResolution=new c$,this.postResolution=new l$}return t})(),n1=new Map,u$=(function(){function t(e){this.parent=e,this._registry=new r$,this.interceptors=new d$,this.disposed=!1,this.disposables=new Set}return t.prototype.register=function(e,n,r){r===void 0&&(r={lifecycle:tt.Transient}),this.ensureNotDisposed();var i;if(n$(n)?i=n:i={useClass:n},Is(i))for(var s=[e],a=i;a!=null;){var c=a.useToken;if(s.includes(c))throw new Error("Token registration cycle detected! "+Wn(s,[c]).join(" -> "));s.push(c);var l=this._registry.get(c);l&&Is(l.provider)?a=l.provider:a=null}if((r.lifecycle===tt.Singleton||r.lifecycle==tt.ContainerScoped||r.lifecycle==tt.ResolutionScoped)&&(js(i)||Vd(i)))throw new Error('Cannot use lifecycle "'+tt[r.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:i,options:r}),this},t.prototype.registerType=function(e,n){return this.ensureNotDisposed(),Cr(n)?this.register(e,{useToken:n}):this.register(e,{useClass:n})},t.prototype.registerInstance=function(e,n){return this.ensureNotDisposed(),this.register(e,{useValue:n})},t.prototype.registerSingleton=function(e,n){if(this.ensureNotDisposed(),Cr(e)){if(Cr(n))return this.register(e,{useToken:n},{lifecycle:tt.Singleton});if(n)return this.register(e,{useClass:n},{lifecycle:tt.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var r=e;return n&&!Cr(n)&&(r=n),this.register(e,{useClass:r},{lifecycle:tt.Singleton})},t.prototype.resolve=function(e,n,r){n===void 0&&(n=new ys),r===void 0&&(r=!1),this.ensureNotDisposed();var i=this.getRegistration(e);if(!i&&Cr(e)){if(r)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),i){var s=this.resolveRegistration(i,n);return this.executePostResolutionInterceptor(e,s,"Single"),s}if(t$(e)){var s=this.construct(e,n);return this.executePostResolutionInterceptor(e,s,"Single"),s}throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},t.prototype.executePreResolutionInterceptor=function(e,n){var r,i;if(this.interceptors.preResolution.has(e)){var s=[];try{for(var a=_s(this.interceptors.preResolution.getAll(e)),c=a.next();!c.done;c=a.next()){var l=c.value;l.options.frequency!="Once"&&s.push(l),l.callback(e,n)}}catch(d){r={error:d}}finally{try{c&&!c.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}this.interceptors.preResolution.setAll(e,s)}},t.prototype.executePostResolutionInterceptor=function(e,n,r){var i,s;if(this.interceptors.postResolution.has(e)){var a=[];try{for(var c=_s(this.interceptors.postResolution.getAll(e)),l=c.next();!l.done;l=c.next()){var d=l.value;d.options.frequency!="Once"&&a.push(d),d.callback(e,n,r)}}catch(u){i={error:u}}finally{try{l&&!l.done&&(s=c.return)&&s.call(c)}finally{if(i)throw i.error}}this.interceptors.postResolution.setAll(e,a)}},t.prototype.resolveRegistration=function(e,n){if(this.ensureNotDisposed(),e.options.lifecycle===tt.ResolutionScoped&&n.scopedResolutions.has(e))return n.scopedResolutions.get(e);var r=e.options.lifecycle===tt.Singleton,i=e.options.lifecycle===tt.ContainerScoped,s=r||i,a;return js(e.provider)?a=e.provider.useValue:Is(e.provider)?a=s?e.instance||(e.instance=this.resolve(e.provider.useToken,n)):this.resolve(e.provider.useToken,n):e1(e.provider)?a=s?e.instance||(e.instance=this.construct(e.provider.useClass,n)):this.construct(e.provider.useClass,n):Vd(e.provider)?a=e.provider.useFactory(this):a=this.construct(e.provider,n),e.options.lifecycle===tt.ResolutionScoped&&n.scopedResolutions.set(e,a),a},t.prototype.resolveAll=function(e,n,r){var i=this;n===void 0&&(n=new ys),r===void 0&&(r=!1),this.ensureNotDisposed();var s=this.getAllRegistrations(e);if(!s&&Cr(e)){if(r)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),s){var a=s.map(function(l){return i.resolveRegistration(l,n)});return this.executePostResolutionInterceptor(e,a,"All"),a}var c=[this.construct(e,n)];return this.executePostResolutionInterceptor(e,c,"All"),c},t.prototype.isRegistered=function(e,n){return n===void 0&&(n=!1),this.ensureNotDisposed(),this._registry.has(e)||n&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},t.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},t.prototype.clearInstances=function(){var e,n;this.ensureNotDisposed();try{for(var r=_s(this._registry.entries()),i=r.next();!i.done;i=r.next()){var s=Oa(i.value,2),a=s[0],c=s[1];this._registry.setAll(a,c.filter(function(l){return!js(l.provider)}).map(function(l){return l.instance=void 0,l}))}}catch(l){e={error:l}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(e)throw e.error}}},t.prototype.createChildContainer=function(){var e,n;this.ensureNotDisposed();var r=new t(this);try{for(var i=_s(this._registry.entries()),s=i.next();!s.done;s=i.next()){var a=Oa(s.value,2),c=a[0],l=a[1];l.some(function(d){var u=d.options;return u.lifecycle===tt.ContainerScoped})&&r._registry.setAll(c,l.map(function(d){return d.options.lifecycle===tt.ContainerScoped?{provider:d.provider,options:d.options}:d}))}}catch(d){e={error:d}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(e)throw e.error}}return r},t.prototype.beforeResolution=function(e,n,r){r===void 0&&(r={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:n,options:r})},t.prototype.afterResolution=function(e,n,r){r===void 0&&(r={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:n,options:r})},t.prototype.dispose=function(){return X4(this,void 0,void 0,function(){var e;return Z4(this,function(n){switch(n.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(r){var i=r.dispose();i&&e.push(i)}),[4,Promise.all(e)];case 1:return n.sent(),[2]}})})},t.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},t.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},t.prototype.construct=function(e,n){var r=this;if(e instanceof t1)return e.createProxy(function(s){return r.resolve(s,n)});var i=(function(){var s=n1.get(e);if(!s||s.length===0){if(e.length===0)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var a=s.map(r.resolveParams(n,e));return new(e.bind.apply(e,Wn([void 0],a)))})();return a$(i)&&this.disposables.add(i),i},t.prototype.resolveParams=function(e,n){var r=this;return function(i,s){var a,c,l;try{return e$(i)?Nh(i)?i.multiple?(a=r.resolve(i.transform)).transform.apply(a,Wn([r.resolveAll(i.token,new ys,i.isOptional)],i.transformArgs)):(c=r.resolve(i.transform)).transform.apply(c,Wn([r.resolve(i.token,e,i.isOptional)],i.transformArgs)):i.multiple?r.resolveAll(i.token,new ys,i.isOptional):r.resolve(i.token,e,i.isOptional):Nh(i)?(l=r.resolve(i.transform,e)).transform.apply(l,Wn([r.resolve(i.token,e)],i.transformArgs)):r.resolve(i,e)}catch(d){throw new Error(s$(n,s,d))}}},t.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},t})(),Fe=new u$;function qc(t){return function(e){n1.set(e,Q4(e))}}if(typeof Reflect>"u"||!Reflect.getMetadata)throw new Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`);var Kd;class Fc{constructor(e={}){this.attrId="",this.attrValues=[],Object.assign(e)}}h([m({type:b.ObjectIdentifier})],Fc.prototype,"attrId",void 0);h([m({type:b.Any,repeated:"set"})],Fc.prototype,"attrValues",void 0);let Ih=Kd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Kd.prototype)}};Ih=Kd=h([j({type:C.Sequence,itemType:Fc})],Ih);var Gd;let jh=Gd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Gd.prototype)}};jh=Gd=h([j({type:C.Sequence,itemType:$i})],jh);class r1{constructor(e={}){this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],r1.prototype,"certId",void 0);h([m({type:b.Any,context:0})],r1.prototype,"certValue",void 0);class i1{constructor(e={}){this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],i1.prototype,"crlId",void 0);h([m({type:b.Any,context:0})],i1.prototype,"crltValue",void 0);class o1 extends ae{}let Hc=class{constructor(e={}){this.encryptionAlgorithm=new U,this.encryptedData=new o1,Object.assign(this,e)}};h([m({type:U})],Hc.prototype,"encryptionAlgorithm",void 0);h([m({type:o1})],Hc.prototype,"encryptedData",void 0);var Wd,Jd;(function(t){t[t.v1=0]="v1"})(Jd||(Jd={}));class s1 extends ae{}let Xd=Wd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Wd.prototype)}};Xd=Wd=h([j({type:C.Sequence,itemType:pn})],Xd);class os{constructor(e={}){this.version=Jd.v1,this.privateKeyAlgorithm=new U,this.privateKey=new s1,Object.assign(this,e)}}h([m({type:b.Integer})],os.prototype,"version",void 0);h([m({type:U})],os.prototype,"privateKeyAlgorithm",void 0);h([m({type:s1})],os.prototype,"privateKey",void 0);h([m({type:Xd,implicit:!0,context:0,optional:!0})],os.prototype,"attributes",void 0);let Ph=class extends os{};Ph=h([j({type:C.Sequence})],Ph);let Oh=class extends Hc{};Oh=h([j({type:C.Sequence})],Oh);class a1{constructor(e={}){this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],a1.prototype,"secretTypeId",void 0);h([m({type:b.Any,context:0})],a1.prototype,"secretValue",void 0);class ss{constructor(e={}){this.mac=new Dc,this.macSalt=new ae,this.iterations=1,Object.assign(this,e)}}h([m({type:Dc})],ss.prototype,"mac",void 0);h([m({type:ae})],ss.prototype,"macSalt",void 0);h([m({type:b.Integer,defaultValue:1})],ss.prototype,"iterations",void 0);class Vc{constructor(e={}){this.version=3,this.authSafe=new $i,this.macData=new ss,Object.assign(this,e)}}h([m({type:b.Integer})],Vc.prototype,"version",void 0);h([m({type:$i})],Vc.prototype,"authSafe",void 0);h([m({type:ss,optional:!0})],Vc.prototype,"macData",void 0);var Zd;class Kc{constructor(e={}){this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:b.ObjectIdentifier})],Kc.prototype,"bagId",void 0);h([m({type:b.Any,context:0})],Kc.prototype,"bagValue",void 0);h([m({type:Fc,repeated:"set",optional:!0})],Kc.prototype,"bagAttributes",void 0);let Th=Zd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Zd.prototype)}};Th=Zd=h([j({type:C.Sequence,itemType:Kc})],Th);var Yd,Qd,eu;const c1="1.2.840.113549.1.9",l1=`${c1}.7`,Ap=`${c1}.14`;let Ta=class extends qe{constructor(e={}){super(e)}toString(){return this.ia5String||super.toString()}};h([m({type:b.IA5String})],Ta.prototype,"ia5String",void 0);Ta=h([j({type:C.Choice})],Ta);let Rh=class extends $i{};Rh=h([j({type:C.Sequence})],Rh);let Bh=class extends Vc{};Bh=h([j({type:C.Sequence})],Bh);let Lh=class extends Hc{};Lh=h([j({type:C.Sequence})],Lh);let tu=class{constructor(e=""){this.value=e}toString(){return this.value}};h([m({type:b.IA5String})],tu.prototype,"value",void 0);tu=h([j({type:C.Choice})],tu);let Uh=class extends Ta{};Uh=h([j({type:C.Choice})],Uh);let Dh=class extends qe{};Dh=h([j({type:C.Choice})],Dh);let nu=class{constructor(e=new Date){this.value=e}};h([m({type:b.GeneralizedTime})],nu.prototype,"value",void 0);nu=h([j({type:C.Choice})],nu);let Mh=class extends qe{};Mh=h([j({type:C.Choice})],Mh);let ru=class{constructor(e="M"){this.value=e}toString(){return this.value}};h([m({type:b.PrintableString})],ru.prototype,"value",void 0);ru=h([j({type:C.Choice})],ru);let Ra=class{constructor(e=""){this.value=e}toString(){return this.value}};h([m({type:b.PrintableString})],Ra.prototype,"value",void 0);Ra=h([j({type:C.Choice})],Ra);let qh=class extends Ra{};qh=h([j({type:C.Choice})],qh);let Fh=class extends qe{};Fh=h([j({type:C.Choice})],Fh);let iu=class{constructor(e=""){this.value=e}toString(){return this.value}};h([m({type:b.ObjectIdentifier})],iu.prototype,"value",void 0);iu=h([j({type:C.Choice})],iu);let Hh=class extends Ue{};Hh=h([j({type:C.Choice})],Hh);let ou=class{constructor(e=0){this.value=e}toString(){return this.value.toString()}};h([m({type:b.Integer})],ou.prototype,"value",void 0);ou=h([j({type:C.Choice})],ou);let Vh=class extends Yt{};Vh=h([j({type:C.Sequence})],Vh);let Ba=class extends qe{};Ba=h([j({type:C.Choice})],Ba);let Kh=Yd=class extends Tn{constructor(e){super(e),Object.setPrototypeOf(this,Yd.prototype)}};Kh=Yd=h([j({type:C.Sequence})],Kh);let Gh=Qd=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,Qd.prototype)}};Gh=Qd=h([j({type:C.Set,itemType:vi})],Gh);let su=class{constructor(e=""){this.value=e}toString(){return this.value}};h([m({type:b.BmpString})],su.prototype,"value",void 0);su=h([j({type:C.Choice})],su);let au=class extends U{};au=h([j({type:C.Sequence})],au);let Wh=eu=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,eu.prototype)}};Wh=eu=h([j({type:C.Sequence,itemType:au})],Wh);var cu;let La=cu=class extends ue{constructor(e){super(e),Object.setPrototypeOf(this,cu.prototype)}};La=cu=h([j({type:C.Sequence,itemType:pn})],La);class Si{constructor(e={}){this.version=0,this.subject=new Ce,this.subjectPKInfo=new At,this.attributes=new La,Object.assign(this,e)}}h([m({type:b.Integer})],Si.prototype,"version",void 0);h([m({type:Ce})],Si.prototype,"subject",void 0);h([m({type:At})],Si.prototype,"subjectPKInfo",void 0);h([m({type:La,implicit:!0,context:0,optional:!0})],Si.prototype,"attributes",void 0);class Co{constructor(e={}){this.certificationRequestInfo=new Si,this.signatureAlgorithm=new U,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}h([m({type:Si,raw:!0})],Co.prototype,"certificationRequestInfo",void 0);h([m({type:U})],Co.prototype,"signatureAlgorithm",void 0);h([m({type:b.BitString})],Co.prototype,"signature",void 0);const as="crypto.algorithm";class p${getAlgorithms(){return Fe.resolveAll(as)}toAsnAlgorithm(e){({...e});for(const n of this.getAlgorithms()){const r=n.toAsnAlgorithm(e);if(r)return r}if(/^[0-9.]+$/.test(e.name)){const n=new U({algorithm:e.name});if("parameters"in e){const r=e;n.parameters=r.parameters}return n}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(const r of this.getAlgorithms()){const i=r.toWebAlgorithm(e);if(i)return i}return{name:e.algorithm,parameters:e.parameters}}}const yr="crypto.algorithmProvider";Fe.registerSingleton(yr,p$);var Ps;const st="1.3.36.3.3.2.8.1.1",Jh=`${st}.1`,Xh=`${st}.2`,Zh=`${st}.3`,Yh=`${st}.4`,Qh=`${st}.5`,eg=`${st}.6`,tg=`${st}.7`,ng=`${st}.8`,rg=`${st}.9`,ig=`${st}.10`,og=`${st}.11`,sg=`${st}.12`,ag=`${st}.13`,cg=`${st}.14`,lg="brainpoolP160r1",dg="brainpoolP160t1",ug="brainpoolP192r1",pg="brainpoolP192t1",fg="brainpoolP224r1",hg="brainpoolP224t1",gg="brainpoolP256r1",mg="brainpoolP256t1",_g="brainpoolP320r1",yg="brainpoolP320t1",wg="brainpoolP384r1",bg="brainpoolP384t1",vg="brainpoolP512r1",$g="brainpoolP512t1",ve="ECDSA";let No=Ps=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case ve.toLowerCase():if("hash"in e)switch((typeof e.hash=="string"?e.hash:e.hash.name).toLowerCase()){case"sha-1":return R4;case"sha-256":return B4;case"sha-384":return L4;case"sha-512":return U4}else if("namedCurve"in e){let n="";switch(e.namedCurve){case"P-256":n=Ah;break;case"K-256":n=Ps.SECP256K1;break;case"P-384":n=Eh;break;case"P-521":n=Ch;break;case lg:n=Jh;break;case dg:n=Xh;break;case ug:n=Zh;break;case pg:n=Yh;break;case fg:n=Qh;break;case hg:n=eg;break;case gg:n=tg;break;case mg:n=ng;break;case _g:n=rg;break;case yg:n=ig;break;case wg:n=og;break;case bg:n=sg;break;case vg:n=ag;break;case $g:n=cg;break}if(n)return new U({algorithm:Ao,parameters:O.serialize(new Bn({namedCurve:n}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case bp:return{name:ve,hash:{name:"SHA-1"}};case vp:return{name:ve,hash:{name:"SHA-256"}};case $p:return{name:ve,hash:{name:"SHA-384"}};case kp:return{name:ve,hash:{name:"SHA-512"}};case Ao:{if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(O.parse(e.parameters,Bn).namedCurve){case Ah:return{name:ve,namedCurve:"P-256"};case Ps.SECP256K1:return{name:ve,namedCurve:"K-256"};case Eh:return{name:ve,namedCurve:"P-384"};case Ch:return{name:ve,namedCurve:"P-521"};case Jh:return{name:ve,namedCurve:lg};case Xh:return{name:ve,namedCurve:dg};case Zh:return{name:ve,namedCurve:ug};case Yh:return{name:ve,namedCurve:pg};case Qh:return{name:ve,namedCurve:fg};case eg:return{name:ve,namedCurve:hg};case tg:return{name:ve,namedCurve:gg};case ng:return{name:ve,namedCurve:mg};case rg:return{name:ve,namedCurve:_g};case ig:return{name:ve,namedCurve:yg};case og:return{name:ve,namedCurve:wg};case sg:return{name:ve,namedCurve:bg};case ag:return{name:ve,namedCurve:vg};case cg:return{name:ve,namedCurve:$g}}}}return null}};No.SECP256K1="1.3.132.0.10";No=Ps=h([qc()],No);Fe.registerSingleton(as,No);const d1=Symbol("name"),u1=Symbol("value");class de{constructor(e,n={},r=""){this[d1]=e,this[u1]=r;for(const i in n)this[i]=n[i]}}de.NAME=d1;de.VALUE=u1;class f${static toTextObject(e){const n=new de("Algorithm Identifier",{},Mn.toString(e.algorithm));if(e.parameters)if(e.algorithm===Ao){const r=new No().toWebAlgorithm(e);r&&"namedCurve"in r?n["Named Curve"]=r.namedCurve:n.Parameters=e.parameters}else n.Parameters=e.parameters;return n}}class Mn{static toString(e){const n=this.items[e];return n||e}}Mn.items={[Na]:"sha1",[Zy]:"sha224",[Ia]:"sha256",[ja]:"sha384",[Pa]:"sha512",[gr]:"rsaEncryption",[Aa]:"sha1WithRSAEncryption",[V4]:"sha224WithRSAEncryption",[Dd]:"sha256WithRSAEncryption",[Ea]:"sha384WithRSAEncryption",[Ca]:"sha512WithRSAEncryption",[Ao]:"ecPublicKey",[bp]:"ecdsaWithSHA1",[Wy]:"ecdsaWithSHA224",[vp]:"ecdsaWithSHA256",[$p]:"ecdsaWithSHA384",[kp]:"ecdsaWithSHA512",[C4]:"TLS WWW server authentication",[N4]:"TLS WWW client authentication",[I4]:"Code Signing",[j4]:"E-mail Protection",[P4]:"Time Stamping",[O4]:"OCSP Signing",[T4]:"Signed Data"};class wr{static serialize(e){return this.serializeObj(e).join(`
74
+ `)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,n=0){const r=[];let i=this.pad(n++),s="";const a=e[de.VALUE];a&&(s=` ${a}`),r.push(`${i}${e[de.NAME]}:${s}`),i=this.pad(n);for(const c in e){if(typeof c=="symbol")continue;const l=e[c],d=c?`${c}: `:"";if(typeof l=="string"||typeof l=="number"||typeof l=="boolean")r.push(`${i}${d}${l}`);else if(l instanceof Date)r.push(`${i}${d}${l.toUTCString()}`);else if(Array.isArray(l))for(const u of l)u[de.NAME]=c,r.push(...this.serializeObj(u,n));else if(l instanceof de)l[de.NAME]=c,r.push(...this.serializeObj(l,n));else if(T.isBufferSource(l))c?(r.push(`${i}${d}`),r.push(...this.serializeBufferSource(l,n+1))):r.push(...this.serializeBufferSource(l,n));else if("toTextObject"in l){const u=l.toTextObject();u[de.NAME]=c,r.push(...this.serializeObj(u,n))}else throw new TypeError("Cannot serialize data in text format. Unsupported type.")}return r}static serializeBufferSource(e,n=0){const r=this.pad(n),i=T.toUint8Array(e),s=[];for(let a=0;a<i.length;){const c=[];for(let l=0;l<16&&a<i.length;l++){l===8&&c.push("");const d=i[a++].toString(16).padStart(2,"0");c.push(d)}s.push(`${r}${c.join(" ")}`)}return s}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}}wr.oidSerializer=Mn;wr.algorithmSerializer=f$;var jr;class qn{get rawData(){return re(this,jr,"f")||ye(this,jr,O.serialize(this.asn),"f"),re(this,jr,"f")}constructor(...e){jr.set(this,void 0),T.isBufferSource(e[0])?(this.asn=O.parse(e[0],e[1]),ye(this,jr,T.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof qn?P_(e.rawData,this.rawData):!1}toString(e="text"){switch(e){case"asn":return O.toString(this.rawData);case"text":return wr.serialize(this.toTextObject());case"hex":return F.ToHex(this.rawData);case"base64":return F.ToBase64(this.rawData);case"base64url":return F.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){const e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new de(this.getTextName(),{},e)}}jr=new WeakMap;qn.NAME="ASN";class pt extends qn{constructor(...e){let n;T.isBufferSource(e[0])?n=T.toArrayBuffer(e[0]):n=O.serialize(new yt({extnID:e[0],critical:e[1],extnValue:new ae(T.toArrayBuffer(e[2]))})),super(n,yt)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[de.NAME]===pt.NAME&&(e[de.NAME]=Mn.toString(this.type)),e}}var p1;class En{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&e.extractable!==void 0}constructor(){this.items=new Map,this[p1]="CryptoProvider",typeof self<"u"&&typeof crypto<"u"?this.set(En.DEFAULT,crypto):typeof global<"u"&&global.crypto&&global.crypto.subtle&&this.set(En.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,n){return this.items.forEach(e,n)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=En.DEFAULT){const n=this.items.get(e.toLowerCase());if(!n)throw new Error(`Cannot get Crypto by name '${e}'`);return n}set(e,n){if(typeof e=="string"){if(!n)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),n)}else this.items.set(En.DEFAULT,e);return this}}p1=Symbol.toStringTag;En.DEFAULT="default";const Oe=new En,h$=/^[0-2](?:\.[1-9][0-9]*)+$/;function g$(t){return new RegExp(h$).test(t)}class f1{constructor(e={}){this.items={};for(const n in e)this.register(n,e[n])}get(e){return this.items[e]||null}findId(e){return g$(e)?e:this.get(e)}register(e,n){this.items[e]=n,this.items[n]=e}}const rt=new f1;rt.register("CN","2.5.4.3");rt.register("L","2.5.4.7");rt.register("ST","2.5.4.8");rt.register("O","2.5.4.10");rt.register("OU","2.5.4.11");rt.register("C","2.5.4.6");rt.register("DC","0.9.2342.19200300.100.1.25");rt.register("E","1.2.840.113549.1.9.1");rt.register("G","2.5.4.42");rt.register("I","2.5.4.43");rt.register("SN","2.5.4.4");rt.register("T","2.5.4.12");function m$(t,e){return`\\${F.ToHex(F.FromUtf8String(e)).toUpperCase()}`}function _$(t){return t.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,m$)}class Et{static isASCII(e){for(let n=0;n<e.length;n++)if(e.charCodeAt(n)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,n={}){this.extraNames=new f1,this.asn=new Ce;for(const r in n)if(Object.prototype.hasOwnProperty.call(n,r)){const i=n[r];this.extraNames.register(r,i)}typeof e=="string"?this.asn=this.fromString(e):e instanceof Ce?this.asn=e:T.isBufferSource(e)?this.asn=O.parse(e,Ce):this.asn=this.fromJSON(e)}getField(e){const n=this.extraNames.findId(e)||rt.findId(e),r=[];for(const i of this.asn)for(const s of i)s.type===n&&r.push(s.value.toString());return r}getName(e){return this.extraNames.get(e)||rt.get(e)}toString(){return this.asn.map(e=>e.map(n=>{const r=this.getName(n.type)||n.type,i=n.value.anyValue?`#${F.ToHex(n.value.anyValue)}`:_$(n.value.toString());return`${r}=${i}`}).join("+")).join(", ")}toJSON(){var e;const n=[];for(const r of this.asn){const i={};for(const s of r){const a=this.getName(s.type)||s.type;(e=i[a])!==null&&e!==void 0||(i[a]=[]),i[a].push(s.value.anyValue?`#${F.ToHex(s.value.anyValue)}`:s.value.toString())}n.push(i)}return n}fromString(e){const n=new Ce,r=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;let i=null,s=",";for(;i=r.exec(`${e},`);){let[,a,c]=i;const l=c[c.length-1];(l===","||l==="+")&&(c=c.slice(0,c.length-1),i[3]=l);const d=i[3];a=this.getTypeOid(a);const u=this.createAttribute(a,c);s==="+"?n[n.length-1].push(u):n.push(new ei([u])),s=d}return n}fromJSON(e){const n=new Ce;for(const r of e){const i=new ei;for(const s in r){const a=this.getTypeOid(s),c=r[s];for(const l of c){const d=this.createAttribute(a,l);i.push(d)}}n.push(i)}return n}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,n){const r=new $c({type:e});if(typeof n=="object")for(const i in n)switch(i){case"ia5String":r.value.ia5String=n[i];break;case"utf8String":r.value.utf8String=n[i];break;case"universalString":r.value.universalString=n[i];break;case"bmpString":r.value.bmpString=n[i];break;case"printableString":r.value.printableString=n[i];break}else if(n[0]==="#")r.value.anyValue=F.FromHex(n.slice(1));else{const i=this.processStringValue(n);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=i:Et.isPrintableString(i)?r.value.printableString=i:r.value.utf8String=i}return r}processStringValue(e){const n=/"(.*?[^\\])?"/.exec(e);return n&&(e=n[1]),e.replace(/\\0a/ig,`
75
+ `).replace(/\\0d/ig,"\r").replace(/\\0g/ig," ").replace(/\\(.)/g,"$1")}toArrayBuffer(){return O.serialize(this.asn)}async getThumbprint(...e){var n;let r,i="SHA-1";return e.length>=1&&!(!((n=e[0])===null||n===void 0)&&n.subtle)?(i=e[0]||i,r=e[1]||Oe.get()):r=e[0]||Oe.get(),await r.subtle.digest(i,this.toArrayBuffer())}}const h1="Cannot initialize GeneralName from ASN.1 data.",kg=`${h1} Unsupported string format in use.`,y$=`${h1} Value doesn't match to GUID regular expression.`,xg=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Sg="1.3.6.1.4.1.311.25.1",zg="1.3.6.1.4.1.311.20.2.3",gl="dns",ml="dn",_l="email",yl="ip",wl="url",bl="guid",vl="upn",ws="id";class Cn extends qn{constructor(...e){let n;if(e.length===2)switch(e[0]){case ml:{const r=new Et(e[1]).toArrayBuffer(),i=O.parse(r,Ce);n=new ee({directoryName:i});break}case gl:n=new ee({dNSName:e[1]});break;case _l:n=new ee({rfc822Name:e[1]});break;case bl:{const r=new RegExp(xg,"i").exec(e[1]);if(!r)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");const i=r.slice(1).map((s,a)=>a<3?F.ToHex(new Uint8Array(F.FromHex(s)).reverse()):s).join("");n=new ee({otherName:new ko({typeId:Sg,value:O.serialize(new ae(F.FromHex(i)))})});break}case yl:n=new ee({iPAddress:e[1]});break;case ws:n=new ee({registeredID:e[1]});break;case vl:{n=new ee({otherName:new ko({typeId:zg,value:O.serialize(Ny.toASN(e[1]))})});break}case wl:n=new ee({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else T.isBufferSource(e[0])?n=O.parse(e[0],ee):n=e[0];super(n)}onInit(e){if(e.dNSName!=null)this.type=gl,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=_l,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=yl,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=wl,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=ws,this.value=e.registeredID;else if(e.directoryName!=null)this.type=ml,this.value=new Et(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===Sg){this.type=bl;const n=O.parse(e.otherName.value,ae),r=new RegExp(xg,"i").exec(F.ToHex(n));if(!r)throw new Error(y$);this.value=r.slice(1).map((i,s)=>s<3?F.ToHex(new Uint8Array(F.FromHex(i)).reverse()):i).join("-")}else if(e.otherName.typeId===zg)this.type=vl,this.value=O.parse(e.otherName.value,qe).toString();else throw new Error(kg);else throw new Error(kg)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case ml:case gl:case bl:case yl:case ws:case vl:case wl:e=this.type.toUpperCase();break;case _l:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let n=this.value;return this.type===ws&&(n=Mn.toString(n)),new de(e,void 0,n)}}class br extends qn{constructor(e){let n;if(e instanceof We)n=e;else if(Array.isArray(e)){const r=[];for(const i of e)if(i instanceof ee)r.push(i);else{const s=O.parse(new Cn(i.type,i.value).rawData,ee);r.push(s)}n=new We(r)}else if(T.isBufferSource(e))n=O.parse(e,We);else throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");super(n)}onInit(e){const n=[];for(const r of e){let i=null;try{i=new Cn(r)}catch{continue}n.push(i)}this.items=n}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){const e=super.toTextObjectEmpty();for(const n of this.items){const r=n.toTextObject();let i=e[r[de.NAME]];Array.isArray(i)||(i=[],e[r[de.NAME]]=i),i.push(r)}return e}}br.NAME="GeneralNames";const fo="-{5}",Io="\\n",w$=`[^${Io}]+`,b$=`${fo}BEGIN (${w$}(?=${fo}))${fo}`,v$=`${fo}END \\1${fo}`,ci="\\n",$$=`[^:${Io}]+`,k$=`(?:[^${Io}]+${ci}(?: +[^${Io}]+${ci})*)`,x$="[a-zA-Z0-9=+/]+",S$=`(?:${x$}${ci})+`,Ag=`${b$}${ci}(?:((?:${$$}: ${k$})+))?${ci}?(${S$})${v$}`;class ct{static isPem(e){return typeof e=="string"&&new RegExp(Ag,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const n=new RegExp(Ag,"g"),r=[];let i=null;for(;i=n.exec(e);){const s=i[3].replace(new RegExp(`[${Io}]+`,"g"),""),a={type:i[1],headers:[],rawData:F.FromBase64(s)},c=i[2];if(c){const l=c.split(new RegExp(ci,"g"));let d=null;for(const u of l){const[f,g]=u.split(/:(.*)/);if(g===void 0){if(!d)throw new Error("Cannot parse PEM string. Incorrect header value");d.value+=f.trim()}else d&&a.headers.push(d),d={key:f,value:g.trim()}}d&&a.headers.push(d)}r.push(a)}return r}static decode(e){return this.decodeWithHeaders(e).map(r=>r.rawData)}static decodeFirst(e){const n=this.decode(e);if(!n.length)throw new RangeError("PEM string doesn't contain any objects");return n[0]}static encode(e,n){if(Array.isArray(e)){const r=new Array;return n?e.forEach(i=>{if(!T.isBufferSource(i))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");r.push(this.encodeStruct({type:n,rawData:T.toArrayBuffer(i)}))}):e.forEach(i=>{if(!("type"in i))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");r.push(this.encodeStruct(i))}),r.join(`
76
76
  `)}else{if(!n)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:n,rawData:T.toArrayBuffer(e)})}}static encodeStruct(e){var n;const r=e.type.toLocaleUpperCase(),i=[];if(i.push(`-----BEGIN ${r}-----`),!((n=e.headers)===null||n===void 0)&&n.length){for(const d of e.headers)i.push(`${d.key}: ${d.value}`);i.push("")}const s=F.ToBase64(e.rawData);let a,c=0;const l=Array();for(;c<s.length&&(s.length-c<64?a=s.substring(c):(a=s.substring(c,c+64),c+=64),a.length!==0);)if(l.push(a),a.length<64)break;return i.push(...l),i.push(`-----END ${r}-----`),i.join(`
77
- `)}}ct.CertificateTag="CERTIFICATE";ct.CrlTag="CRL";ct.CertificateRequestTag="CERTIFICATE REQUEST";ct.PublicKeyTag="PUBLIC KEY";ct.PrivateKeyTag="PRIVATE KEY";class gn extends qn{static isAsnEncoded(e){return T.isBufferSource(e)||typeof e=="string"}static toArrayBuffer(e){if(typeof e=="string"){if(ct.isPem(e))return ct.decode(e)[0];if(F.isHex(e))return F.FromHex(e);if(F.isBase64(e))return F.FromBase64(e);if(F.isBase64Url(e))return F.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}else{const n=T.toUint8Array(e);if(n.length>0&&n[0]===48)return T.toArrayBuffer(e);const r=F.ToBinary(e);if(ct.isPem(r))return ct.decode(r)[0];if(F.isHex(r))return F.FromHex(r);if(F.isBase64(r))return F.FromBase64(r);if(F.isBase64Url(r))return F.FromBase64Url(r);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){gn.isAsnEncoded(e[0])?super(gn.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return e==="pem"?ct.encode(this.rawData,this.tag):super.toString(e)}}class jt extends gn{static async create(e,n=Oe.get()){if(e instanceof jt)return e;if(En.isCryptoKey(e)){if(e.type!=="public")throw new TypeError("Public key is required");const r=await n.subtle.exportKey("spki",e);return new jt(r)}else{if(e.publicKey)return e.publicKey;if(T.isBufferSource(e))return new jt(e);throw new TypeError("Unsupported PublicKeyType")}}constructor(e){gn.isAsnEncoded(e)?super(e,At):super(e),this.tag=ct.PublicKeyTag}async export(...e){let n,r=["verify"],i={hash:"SHA-256",...this.algorithm};e.length>1?(i=e[0]||i,r=e[1]||r,n=e[2]||Oe.get()):n=e[0]||Oe.get();let s=this.rawData;const a=O.parse(this.rawData,At);return a.algorithm.algorithm===uo&&(s=z$(a,s)),n.subtle.importKey("spki",s,i,!0,r)}onInit(e){const n=Fe.resolve(yr),r=this.algorithm=n.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===gr){const i=O.parse(e.subjectPublicKey,xp),s=T.toUint8Array(i.modulus);r.publicExponent=T.toUint8Array(i.publicExponent),r.modulusLength=(s[0]?s:s.slice(1)).byteLength<<3}}async getThumbprint(...e){var n;let r,i="SHA-1";return e.length>=1&&!(!((n=e[0])===null||n===void 0)&&n.subtle)?(i=e[0]||i,r=e[1]||Oe.get()):r=e[0]||Oe.get(),await r.subtle.digest(i,this.rawData)}async getKeyIdentifier(...e){let n,r="SHA-1";e.length===1?typeof e[0]=="string"?(r=e[0],n=Oe.get()):n=e[0]:e.length===2?(r=e[0],n=e[1]):n=Oe.get();const i=O.parse(this.rawData,At);return await n.subtle.digest(r,i.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),n=O.parse(this.rawData,At);switch(e.Algorithm=wr.serializeAlgorithm(n.algorithm),n.algorithm.algorithm){case Ao:e["EC Point"]=n.subjectPublicKey;break;case gr:default:e["Raw Data"]=n.subjectPublicKey}return e}}function z$(t,e){return t.algorithm=new U({algorithm:gr,parameters:null}),e=O.serialize(t),e}class jo extends pt{static async create(e,n=!1,r=Oe.get()){if("name"in e&&"serialNumber"in e)return new jo(e,n);const s=await(await jt.create(e,r)).getKeyIdentifier(r);return new jo(F.ToHex(s),n)}constructor(...e){if(T.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]=="string"){const n=new Qn({keyIdentifier:new op(F.FromHex(e[0]))});super(id,e[1],O.serialize(n))}else{const n=e[0],r=n.name instanceof br?O.parse(n.name.rawData,We):n.name,i=new Qn({authorityCertIssuer:r,authorityCertSerialNumber:F.FromHex(n.serialNumber)});super(id,e[1],O.serialize(i))}}onInit(e){super.onInit(e);const n=O.parse(e.extnValue,Qn);n.keyIdentifier&&(this.keyId=F.ToHex(n.keyIdentifier)),(n.authorityCertIssuer||n.authorityCertSerialNumber)&&(this.certId={name:n.authorityCertIssuer||[],serialNumber:n.authorityCertSerialNumber?F.ToHex(n.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),n=O.parse(this.value,Qn);return n.authorityCertIssuer&&(e["Authority Issuer"]=new br(n.authorityCertIssuer).toTextObject()),n.authorityCertSerialNumber&&(e["Authority Serial Number"]=n.authorityCertSerialNumber),n.keyIdentifier&&(e[""]=n.keyIdentifier),e}}jo.NAME="Authority Key Identifier";class Ep extends pt{constructor(...e){if(T.isBufferSource(e[0])){super(e[0]);const n=O.parse(this.value,la);this.ca=n.cA,this.pathLength=n.pathLenConstraint}else{const n=new la({cA:e[0],pathLenConstraint:e[1]});super(jy,e[2],O.serialize(n)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e["Path Length"]=this.pathLength),e}}Ep.NAME="Basic Constraints";var Eg;(function(t){t.serverAuth="1.3.6.1.5.5.7.3.1",t.clientAuth="1.3.6.1.5.5.7.3.2",t.codeSigning="1.3.6.1.5.5.7.3.3",t.emailProtection="1.3.6.1.5.5.7.3.4",t.timeStamping="1.3.6.1.5.5.7.3.8",t.ocspSigning="1.3.6.1.5.5.7.3.9"})(Eg||(Eg={}));class Cp extends pt{constructor(...e){if(T.isBufferSource(e[0])){super(e[0]);const n=O.parse(this.value,fa);this.usages=n.map(r=>r)}else{const n=new fa(e[0]);super(Ty,e[1],O.serialize(n)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(n=>Mn.toString(n)).join(", "),e}}Cp.NAME="Extended Key Usages";var Ua;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(Ua||(Ua={}));class Np extends pt{constructor(...e){if(T.isBufferSource(e[0])){super(e[0]);const n=O.parse(this.value,hl);this.usages=n.toNumber()}else{const n=new hl(e[0]);super(By,e[1],O.serialize(n)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),n=O.parse(this.value,hl);return e[""]=n.toJSON().join(", "),e}}Np.NAME="Key Usages";class cs extends pt{static async create(e,n=!1,r=Oe.get()){const s=await(await jt.create(e,r)).getKeyIdentifier(r);return new cs(F.ToHex(s),n)}constructor(...e){if(T.isBufferSource(e[0])){super(e[0]);const n=O.parse(this.value,jn);this.keyId=F.ToHex(n)}else{const n=typeof e[0]=="string"?F.FromHex(e[0]):e[0],r=new jn(n);super(My,e[1],O.serialize(r)),this.keyId=F.ToHex(n)}}toTextObject(){const e=this.toTextObjectWithoutValue(),n=O.parse(this.value,jn);return e[""]=n,e}}cs.NAME="Subject Key Identifier";class g1 extends pt{constructor(...e){T.isBufferSource(e[0])?super(e[0]):super(Dy,e[1],new br(e[0]||[]).rawData)}onInit(e){super.onInit(e);const n=O.parse(e.extnValue,wd);this.names=new br(n)}toTextObject(){const e=this.toTextObjectWithoutValue(),n=this.names.toTextObject();for(const r in n)e[r]=n[r];return e}}g1.NAME="Subject Alternative Name";class ft{static register(e,n){this.items.set(e,n)}static create(e){const n=new pt(e),r=this.items.get(n.type);return r?new r(e):n}}ft.items=new Map;class m1 extends pt{constructor(...e){var n;if(T.isBufferSource(e[0])){super(e[0]);const r=O.parse(this.value,ua);this.policies=r.map(i=>i.policyIdentifier)}else{const r=e[0],i=(n=e[1])!==null&&n!==void 0?n:!1,s=new ua(r.map(a=>new xc({policyIdentifier:a})));super(Py,i,O.serialize(s)),this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(n=>new de("",{},Mn.toString(n))),e}}m1.NAME="Certificate Policies";ft.register(Py,m1);class _1 extends pt{constructor(...e){var n;if(T.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]=="string"){const i=e[0].map(a=>new yi({distributionPoint:new ur({fullName:[new ee({uniformResourceIdentifier:a})]})})),s=new Vr(i);super(ld,e[1],O.serialize(s))}else{const r=new Vr(e[0]);super(ld,e[1],O.serialize(r))}(n=this.distributionPoints)!==null&&n!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);const n=O.parse(e.extnValue,Vr);this.distributionPoints=n}toTextObject(){const e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(n=>{var r;const i={};return n.distributionPoint&&(i[""]=(r=n.distributionPoint.fullName)===null||r===void 0?void 0:r.map(s=>new Cn(s).toString()).join(", ")),n.reasons&&(i.Reasons=n.reasons.toString()),n.cRLIssuer&&(i["CRL Issuer"]=n.cRLIssuer.map(s=>s.toString()).join(", ")),i}),e}}_1.NAME="CRL Distribution Points";class y1 extends pt{constructor(...e){var n,r,i,s;if(T.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof Ur){const a=new Ur(e[0]);super(rd,e[1],O.serialize(a))}else{const a=e[0],c=new Ur;vs(c,a,ph,"ocsp"),vs(c,a,fh,"caIssuers"),vs(c,a,hh,"timeStamping"),vs(c,a,gh,"caRepository"),super(rd,e[1],O.serialize(c))}(n=this.ocsp)!==null&&n!==void 0||(this.ocsp=[]),(r=this.caIssuers)!==null&&r!==void 0||(this.caIssuers=[]),(i=this.timeStamping)!==null&&i!==void 0||(this.timeStamping=[]),(s=this.caRepository)!==null&&s!==void 0||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],O.parse(e.extnValue,Ur).forEach(r=>{switch(r.accessMethod){case ph:this.ocsp.push(new Cn(r.accessLocation));break;case fh:this.caIssuers.push(new Cn(r.accessLocation));break;case hh:this.timeStamping.push(new Cn(r.accessLocation));break;case gh:this.caRepository.push(new Cn(r.accessLocation));break}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&bs(e,"OCSP",this.ocsp),this.caIssuers.length&&bs(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&bs(e,"Time Stamping",this.timeStamping),this.caRepository.length&&bs(e,"CA Repository",this.caRepository),e}}y1.NAME="Authority Info Access";function bs(t,e,n){if(n.length===1)t[e]=n[0].toTextObject();else{const r=new de("");n.forEach((i,s)=>{const a=i.toTextObject(),c=`${a[de.NAME]} ${s+1}`;let l=r[c];Array.isArray(l)||(l=[],r[c]=l),l.push(a)}),t[e]=r}}function vs(t,e,n,r){const i=e[r];i&&(Array.isArray(i)?i:[i]).forEach(a=>{typeof a=="string"&&(a=new Cn("url",a)),t.push(new Jo({accessMethod:n,accessLocation:O.parse(a.rawData,ee)}))})}class w1 extends pt{constructor(...e){T.isBufferSource(e[0])?super(e[0]):super(Ry,e[1],new br(e[0]||[]).rawData)}onInit(e){super.onInit(e);const n=O.parse(e.extnValue,We);this.names=new br(n)}toTextObject(){const e=this.toTextObjectWithoutValue(),n=this.names.toTextObject();for(const r in n)e[r]=n[r];return e}}w1.NAME="Issuer Alternative Name";class Si extends qn{constructor(...e){let n;if(T.isBufferSource(e[0]))n=T.toArrayBuffer(e[0]);else{const r=e[0],i=Array.isArray(e[1])?e[1].map(s=>T.toArrayBuffer(s)):[];n=O.serialize(new pn({type:r,values:i}))}super(n,pn)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(n=>new de("",{"":n})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[de.NAME]===Si.NAME&&(e[de.NAME]=Mn.toString(this.type)),e}}Si.NAME="Attribute";class b1 extends Si{constructor(...e){var n;if(T.isBufferSource(e[0]))super(e[0]);else{const r=new Ba({printableString:e[0]});super(l1,[O.serialize(r)])}(n=this.password)!==null&&n!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const n=O.parse(this.values[0],Ba);this.password=n.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[de.VALUE]=this.password,e}}b1.NAME="Challenge Password";class Ip extends Si{constructor(...e){var n;if(T.isBufferSource(e[0]))super(e[0]);else{const r=e[0],i=new Tn;for(const s of r)i.push(O.parse(s.rawData,yt));super(Ap,[O.serialize(i)])}(n=this.items)!==null&&n!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const n=O.parse(this.values[0],Tn);this.items=n.map(r=>ft.create(O.serialize(r)))}}toTextObject(){const e=this.toTextObjectWithoutValue(),n=this.items.map(r=>r.toTextObject());for(const r of n)e[r[de.NAME]]=r;return e}}Ip.NAME="Extensions";class Gc{static register(e,n){this.items.set(e,n)}static create(e){const n=new Si(e),r=this.items.get(n.type);return r?new r(e):n}}Gc.items=new Map;const ls="crypto.signatureFormatter";class A${toAsnSignature(e,n){return T.toArrayBuffer(n)}toWebSignature(e,n){return T.toArrayBuffer(n)}}var Os;let lu=Os=class{static createPssParams(e,n){const r=Os.getHashAlgorithm(e);return r?new _r({hashAlgorithm:r,maskGenAlgorithm:new U({algorithm:Lc,parameters:O.serialize(r)}),saltLength:n}):null}static getHashAlgorithm(e){const n=Fe.resolve(yr);return typeof e=="string"?n.toAsnAlgorithm({name:e}):typeof e=="object"&&e&&"name"in e?n.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if("hash"in e){let n;if(typeof e.hash=="string")n=e.hash;else if(e.hash&&typeof e.hash=="object"&&"name"in e.hash&&typeof e.hash.name=="string")n=e.hash.name.toUpperCase();else throw new Error("Cannot get hash algorithm name");switch(n.toLowerCase()){case"sha-1":return new U({algorithm:Aa,parameters:null});case"sha-256":return new U({algorithm:Dd,parameters:null});case"sha-384":return new U({algorithm:Ea,parameters:null});case"sha-512":return new U({algorithm:Ca,parameters:null})}}else return new U({algorithm:gr,parameters:null});break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e&&typeof e.saltLength=="number"))throw new Error("Cannot get 'saltLength' from 'alg' argument");const n=Os.createPssParams(e.hash,e.saltLength);if(!n)throw new Error("Cannot create PSS parameters");return new U({algorithm:uo,parameters:O.serialize(n)})}else return new U({algorithm:uo,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case gr:return{name:"RSASSA-PKCS1-v1_5"};case Aa:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case Dd:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case Ea:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case Ca:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case uo:if(e.parameters){const n=O.parse(e.parameters,_r);return{name:"RSA-PSS",hash:Fe.resolve(yr).toWebAlgorithm(n.hashAlgorithm),saltLength:n.saltLength}}else return{name:"RSA-PSS"}}return null}};lu=Os=h([qc()],lu);Fe.registerSingleton(as,lu);let du=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new U({algorithm:Na});case"sha-256":return new U({algorithm:Ia});case"sha-384":return new U({algorithm:ja});case"sha-512":return new U({algorithm:Pa})}return null}toWebAlgorithm(e){switch(e.algorithm){case Na:return{name:"SHA-1"};case Ia:return{name:"SHA-256"};case ja:return{name:"SHA-384"};case Pa:return{name:"SHA-512"}}return null}};du=h([qc()],du);Fe.registerSingleton(as,du);class gt{addPadding(e,n){const r=T.toUint8Array(n),i=new Uint8Array(e);return i.set(r,e-r.length),i.buffer}removePadding(e,n=!1){let r=T.toUint8Array(e);for(let i=0;i<r.length;i++)if(r[i]){r=r.slice(i);break}if(n&&r[0]>127){const i=new Uint8Array(r.length+1);return i.set(r,1),i.buffer}return r.buffer}toAsnSignature(e,n){if(e.name==="ECDSA"){const r=e.namedCurve,i=gt.namedCurveSize.get(r)||gt.defaultNamedCurveSize,s=new za,a=T.toUint8Array(n);return s.r=this.removePadding(a.slice(0,i),!0),s.s=this.removePadding(a.slice(i,i+i),!0),O.serialize(s)}return null}toWebSignature(e,n){if(e.name==="ECDSA"){const r=O.parse(n,za),i=e.namedCurve,s=gt.namedCurveSize.get(i)||gt.defaultNamedCurveSize,a=this.addPadding(s,this.removePadding(r.r)),c=this.addPadding(s,this.removePadding(r.s));return D3(a,c)}return null}}gt.namedCurveSize=new Map;gt.defaultNamedCurveSize=32;const $l="1.3.101.110",Cg="1.3.101.111",kl="1.3.101.112",Ng="1.3.101.113";let uu=class{toAsnAlgorithm(e){let n=null;switch(e.name.toLowerCase()){case"ed25519":n=kl;break;case"x25519":n=$l;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":n=kl;break;case"ed448":n=Ng;break}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":n=$l;break;case"x448":n=Cg;break}}return n?new U({algorithm:n}):null}toWebAlgorithm(e){switch(e.algorithm){case kl:return{name:"Ed25519"};case Ng:return{name:"EdDSA",namedCurve:"Ed448"};case $l:return{name:"X25519"};case Cg:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};uu=h([qc()],uu);Fe.registerSingleton(as,uu);var Ri,Bi,Li,Ui,Di,Mi,qi,Pr;class E$ extends gn{get subjectName(){return re(this,Bi,"f")||ye(this,Bi,new Et(this.asn.certificationRequestInfo.subject),"f"),re(this,Bi,"f")}get subject(){return re(this,Li,"f")||ye(this,Li,this.subjectName.toString(),"f"),re(this,Li,"f")}get signatureAlgorithm(){if(!re(this,Ui,"f")){const e=Fe.resolve(yr);ye(this,Ui,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return re(this,Ui,"f")}get signature(){return re(this,Di,"f")||ye(this,Di,this.asn.signature,"f"),re(this,Di,"f")}get publicKey(){return re(this,Mi,"f")||ye(this,Mi,new jt(this.asn.certificationRequestInfo.subjectPKInfo),"f"),re(this,Mi,"f")}get attributes(){return re(this,qi,"f")||ye(this,qi,this.asn.certificationRequestInfo.attributes.map(e=>Gc.create(O.serialize(e))),"f"),re(this,qi,"f")}get extensions(){if(!re(this,Pr,"f")){ye(this,Pr,[],"f");const e=this.getAttribute(Ap);e instanceof Ip&&ye(this,Pr,e.items,"f")}return re(this,Pr,"f")}get tbs(){return re(this,Ri,"f")||ye(this,Ri,this.asn.certificationRequestInfoRaw||O.serialize(this.asn.certificationRequestInfo),"f"),re(this,Ri,"f")}constructor(e){const n=gn.isAsnEncoded(e)?[e,Co]:[e];super(n[0],n[1]),Ri.set(this,void 0),Bi.set(this,void 0),Li.set(this,void 0),Ui.set(this,void 0),Di.set(this,void 0),Mi.set(this,void 0),qi.set(this,void 0),Pr.set(this,void 0),this.tag=ct.CertificateRequestTag}onInit(e){}getAttribute(e){for(const n of this.attributes)if(n.type===e)return n;return null}getAttributes(e){return this.attributes.filter(n=>n.type===e)}getExtension(e){for(const n of this.extensions)if(n.type===e)return n;return null}getExtensions(e){return this.extensions.filter(n=>n.type===e)}async verify(e=Oe.get()){const n={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(n,["verify"],e),i=Fe.resolveAll(ls).reverse();let s=null;for(const c of i)if(s=c.toWebSignature(n,this.signature),s)break;if(!s)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,r,s,this.tbs)}toTextObject(){const e=this.toTextObjectEmpty(),n=O.parse(this.rawData,Co),r=n.certificationRequestInfo,i=new de("",{Version:`${pr[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const s=new de("");for(const a of this.attributes){const c=a.toTextObject();s[c[de.NAME]]=c}i.Attributes=s}return e.Data=i,e.Signature=new de("",{Algorithm:wr.serializeAlgorithm(n.signatureAlgorithm),"":n.signature}),e}}Ri=new WeakMap,Bi=new WeakMap,Li=new WeakMap,Ui=new WeakMap,Di=new WeakMap,Mi=new WeakMap,qi=new WeakMap,Pr=new WeakMap;E$.NAME="PKCS#10 Certificate Request";var Fi,Hi,Vi,Ki,Gi,Wi,Ji,Xi,Zi,Yi,Or,Qi;class Wc extends gn{get publicKey(){return re(this,Qi,"f")||ye(this,Qi,new jt(this.asn.tbsCertificate.subjectPublicKeyInfo),"f"),re(this,Qi,"f")}get serialNumber(){if(!re(this,Hi,"f")){const e=this.asn.tbsCertificate;let n=new Uint8Array(e.serialNumber);n.length>1&&n[0]===0&&n[1]>127&&(n=n.slice(1)),ye(this,Hi,F.ToHex(n),"f")}return re(this,Hi,"f")}get subjectName(){return re(this,Vi,"f")||ye(this,Vi,new Et(this.asn.tbsCertificate.subject),"f"),re(this,Vi,"f")}get subject(){return re(this,Ki,"f")||ye(this,Ki,this.subjectName.toString(),"f"),re(this,Ki,"f")}get issuerName(){return re(this,Gi,"f")||ye(this,Gi,new Et(this.asn.tbsCertificate.issuer),"f"),re(this,Gi,"f")}get issuer(){return re(this,Wi,"f")||ye(this,Wi,this.issuerName.toString(),"f"),re(this,Wi,"f")}get notBefore(){if(!re(this,Ji,"f")){const e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");ye(this,Ji,e,"f")}return re(this,Ji,"f")}get notAfter(){if(!re(this,Xi,"f")){const e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");ye(this,Xi,e,"f")}return re(this,Xi,"f")}get signatureAlgorithm(){if(!re(this,Zi,"f")){const e=Fe.resolve(yr);ye(this,Zi,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return re(this,Zi,"f")}get signature(){return re(this,Yi,"f")||ye(this,Yi,this.asn.signatureValue,"f"),re(this,Yi,"f")}get extensions(){return re(this,Or,"f")||(ye(this,Or,[],"f"),this.asn.tbsCertificate.extensions&&ye(this,Or,this.asn.tbsCertificate.extensions.map(e=>ft.create(O.serialize(e))),"f")),re(this,Or,"f")}get tbs(){return re(this,Fi,"f")||ye(this,Fi,this.asn.tbsCertificateRaw||O.serialize(this.asn.tbsCertificate),"f"),re(this,Fi,"f")}constructor(e){const n=gn.isAsnEncoded(e)?[e,fr]:[e];super(n[0],n[1]),Fi.set(this,void 0),Hi.set(this,void 0),Vi.set(this,void 0),Ki.set(this,void 0),Gi.set(this,void 0),Wi.set(this,void 0),Ji.set(this,void 0),Xi.set(this,void 0),Zi.set(this,void 0),Yi.set(this,void 0),Or.set(this,void 0),Qi.set(this,void 0),this.tag=ct.CertificateTag}onInit(e){}getExtension(e){for(const n of this.extensions)if(typeof e=="string"){if(n.type===e)return n}else if(n instanceof e)return n;return null}getExtensions(e){return this.extensions.filter(n=>typeof e=="string"?n.type===e:n instanceof e)}async verify(e={},n=Oe.get()){let r,i;const s=e.publicKey;try{if(!s)r={...this.publicKey.algorithm,...this.signatureAlgorithm},i=await this.publicKey.export(r,["verify"],n);else if("publicKey"in s)r={...s.publicKey.algorithm,...this.signatureAlgorithm},i=await s.publicKey.export(r,["verify"],n);else if(s instanceof jt)r={...s.algorithm,...this.signatureAlgorithm},i=await s.export(r,["verify"],n);else if(T.isBufferSource(s)){const d=new jt(s);r={...d.algorithm,...this.signatureAlgorithm},i=await d.export(r,["verify"],n)}else r={...s.algorithm,...this.signatureAlgorithm},i=s}catch{return!1}const a=Fe.resolveAll(ls).reverse();let c=null;for(const d of a)if(c=d.toWebSignature(r,this.signature),c)break;if(!c)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const l=await n.subtle.verify(this.signatureAlgorithm,i,c,this.tbs);if(e.signatureOnly)return l;{const u=(e.date||new Date).getTime();return l&&this.notBefore.getTime()<u&&u<this.notAfter.getTime()}}async getThumbprint(...e){let n,r="SHA-1";return e[0]&&(e[0].subtle?n=e[0]:(r=e[0]||r,n=e[1])),n??(n=Oe.get()),await n.subtle.digest(r,this.rawData)}async isSelfSigned(e=Oe.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),n=O.parse(this.rawData,fr),r=n.tbsCertificate,i=new de("",{Version:`${pr[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":wr.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new de("",{"Not Before":r.validity.notBefore.getTime(),"Not After":r.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(r.issuerUniqueID&&(i["Issuer Unique ID"]=r.issuerUniqueID),r.subjectUniqueID&&(i["Subject Unique ID"]=r.subjectUniqueID),this.extensions.length){const s=new de("");for(const a of this.extensions){const c=a.toTextObject();s[c[de.NAME]]=c}i.Extensions=s}return e.Data=i,e.Signature=new de("",{Algorithm:wr.serializeAlgorithm(n.signatureAlgorithm),"":n.signatureValue}),e}}Fi=new WeakMap,Hi=new WeakMap,Vi=new WeakMap,Ki=new WeakMap,Gi=new WeakMap,Wi=new WeakMap,Ji=new WeakMap,Xi=new WeakMap,Zi=new WeakMap,Yi=new WeakMap,Or=new WeakMap,Qi=new WeakMap;Wc.NAME="Certificate";function C$(t,e=Oe.get()){const n=T.toUint8Array(F.FromHex(t||""));let r=n&&n.length&&n.some(s=>s>0)?new Uint8Array(n):void 0;r||(r=e.getRandomValues(new Uint8Array(16)));let i=0;for(;i<r.length-1&&r[i]===0;)i++;if(r=r.slice(i),r[0]>127){const s=new Uint8Array(r.length+1);s[0]=0,s.set(r,1),r=s}return r.buffer}class N${static async createSelfSigned(e,n=Oe.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},n)}static async create(e,n=Oe.get()){var r;let i;e.publicKey instanceof jt?i=e.publicKey.rawData:"publicKey"in e.publicKey?i=e.publicKey.publicKey.rawData:T.isBufferSource(e.publicKey)?i=e.publicKey:i=await n.subtle.exportKey("spki",e.publicKey);const s=C$(e.serialNumber,n),a=e.notBefore||new Date,c=e.notAfter||new Date(a.getTime()+31536e6),l=new fr({tbsCertificate:new ut({version:pr.v3,serialNumber:s,validity:new Xo({notBefore:a,notAfter:c}),extensions:new Tn(((r=e.extensions)===null||r===void 0?void 0:r.map(z=>O.parse(z.rawData,yt)))||[]),subjectPublicKeyInfo:O.parse(i,At)})});if(e.subject){const z=e.subject instanceof Et?e.subject:new Et(e.subject);l.tbsCertificate.subject=O.parse(z.toArrayBuffer(),Ce)}if(e.issuer){const z=e.issuer instanceof Et?e.issuer:new Et(e.issuer);l.tbsCertificate.issuer=O.parse(z.toArrayBuffer(),Ce)}const d={hash:"SHA-256"},u="signingKey"in e?{...d,...e.signingAlgorithm,...e.signingKey.algorithm}:{...d,...e.signingAlgorithm},f=Fe.resolve(yr);l.tbsCertificate.signature=l.signatureAlgorithm=f.toAsnAlgorithm(u);const g=O.serialize(l.tbsCertificate),_="signingKey"in e?await n.subtle.sign(u,e.signingKey,g):e.signature,w=Fe.resolveAll(ls).reverse();let k=null;for(const z of w)if(k=z.toAsnSignature(u,_),k)break;if(!k)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return l.signatureValue=k,new Wc(O.serialize(l))}}var Ig;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(Ig||(Ig={}));ft.register(jy,Ep);ft.register(Ty,Cp);ft.register(By,Np);ft.register(My,cs);ft.register(id,jo);ft.register(Dy,g1);ft.register(ld,_1);ft.register(rd,y1);ft.register(Ry,w1);Gc.register(l1,b1);Gc.register(Ap,Ip);Fe.registerSingleton(ls,A$);Fe.registerSingleton(ls,gt);gt.namedCurveSize.set("P-256",32);gt.namedCurveSize.set("K-256",32);gt.namedCurveSize.set("P-384",48);gt.namedCurveSize.set("P-521",66);async function Da(t){const e={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",publicExponent:new Uint8Array([1,0,1]),modulusLength:2048},n=await crypto.subtle.generateKey(e,!0,["sign","verify"]),r=pe(),i=Fl(new TextEncoder().encode(r)),s=await N$.createSelfSigned({serialNumber:i,name:t.name,notBefore:new Date,notAfter:new Date(Date.now()+365*24*60*60*1e3),signingAlgorithm:e,keys:n,extensions:[new Ep(!0,2,!0),new Cp(["1.3.6.1.5.5.7.3.1"],!0),new Np(Ua.keyCertSign|Ua.cRLSign,!0),await cs.create(n.publicKey)]}),a=await crypto.subtle.exportKey("pkcs8",n.privateKey),c=s.toString("pem"),l=await j$(s),d=Fl(await s.getThumbprint()),u=I$("PRIVATE",a);return{kid:s.serialNumber,cert:c,thumbprint:d,fingerprint:l,pkcs7:u,type:"jwt_signing"}}function I$(t,e){const n=Zb.encode(new Uint8Array(e));let r=`-----BEGIN ${t} KEY-----\r
77
+ `)}}ct.CertificateTag="CERTIFICATE";ct.CrlTag="CRL";ct.CertificateRequestTag="CERTIFICATE REQUEST";ct.PublicKeyTag="PUBLIC KEY";ct.PrivateKeyTag="PRIVATE KEY";class gn extends qn{static isAsnEncoded(e){return T.isBufferSource(e)||typeof e=="string"}static toArrayBuffer(e){if(typeof e=="string"){if(ct.isPem(e))return ct.decode(e)[0];if(F.isHex(e))return F.FromHex(e);if(F.isBase64(e))return F.FromBase64(e);if(F.isBase64Url(e))return F.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}else{const n=T.toUint8Array(e);if(n.length>0&&n[0]===48)return T.toArrayBuffer(e);const r=F.ToBinary(e);if(ct.isPem(r))return ct.decode(r)[0];if(F.isHex(r))return F.FromHex(r);if(F.isBase64(r))return F.FromBase64(r);if(F.isBase64Url(r))return F.FromBase64Url(r);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){gn.isAsnEncoded(e[0])?super(gn.toArrayBuffer(e[0]),e[1]):super(e[0])}toString(e="pem"){return e==="pem"?ct.encode(this.rawData,this.tag):super.toString(e)}}class jt extends gn{static async create(e,n=Oe.get()){if(e instanceof jt)return e;if(En.isCryptoKey(e)){if(e.type!=="public")throw new TypeError("Public key is required");const r=await n.subtle.exportKey("spki",e);return new jt(r)}else{if(e.publicKey)return e.publicKey;if(T.isBufferSource(e))return new jt(e);throw new TypeError("Unsupported PublicKeyType")}}constructor(e){gn.isAsnEncoded(e)?super(e,At):super(e),this.tag=ct.PublicKeyTag}async export(...e){let n,r=["verify"],i={hash:"SHA-256",...this.algorithm};e.length>1?(i=e[0]||i,r=e[1]||r,n=e[2]||Oe.get()):n=e[0]||Oe.get();let s=this.rawData;const a=O.parse(this.rawData,At);return a.algorithm.algorithm===po&&(s=z$(a,s)),n.subtle.importKey("spki",s,i,!0,r)}onInit(e){const n=Fe.resolve(yr),r=this.algorithm=n.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===gr){const i=O.parse(e.subjectPublicKey,xp),s=T.toUint8Array(i.modulus);r.publicExponent=T.toUint8Array(i.publicExponent),r.modulusLength=(s[0]?s:s.slice(1)).byteLength<<3}}async getThumbprint(...e){var n;let r,i="SHA-1";return e.length>=1&&!(!((n=e[0])===null||n===void 0)&&n.subtle)?(i=e[0]||i,r=e[1]||Oe.get()):r=e[0]||Oe.get(),await r.subtle.digest(i,this.rawData)}async getKeyIdentifier(...e){let n,r="SHA-1";e.length===1?typeof e[0]=="string"?(r=e[0],n=Oe.get()):n=e[0]:e.length===2?(r=e[0],n=e[1]):n=Oe.get();const i=O.parse(this.rawData,At);return await n.subtle.digest(r,i.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),n=O.parse(this.rawData,At);switch(e.Algorithm=wr.serializeAlgorithm(n.algorithm),n.algorithm.algorithm){case Ao:e["EC Point"]=n.subjectPublicKey;break;case gr:default:e["Raw Data"]=n.subjectPublicKey}return e}}function z$(t,e){return t.algorithm=new U({algorithm:gr,parameters:null}),e=O.serialize(t),e}class jo extends pt{static async create(e,n=!1,r=Oe.get()){if("name"in e&&"serialNumber"in e)return new jo(e,n);const s=await(await jt.create(e,r)).getKeyIdentifier(r);return new jo(F.ToHex(s),n)}constructor(...e){if(T.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]=="string"){const n=new Qn({keyIdentifier:new op(F.FromHex(e[0]))});super(id,e[1],O.serialize(n))}else{const n=e[0],r=n.name instanceof br?O.parse(n.name.rawData,We):n.name,i=new Qn({authorityCertIssuer:r,authorityCertSerialNumber:F.FromHex(n.serialNumber)});super(id,e[1],O.serialize(i))}}onInit(e){super.onInit(e);const n=O.parse(e.extnValue,Qn);n.keyIdentifier&&(this.keyId=F.ToHex(n.keyIdentifier)),(n.authorityCertIssuer||n.authorityCertSerialNumber)&&(this.certId={name:n.authorityCertIssuer||[],serialNumber:n.authorityCertSerialNumber?F.ToHex(n.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),n=O.parse(this.value,Qn);return n.authorityCertIssuer&&(e["Authority Issuer"]=new br(n.authorityCertIssuer).toTextObject()),n.authorityCertSerialNumber&&(e["Authority Serial Number"]=n.authorityCertSerialNumber),n.keyIdentifier&&(e[""]=n.keyIdentifier),e}}jo.NAME="Authority Key Identifier";class Ep extends pt{constructor(...e){if(T.isBufferSource(e[0])){super(e[0]);const n=O.parse(this.value,la);this.ca=n.cA,this.pathLength=n.pathLenConstraint}else{const n=new la({cA:e[0],pathLenConstraint:e[1]});super(jy,e[2],O.serialize(n)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e["Path Length"]=this.pathLength),e}}Ep.NAME="Basic Constraints";var Eg;(function(t){t.serverAuth="1.3.6.1.5.5.7.3.1",t.clientAuth="1.3.6.1.5.5.7.3.2",t.codeSigning="1.3.6.1.5.5.7.3.3",t.emailProtection="1.3.6.1.5.5.7.3.4",t.timeStamping="1.3.6.1.5.5.7.3.8",t.ocspSigning="1.3.6.1.5.5.7.3.9"})(Eg||(Eg={}));class Cp extends pt{constructor(...e){if(T.isBufferSource(e[0])){super(e[0]);const n=O.parse(this.value,fa);this.usages=n.map(r=>r)}else{const n=new fa(e[0]);super(Ty,e[1],O.serialize(n)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(n=>Mn.toString(n)).join(", "),e}}Cp.NAME="Extended Key Usages";var Ua;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(Ua||(Ua={}));class Np extends pt{constructor(...e){if(T.isBufferSource(e[0])){super(e[0]);const n=O.parse(this.value,hl);this.usages=n.toNumber()}else{const n=new hl(e[0]);super(By,e[1],O.serialize(n)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),n=O.parse(this.value,hl);return e[""]=n.toJSON().join(", "),e}}Np.NAME="Key Usages";class cs extends pt{static async create(e,n=!1,r=Oe.get()){const s=await(await jt.create(e,r)).getKeyIdentifier(r);return new cs(F.ToHex(s),n)}constructor(...e){if(T.isBufferSource(e[0])){super(e[0]);const n=O.parse(this.value,jn);this.keyId=F.ToHex(n)}else{const n=typeof e[0]=="string"?F.FromHex(e[0]):e[0],r=new jn(n);super(My,e[1],O.serialize(r)),this.keyId=F.ToHex(n)}}toTextObject(){const e=this.toTextObjectWithoutValue(),n=O.parse(this.value,jn);return e[""]=n,e}}cs.NAME="Subject Key Identifier";class g1 extends pt{constructor(...e){T.isBufferSource(e[0])?super(e[0]):super(Dy,e[1],new br(e[0]||[]).rawData)}onInit(e){super.onInit(e);const n=O.parse(e.extnValue,wd);this.names=new br(n)}toTextObject(){const e=this.toTextObjectWithoutValue(),n=this.names.toTextObject();for(const r in n)e[r]=n[r];return e}}g1.NAME="Subject Alternative Name";class ft{static register(e,n){this.items.set(e,n)}static create(e){const n=new pt(e),r=this.items.get(n.type);return r?new r(e):n}}ft.items=new Map;class m1 extends pt{constructor(...e){var n;if(T.isBufferSource(e[0])){super(e[0]);const r=O.parse(this.value,ua);this.policies=r.map(i=>i.policyIdentifier)}else{const r=e[0],i=(n=e[1])!==null&&n!==void 0?n:!1,s=new ua(r.map(a=>new xc({policyIdentifier:a})));super(Py,i,O.serialize(s)),this.policies=r}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(n=>new de("",{},Mn.toString(n))),e}}m1.NAME="Certificate Policies";ft.register(Py,m1);class _1 extends pt{constructor(...e){var n;if(T.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]=="string"){const i=e[0].map(a=>new wi({distributionPoint:new ur({fullName:[new ee({uniformResourceIdentifier:a})]})})),s=new Vr(i);super(ld,e[1],O.serialize(s))}else{const r=new Vr(e[0]);super(ld,e[1],O.serialize(r))}(n=this.distributionPoints)!==null&&n!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);const n=O.parse(e.extnValue,Vr);this.distributionPoints=n}toTextObject(){const e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(n=>{var r;const i={};return n.distributionPoint&&(i[""]=(r=n.distributionPoint.fullName)===null||r===void 0?void 0:r.map(s=>new Cn(s).toString()).join(", ")),n.reasons&&(i.Reasons=n.reasons.toString()),n.cRLIssuer&&(i["CRL Issuer"]=n.cRLIssuer.map(s=>s.toString()).join(", ")),i}),e}}_1.NAME="CRL Distribution Points";class y1 extends pt{constructor(...e){var n,r,i,s;if(T.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof Ur){const a=new Ur(e[0]);super(rd,e[1],O.serialize(a))}else{const a=e[0],c=new Ur;vs(c,a,ph,"ocsp"),vs(c,a,fh,"caIssuers"),vs(c,a,hh,"timeStamping"),vs(c,a,gh,"caRepository"),super(rd,e[1],O.serialize(c))}(n=this.ocsp)!==null&&n!==void 0||(this.ocsp=[]),(r=this.caIssuers)!==null&&r!==void 0||(this.caIssuers=[]),(i=this.timeStamping)!==null&&i!==void 0||(this.timeStamping=[]),(s=this.caRepository)!==null&&s!==void 0||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],O.parse(e.extnValue,Ur).forEach(r=>{switch(r.accessMethod){case ph:this.ocsp.push(new Cn(r.accessLocation));break;case fh:this.caIssuers.push(new Cn(r.accessLocation));break;case hh:this.timeStamping.push(new Cn(r.accessLocation));break;case gh:this.caRepository.push(new Cn(r.accessLocation));break}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&bs(e,"OCSP",this.ocsp),this.caIssuers.length&&bs(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&bs(e,"Time Stamping",this.timeStamping),this.caRepository.length&&bs(e,"CA Repository",this.caRepository),e}}y1.NAME="Authority Info Access";function bs(t,e,n){if(n.length===1)t[e]=n[0].toTextObject();else{const r=new de("");n.forEach((i,s)=>{const a=i.toTextObject(),c=`${a[de.NAME]} ${s+1}`;let l=r[c];Array.isArray(l)||(l=[],r[c]=l),l.push(a)}),t[e]=r}}function vs(t,e,n,r){const i=e[r];i&&(Array.isArray(i)?i:[i]).forEach(a=>{typeof a=="string"&&(a=new Cn("url",a)),t.push(new Jo({accessMethod:n,accessLocation:O.parse(a.rawData,ee)}))})}class w1 extends pt{constructor(...e){T.isBufferSource(e[0])?super(e[0]):super(Ry,e[1],new br(e[0]||[]).rawData)}onInit(e){super.onInit(e);const n=O.parse(e.extnValue,We);this.names=new br(n)}toTextObject(){const e=this.toTextObjectWithoutValue(),n=this.names.toTextObject();for(const r in n)e[r]=n[r];return e}}w1.NAME="Issuer Alternative Name";class zi extends qn{constructor(...e){let n;if(T.isBufferSource(e[0]))n=T.toArrayBuffer(e[0]);else{const r=e[0],i=Array.isArray(e[1])?e[1].map(s=>T.toArrayBuffer(s)):[];n=O.serialize(new pn({type:r,values:i}))}super(n,pn)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(n=>new de("",{"":n})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[de.NAME]===zi.NAME&&(e[de.NAME]=Mn.toString(this.type)),e}}zi.NAME="Attribute";class b1 extends zi{constructor(...e){var n;if(T.isBufferSource(e[0]))super(e[0]);else{const r=new Ba({printableString:e[0]});super(l1,[O.serialize(r)])}(n=this.password)!==null&&n!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const n=O.parse(this.values[0],Ba);this.password=n.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[de.VALUE]=this.password,e}}b1.NAME="Challenge Password";class Ip extends zi{constructor(...e){var n;if(T.isBufferSource(e[0]))super(e[0]);else{const r=e[0],i=new Tn;for(const s of r)i.push(O.parse(s.rawData,yt));super(Ap,[O.serialize(i)])}(n=this.items)!==null&&n!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const n=O.parse(this.values[0],Tn);this.items=n.map(r=>ft.create(O.serialize(r)))}}toTextObject(){const e=this.toTextObjectWithoutValue(),n=this.items.map(r=>r.toTextObject());for(const r of n)e[r[de.NAME]]=r;return e}}Ip.NAME="Extensions";class Gc{static register(e,n){this.items.set(e,n)}static create(e){const n=new zi(e),r=this.items.get(n.type);return r?new r(e):n}}Gc.items=new Map;const ls="crypto.signatureFormatter";class A${toAsnSignature(e,n){return T.toArrayBuffer(n)}toWebSignature(e,n){return T.toArrayBuffer(n)}}var Os;let lu=Os=class{static createPssParams(e,n){const r=Os.getHashAlgorithm(e);return r?new _r({hashAlgorithm:r,maskGenAlgorithm:new U({algorithm:Lc,parameters:O.serialize(r)}),saltLength:n}):null}static getHashAlgorithm(e){const n=Fe.resolve(yr);return typeof e=="string"?n.toAsnAlgorithm({name:e}):typeof e=="object"&&e&&"name"in e?n.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if("hash"in e){let n;if(typeof e.hash=="string")n=e.hash;else if(e.hash&&typeof e.hash=="object"&&"name"in e.hash&&typeof e.hash.name=="string")n=e.hash.name.toUpperCase();else throw new Error("Cannot get hash algorithm name");switch(n.toLowerCase()){case"sha-1":return new U({algorithm:Aa,parameters:null});case"sha-256":return new U({algorithm:Dd,parameters:null});case"sha-384":return new U({algorithm:Ea,parameters:null});case"sha-512":return new U({algorithm:Ca,parameters:null})}}else return new U({algorithm:gr,parameters:null});break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e&&typeof e.saltLength=="number"))throw new Error("Cannot get 'saltLength' from 'alg' argument");const n=Os.createPssParams(e.hash,e.saltLength);if(!n)throw new Error("Cannot create PSS parameters");return new U({algorithm:po,parameters:O.serialize(n)})}else return new U({algorithm:po,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case gr:return{name:"RSASSA-PKCS1-v1_5"};case Aa:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case Dd:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case Ea:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case Ca:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case po:if(e.parameters){const n=O.parse(e.parameters,_r);return{name:"RSA-PSS",hash:Fe.resolve(yr).toWebAlgorithm(n.hashAlgorithm),saltLength:n.saltLength}}else return{name:"RSA-PSS"}}return null}};lu=Os=h([qc()],lu);Fe.registerSingleton(as,lu);let du=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new U({algorithm:Na});case"sha-256":return new U({algorithm:Ia});case"sha-384":return new U({algorithm:ja});case"sha-512":return new U({algorithm:Pa})}return null}toWebAlgorithm(e){switch(e.algorithm){case Na:return{name:"SHA-1"};case Ia:return{name:"SHA-256"};case ja:return{name:"SHA-384"};case Pa:return{name:"SHA-512"}}return null}};du=h([qc()],du);Fe.registerSingleton(as,du);class gt{addPadding(e,n){const r=T.toUint8Array(n),i=new Uint8Array(e);return i.set(r,e-r.length),i.buffer}removePadding(e,n=!1){let r=T.toUint8Array(e);for(let i=0;i<r.length;i++)if(r[i]){r=r.slice(i);break}if(n&&r[0]>127){const i=new Uint8Array(r.length+1);return i.set(r,1),i.buffer}return r.buffer}toAsnSignature(e,n){if(e.name==="ECDSA"){const r=e.namedCurve,i=gt.namedCurveSize.get(r)||gt.defaultNamedCurveSize,s=new za,a=T.toUint8Array(n);return s.r=this.removePadding(a.slice(0,i),!0),s.s=this.removePadding(a.slice(i,i+i),!0),O.serialize(s)}return null}toWebSignature(e,n){if(e.name==="ECDSA"){const r=O.parse(n,za),i=e.namedCurve,s=gt.namedCurveSize.get(i)||gt.defaultNamedCurveSize,a=this.addPadding(s,this.removePadding(r.r)),c=this.addPadding(s,this.removePadding(r.s));return D3(a,c)}return null}}gt.namedCurveSize=new Map;gt.defaultNamedCurveSize=32;const $l="1.3.101.110",Cg="1.3.101.111",kl="1.3.101.112",Ng="1.3.101.113";let uu=class{toAsnAlgorithm(e){let n=null;switch(e.name.toLowerCase()){case"ed25519":n=kl;break;case"x25519":n=$l;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":n=kl;break;case"ed448":n=Ng;break}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":n=$l;break;case"x448":n=Cg;break}}return n?new U({algorithm:n}):null}toWebAlgorithm(e){switch(e.algorithm){case kl:return{name:"Ed25519"};case Ng:return{name:"EdDSA",namedCurve:"Ed448"};case $l:return{name:"X25519"};case Cg:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};uu=h([qc()],uu);Fe.registerSingleton(as,uu);var Bi,Li,Ui,Di,Mi,qi,Fi,Pr;class E$ extends gn{get subjectName(){return re(this,Li,"f")||ye(this,Li,new Et(this.asn.certificationRequestInfo.subject),"f"),re(this,Li,"f")}get subject(){return re(this,Ui,"f")||ye(this,Ui,this.subjectName.toString(),"f"),re(this,Ui,"f")}get signatureAlgorithm(){if(!re(this,Di,"f")){const e=Fe.resolve(yr);ye(this,Di,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return re(this,Di,"f")}get signature(){return re(this,Mi,"f")||ye(this,Mi,this.asn.signature,"f"),re(this,Mi,"f")}get publicKey(){return re(this,qi,"f")||ye(this,qi,new jt(this.asn.certificationRequestInfo.subjectPKInfo),"f"),re(this,qi,"f")}get attributes(){return re(this,Fi,"f")||ye(this,Fi,this.asn.certificationRequestInfo.attributes.map(e=>Gc.create(O.serialize(e))),"f"),re(this,Fi,"f")}get extensions(){if(!re(this,Pr,"f")){ye(this,Pr,[],"f");const e=this.getAttribute(Ap);e instanceof Ip&&ye(this,Pr,e.items,"f")}return re(this,Pr,"f")}get tbs(){return re(this,Bi,"f")||ye(this,Bi,this.asn.certificationRequestInfoRaw||O.serialize(this.asn.certificationRequestInfo),"f"),re(this,Bi,"f")}constructor(e){const n=gn.isAsnEncoded(e)?[e,Co]:[e];super(n[0],n[1]),Bi.set(this,void 0),Li.set(this,void 0),Ui.set(this,void 0),Di.set(this,void 0),Mi.set(this,void 0),qi.set(this,void 0),Fi.set(this,void 0),Pr.set(this,void 0),this.tag=ct.CertificateRequestTag}onInit(e){}getAttribute(e){for(const n of this.attributes)if(n.type===e)return n;return null}getAttributes(e){return this.attributes.filter(n=>n.type===e)}getExtension(e){for(const n of this.extensions)if(n.type===e)return n;return null}getExtensions(e){return this.extensions.filter(n=>n.type===e)}async verify(e=Oe.get()){const n={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(n,["verify"],e),i=Fe.resolveAll(ls).reverse();let s=null;for(const c of i)if(s=c.toWebSignature(n,this.signature),s)break;if(!s)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,r,s,this.tbs)}toTextObject(){const e=this.toTextObjectEmpty(),n=O.parse(this.rawData,Co),r=n.certificationRequestInfo,i=new de("",{Version:`${pr[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const s=new de("");for(const a of this.attributes){const c=a.toTextObject();s[c[de.NAME]]=c}i.Attributes=s}return e.Data=i,e.Signature=new de("",{Algorithm:wr.serializeAlgorithm(n.signatureAlgorithm),"":n.signature}),e}}Bi=new WeakMap,Li=new WeakMap,Ui=new WeakMap,Di=new WeakMap,Mi=new WeakMap,qi=new WeakMap,Fi=new WeakMap,Pr=new WeakMap;E$.NAME="PKCS#10 Certificate Request";var Hi,Vi,Ki,Gi,Wi,Ji,Xi,Zi,Yi,Qi,Or,eo;class Wc extends gn{get publicKey(){return re(this,eo,"f")||ye(this,eo,new jt(this.asn.tbsCertificate.subjectPublicKeyInfo),"f"),re(this,eo,"f")}get serialNumber(){if(!re(this,Vi,"f")){const e=this.asn.tbsCertificate;let n=new Uint8Array(e.serialNumber);n.length>1&&n[0]===0&&n[1]>127&&(n=n.slice(1)),ye(this,Vi,F.ToHex(n),"f")}return re(this,Vi,"f")}get subjectName(){return re(this,Ki,"f")||ye(this,Ki,new Et(this.asn.tbsCertificate.subject),"f"),re(this,Ki,"f")}get subject(){return re(this,Gi,"f")||ye(this,Gi,this.subjectName.toString(),"f"),re(this,Gi,"f")}get issuerName(){return re(this,Wi,"f")||ye(this,Wi,new Et(this.asn.tbsCertificate.issuer),"f"),re(this,Wi,"f")}get issuer(){return re(this,Ji,"f")||ye(this,Ji,this.issuerName.toString(),"f"),re(this,Ji,"f")}get notBefore(){if(!re(this,Xi,"f")){const e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");ye(this,Xi,e,"f")}return re(this,Xi,"f")}get notAfter(){if(!re(this,Zi,"f")){const e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");ye(this,Zi,e,"f")}return re(this,Zi,"f")}get signatureAlgorithm(){if(!re(this,Yi,"f")){const e=Fe.resolve(yr);ye(this,Yi,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return re(this,Yi,"f")}get signature(){return re(this,Qi,"f")||ye(this,Qi,this.asn.signatureValue,"f"),re(this,Qi,"f")}get extensions(){return re(this,Or,"f")||(ye(this,Or,[],"f"),this.asn.tbsCertificate.extensions&&ye(this,Or,this.asn.tbsCertificate.extensions.map(e=>ft.create(O.serialize(e))),"f")),re(this,Or,"f")}get tbs(){return re(this,Hi,"f")||ye(this,Hi,this.asn.tbsCertificateRaw||O.serialize(this.asn.tbsCertificate),"f"),re(this,Hi,"f")}constructor(e){const n=gn.isAsnEncoded(e)?[e,fr]:[e];super(n[0],n[1]),Hi.set(this,void 0),Vi.set(this,void 0),Ki.set(this,void 0),Gi.set(this,void 0),Wi.set(this,void 0),Ji.set(this,void 0),Xi.set(this,void 0),Zi.set(this,void 0),Yi.set(this,void 0),Qi.set(this,void 0),Or.set(this,void 0),eo.set(this,void 0),this.tag=ct.CertificateTag}onInit(e){}getExtension(e){for(const n of this.extensions)if(typeof e=="string"){if(n.type===e)return n}else if(n instanceof e)return n;return null}getExtensions(e){return this.extensions.filter(n=>typeof e=="string"?n.type===e:n instanceof e)}async verify(e={},n=Oe.get()){let r,i;const s=e.publicKey;try{if(!s)r={...this.publicKey.algorithm,...this.signatureAlgorithm},i=await this.publicKey.export(r,["verify"],n);else if("publicKey"in s)r={...s.publicKey.algorithm,...this.signatureAlgorithm},i=await s.publicKey.export(r,["verify"],n);else if(s instanceof jt)r={...s.algorithm,...this.signatureAlgorithm},i=await s.export(r,["verify"],n);else if(T.isBufferSource(s)){const d=new jt(s);r={...d.algorithm,...this.signatureAlgorithm},i=await d.export(r,["verify"],n)}else r={...s.algorithm,...this.signatureAlgorithm},i=s}catch{return!1}const a=Fe.resolveAll(ls).reverse();let c=null;for(const d of a)if(c=d.toWebSignature(r,this.signature),c)break;if(!c)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const l=await n.subtle.verify(this.signatureAlgorithm,i,c,this.tbs);if(e.signatureOnly)return l;{const u=(e.date||new Date).getTime();return l&&this.notBefore.getTime()<u&&u<this.notAfter.getTime()}}async getThumbprint(...e){let n,r="SHA-1";return e[0]&&(e[0].subtle?n=e[0]:(r=e[0]||r,n=e[1])),n??(n=Oe.get()),await n.subtle.digest(r,this.rawData)}async isSelfSigned(e=Oe.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),n=O.parse(this.rawData,fr),r=n.tbsCertificate,i=new de("",{Version:`${pr[r.version]} (${r.version})`,"Serial Number":r.serialNumber,"Signature Algorithm":wr.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new de("",{"Not Before":r.validity.notBefore.getTime(),"Not After":r.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(r.issuerUniqueID&&(i["Issuer Unique ID"]=r.issuerUniqueID),r.subjectUniqueID&&(i["Subject Unique ID"]=r.subjectUniqueID),this.extensions.length){const s=new de("");for(const a of this.extensions){const c=a.toTextObject();s[c[de.NAME]]=c}i.Extensions=s}return e.Data=i,e.Signature=new de("",{Algorithm:wr.serializeAlgorithm(n.signatureAlgorithm),"":n.signatureValue}),e}}Hi=new WeakMap,Vi=new WeakMap,Ki=new WeakMap,Gi=new WeakMap,Wi=new WeakMap,Ji=new WeakMap,Xi=new WeakMap,Zi=new WeakMap,Yi=new WeakMap,Qi=new WeakMap,Or=new WeakMap,eo=new WeakMap;Wc.NAME="Certificate";function C$(t,e=Oe.get()){const n=T.toUint8Array(F.FromHex(t||""));let r=n&&n.length&&n.some(s=>s>0)?new Uint8Array(n):void 0;r||(r=e.getRandomValues(new Uint8Array(16)));let i=0;for(;i<r.length-1&&r[i]===0;)i++;if(r=r.slice(i),r[0]>127){const s=new Uint8Array(r.length+1);s[0]=0,s.set(r,1),r=s}return r.buffer}class N${static async createSelfSigned(e,n=Oe.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},n)}static async create(e,n=Oe.get()){var r;let i;e.publicKey instanceof jt?i=e.publicKey.rawData:"publicKey"in e.publicKey?i=e.publicKey.publicKey.rawData:T.isBufferSource(e.publicKey)?i=e.publicKey:i=await n.subtle.exportKey("spki",e.publicKey);const s=C$(e.serialNumber,n),a=e.notBefore||new Date,c=e.notAfter||new Date(a.getTime()+31536e6),l=new fr({tbsCertificate:new ut({version:pr.v3,serialNumber:s,validity:new Xo({notBefore:a,notAfter:c}),extensions:new Tn(((r=e.extensions)===null||r===void 0?void 0:r.map(z=>O.parse(z.rawData,yt)))||[]),subjectPublicKeyInfo:O.parse(i,At)})});if(e.subject){const z=e.subject instanceof Et?e.subject:new Et(e.subject);l.tbsCertificate.subject=O.parse(z.toArrayBuffer(),Ce)}if(e.issuer){const z=e.issuer instanceof Et?e.issuer:new Et(e.issuer);l.tbsCertificate.issuer=O.parse(z.toArrayBuffer(),Ce)}const d={hash:"SHA-256"},u="signingKey"in e?{...d,...e.signingAlgorithm,...e.signingKey.algorithm}:{...d,...e.signingAlgorithm},f=Fe.resolve(yr);l.tbsCertificate.signature=l.signatureAlgorithm=f.toAsnAlgorithm(u);const g=O.serialize(l.tbsCertificate),_="signingKey"in e?await n.subtle.sign(u,e.signingKey,g):e.signature,w=Fe.resolveAll(ls).reverse();let k=null;for(const z of w)if(k=z.toAsnSignature(u,_),k)break;if(!k)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return l.signatureValue=k,new Wc(O.serialize(l))}}var Ig;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(Ig||(Ig={}));ft.register(jy,Ep);ft.register(Ty,Cp);ft.register(By,Np);ft.register(My,cs);ft.register(id,jo);ft.register(Dy,g1);ft.register(ld,_1);ft.register(rd,y1);ft.register(Ry,w1);Gc.register(l1,b1);Gc.register(Ap,Ip);Fe.registerSingleton(ls,A$);Fe.registerSingleton(ls,gt);gt.namedCurveSize.set("P-256",32);gt.namedCurveSize.set("K-256",32);gt.namedCurveSize.set("P-384",48);gt.namedCurveSize.set("P-521",66);async function Da(t){const e={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",publicExponent:new Uint8Array([1,0,1]),modulusLength:2048},n=await crypto.subtle.generateKey(e,!0,["sign","verify"]),r=pe(),i=Fl(new TextEncoder().encode(r)),s=await N$.createSelfSigned({serialNumber:i,name:t.name,notBefore:new Date,notAfter:new Date(Date.now()+365*24*60*60*1e3),signingAlgorithm:e,keys:n,extensions:[new Ep(!0,2,!0),new Cp(["1.3.6.1.5.5.7.3.1"],!0),new Np(Ua.keyCertSign|Ua.cRLSign,!0),await cs.create(n.publicKey)]}),a=await crypto.subtle.exportKey("pkcs8",n.privateKey),c=s.toString("pem"),l=await j$(s),d=Fl(await s.getThumbprint()),u=I$("PRIVATE",a);return{kid:s.serialNumber,cert:c,thumbprint:d,fingerprint:l,pkcs7:u,type:"jwt_signing"}}function I$(t,e){const n=Zb.encode(new Uint8Array(e));let r=`-----BEGIN ${t} KEY-----\r
78
78
  `,i=0;for(;i<n.length;)i+64<=n.length?r+=n.substr(i,64)+`\r
79
79
  `:r+=n.substr(i)+`\r
80
80
  `,i+=64;return r+=`-----END ${t} KEY-----\r
81
- `,r}async function j$(t){const e=await t.publicKey.export(),n=await crypto.subtle.exportKey("jwk",e),r=JSON.stringify(n,Object.keys(n).sort()),s=new TextEncoder().encode(r);return Fl(await Ym(s))}const P$=1e3*60*60*24,O$=new o.OpenAPIHono().openapi(o.createRoute({tags:["keys"],method:"get",path:"/signing",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(Ul)}},description:"List of keys"}}}),async t=>{const{signingKeys:e}=await t.env.data.keys.list({q:"type:jwt_signing"}),n=e.filter(r=>"cert"in r).map(r=>r);return t.json(n)}).openapi(o.createRoute({tags:["keys"],method:"get",path:"/signing/{kid}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({kid:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ul}},description:"The requested key"}}}),async t=>{const{kid:e}=t.req.valid("param"),{signingKeys:n}=await t.env.data.keys.list({q:"type:jwt_signing"}),r=n.find(i=>i.kid===e);if(!r)throw new v(404,{message:"Key not found"});return t.json(r)}).openapi(o.createRoute({tags:["keys"],method:"post",path:"/signing/rotate",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Status"}}}),async t=>{const{signingKeys:e}=await t.env.data.keys.list({q:"type:jwt_signing"});for await(const r of e)await t.env.data.keys.update(r.kid,{revoked_at:new Date(Date.now()+P$).toISOString()});const n=await Da({name:`CN=${t.env.ORGANIZATION_NAME}`});return await t.env.data.keys.create({...n,type:"jwt_signing"}),t.text("OK",{status:201})}).openapi(o.createRoute({tags:["keys"],method:"put",path:"/signing/{kid}/revoke",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({kid:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Status"}}}),async t=>{const{kid:e}=t.req.valid("param");if(!await t.env.data.keys.update(e,{revoked_at:new Date().toISOString()}))throw new v(404,{message:"Key not found"});const r=await Da({name:`CN=${t.env.ORGANIZATION_NAME}`});return await t.env.data.keys.create({...r,type:"jwt_signing"}),t.text("OK")}),T$=new o.OpenAPIHono().openapi(o.createRoute({tags:["users"],method:"get",path:"/",request:{query:o.z.object({email:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:o.z.array(Su)}},description:"List of users"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{email:n}=t.req.valid("query"),i=(await Ru(t.env.data.users,e,n)).filter(s=>!s.linked_to);return t.json(i)}),R$=it.extend({clients:o.z.array(Jn)}),jg=o.z.object({enabled_connections:o.z.array(o.z.object({connection_id:o.z.string(),connection:ht.optional()}))}),B$=o.z.array(o.z.string()),L$=new o.OpenAPIHono().openapi(o.createRoute({tags:["clients"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([R$,o.z.array(Jn)])}},description:"List of clients"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i,sort:s,q:a}=t.req.valid("query"),l=(await t.env.data.clients.list(e,{page:n,per_page:r,include_totals:i,sort:Ke(s),q:a})).clients;return i?t.json({clients:l,start:0,limit:10,length:l.length}):t.json(l)}).openapi(o.createRoute({tags:["clients"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Jn}},description:"A client"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.clients.get(e,n);if(!r)throw new v(404);return t.json(r)}).openapi(o.createRoute({tags:["clients"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.clients.remove(e,n))throw new v(404,{message:"Client not found"});return t.text("OK")}).openapi(o.createRoute({tags:["clients"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(Hs.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Jn}},description:"The updated client"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),i=t.req.valid("json");await t.env.data.clients.update(e,n,i);const s=await t.env.data.clients.get(e,n);if(!s)throw new v(404,{message:"Client not found"});return t.json(s)}).openapi(o.createRoute({tags:["clients"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Hs.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:o.z.object(Jn.shape)}},description:"A client"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r={...n,client_secret:n.client_secret||pe()},i=await t.env.data.clients.create(e,r);return t.json(i,{status:201})}).openapi(o.createRoute({tags:["clients"],method:"get",path:"/{id}/connections",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:jg}},description:"List of connections enabled for this client"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.clients.get(e,n);if(!r)throw new v(404,{message:"Client not found"});const i=r.connections&&r.connections.length>0;let s;if(i)s=await Promise.all(r.connections.map(async a=>{const c=await t.env.data.connections.get(e,a);return{connection_id:a,connection:c||void 0}}));else{const{connections:a}=await t.env.data.connections.list(e,{});s=a.filter(c=>c.id).map(c=>({connection_id:c.id,connection:c}))}return t.json({enabled_connections:s})}).openapi(o.createRoute({tags:["clients"],method:"patch",path:"/{id}/connections",request:{body:{content:{"application/json":{schema:B$}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:jg}},description:"Updated list of connections for this client"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.clients.get(e,n))throw new v(404,{message:"Client not found"});const s=[];for(const c of r)await t.env.data.connections.get(e,c)&&s.push(c);await t.env.data.clients.update(e,n,{connections:s});const a=await Promise.all(s.map(async c=>{const l=await t.env.data.connections.get(e,c);return{connection_id:c,connection:l||void 0}}));return t.json({enabled_connections:a})});o.z.object({start:o.z.number(),limit:o.z.number(),length:o.z.number()});Va.extend({email:o.z.string(),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());const U$=it.extend({tenants:o.z.array(Sn)}),D$=new o.OpenAPIHono().openapi(o.createRoute({tags:["tenants","settings"],method:"get",path:"/settings",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Sn}},description:"Current tenant settings"}}}),async t=>{const e=await t.env.data.tenants.get(t.var.tenant_id);if(!e)throw new v(404,{message:"Tenant not found"});return t.json(e)}).openapi(o.createRoute({tags:["tenants","settings"],method:"patch",path:"/settings",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(ro.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Sn}},description:"Updated tenant settings"}}}),async t=>{const e=t.req.valid("json"),{id:n,...r}=e,i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new v(404,{message:"Tenant not found"});const s=Dl(i,r);await t.env.data.tenants.update(t.var.tenant_id,s);const a=await t.env.data.tenants.get(t.var.tenant_id);if(!a)throw new v(500,{message:"Failed to retrieve updated tenant"});return t.json(a)}).openapi(o.createRoute({tags:["tenants"],method:"get",path:"/",request:{query:Te},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:o.z.union([o.z.array(Sn),U$])}},description:"List of tenants"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),a=await t.env.data.tenants.list({page:e,per_page:n,include_totals:r,sort:Ke(i),q:s});return r?t.json(a):t.json(a.tenants)}).openapi(o.createRoute({tags:["tenants"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:Sn}},description:"A tenant"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.tenants.get(e);if(!n)throw new v(404);return t.json(n)}).openapi(o.createRoute({tags:["tenants"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param");return await t.env.data.tenants.remove(e),t.text("OK")}).openapi(o.createRoute({tags:["tenants"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(ro.shape).partial()}}},params:o.z.object({id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param"),n=t.req.valid("json");return await t.env.data.tenants.update(e,n),t.text("OK")}).openapi(o.createRoute({tags:["tenants"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(ro.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"tenant/json":{schema:Sn}},description:"An tenant"}}}),async t=>{const e=t.req.valid("json"),n=await t.env.data.tenants.create(e);return t.json(n,{status:201})}),M$=it.extend({logs:o.z.array(Ws)}),q$=new o.OpenAPIHono().openapi(o.createRoute({tags:["logs"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Ws),M$])}},description:"List of log rows"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),a=await t.env.data.logs.list(t.var.tenant_id,{page:e,per_page:n,include_totals:r,sort:Ke(i),q:s});return r?t.json(a):t.json(a.logs)}).openapi(o.createRoute({tags:["logs"],method:"get",path:"/{id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ws}},description:"A log entry"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.logs.get(t.var.tenant_id,e);if(!n)throw new v(404);return t.json(n)}),F$=17,H$={organization:"org_",connection:"con_",action:"act_",hook:"h_",rule:"rul_",resource_server:"api_",guardian_factor:"gfa_",invite:"inv_"};function Jc(t){const r=Jm("0123456789abcdefghijklmnopqrstuvwxyz",F$)();return`${H$[t]}${r}`}function V$(){return Jc("organization")}function K$(){return Jc("connection")}function G$(){return Jc("hook")}function W$(){return Jc("invite")}const J$=it.extend({hooks:o.z.array(Lr)}),X$=new o.OpenAPIHono().openapi(o.createRoute({tags:["hooks"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Lr),J$])}},description:"List of hooks"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),a=await t.env.data.hooks.list(t.var.tenant_id,{page:e,per_page:n,include_totals:r,sort:Ke(i),q:s});return r?t.json(a):t.json(a.hooks)}).openapi(o.createRoute({tags:["hooks"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:ks}}}},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Lr}},description:"The created hook"}}}),async t=>{const e=t.req.valid("json"),n={...e,hook_id:e.hook_id||G$()},r=await t.env.data.hooks.create(t.var.tenant_id,n);return t.json(r,{status:201})}).openapi(o.createRoute({tags:["hooks"],method:"patch",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({hook_id:o.z.string()}),body:{content:{"application/json":{schema:o.z.union([ks.options[0].omit({hook_id:!0}).partial(),ks.options[1].omit({hook_id:!0}).partial()])}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Lr}},description:"The updated hook"},404:{description:"Hook not found"}}}),async t=>{const{hook_id:e}=t.req.valid("param"),n=t.req.valid("json");await t.env.data.hooks.update(t.var.tenant_id,e,n);const r=await t.env.data.hooks.get(t.var.tenant_id,e);if(!r)throw new v(404,{message:"Hook not found"});return t.json(r)}).openapi(o.createRoute({tags:["hooks"],method:"get",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({hook_id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Lr}},description:"A hook"},404:{description:"Hook not found"}}}),async t=>{const{hook_id:e}=t.req.valid("param"),n=await t.env.data.hooks.get(t.var.tenant_id,e);if(!n)throw new v(404,{message:"Hook not found"});return t.json(n)}).openapi(o.createRoute({tags:["hooks"],method:"delete",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({hook_id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{description:"A hook"}}}),async t=>{const{hook_id:e}=t.req.valid("param");if(!await t.env.data.hooks.remove(t.var.tenant_id,e))throw new v(404,{message:"Hook not found"});return t.text("OK")}),Z$=it.extend({connections:o.z.array(ht)}),Y$=o.z.object({enabled_clients:o.z.array(o.z.object({client_id:o.z.string(),name:o.z.string()}))}),Q$=o.z.array(o.z.object({client_id:o.z.string(),status:o.z.boolean()})),ek=new o.OpenAPIHono().openapi(o.createRoute({tags:["connections"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(ht),Z$])}},description:"List of connectionss"}}}),async t=>{const{page:e,per_page:n,include_totals:r=!1,sort:i,q:s}=t.req.valid("query"),a=await t.env.data.connections.list(t.var.tenant_id,{page:e,per_page:n,include_totals:r,sort:Ke(i),q:s});return r?t.json(a):t.json(a.connections)}).openapi(o.createRoute({tags:["connections"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:ht}},description:"A connection"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.connections.get(t.var.tenant_id,e);if(!n)throw new v(404);return t.json(n)}).openapi(o.createRoute({tags:["connections"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param");if(!await t.env.data.connections.remove(t.var.tenant_id,e))throw new v(404,{message:"Connection not found"});return t.text("OK")}).openapi(o.createRoute({tags:["connections"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(Ks.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:ht}},description:"The updated connection"}}}),async t=>{const{id:e}=t.req.valid("param"),n=t.req.valid("json");if(!await t.env.data.connections.update(t.var.tenant_id,e,n))throw new v(404,{message:"Connection not found"});const i=await t.env.data.connections.get(t.var.tenant_id,e);if(!i)throw new v(404,{message:"Connection not found"});return t.json(i)}).openapi(o.createRoute({tags:["connections"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Ks.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:ht}},description:"A connection"}}}),async t=>{const e=t.req.valid("json"),n={...e,id:e.id||K$()},r=await t.env.data.connections.create(t.var.tenant_id,n);return t.json(r,{status:201})}).openapi(o.createRoute({tags:["connections"],method:"get",path:"/{id}/clients",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Y$}},description:"List of clients enabled for this connection"}}}),async t=>{const{id:e}=t.req.valid("param");if(!await t.env.data.connections.get(t.var.tenant_id,e))throw new v(404,{message:"Connection not found"});const{clients:r}=await t.env.data.clients.list(t.var.tenant_id,{per_page:1e3}),i=r.filter(s=>s.connections?.includes(e)).map(s=>({client_id:s.client_id,name:s.name}));return t.json({enabled_clients:i})}).openapi(o.createRoute({tags:["connections"],method:"patch",path:"/{id}/clients",request:{body:{content:{"application/json":{schema:Q$}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Clients updated successfully"}}}),async t=>{const{id:e}=t.req.valid("param"),n=t.req.valid("json");if(!await t.env.data.connections.get(t.var.tenant_id,e))throw new v(404,{message:"Connection not found"});for(const i of n){const s=await t.env.data.clients.get(t.var.tenant_id,i.client_id);if(!s)continue;const a=s.connections||[];i.status?a.includes(e)||await t.env.data.clients.update(t.var.tenant_id,i.client_id,{connections:[...a,e]}):a.includes(e)&&await t.env.data.clients.update(t.var.tenant_id,i.client_id,{connections:a.filter(c=>c!==e)})}return t.text("OK")}),tk=new o.OpenAPIHono().openapi(o.createRoute({tags:["prompts"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ss}},description:"Branding settings"}}}),async t=>{const e=await t.env.data.promptSettings.get(t.var.tenant_id);return e?t.json(e):t.json(Ss.parse({}))}).openapi(o.createRoute({tags:["prompts"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Ss.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Prompts settings"}}}),async t=>{const e=t.req.valid("json"),n=await t.env.data.promptSettings.get(t.var.tenant_id);return Object.assign(n,e),await t.env.data.promptSettings.set(t.var.tenant_id,n),t.json(n)});let Pg=!1;function jp(t){t.use(async(e,n)=>(Pg||(t.openAPIRegistry.registerComponent("securitySchemes","Bearer",{type:"oauth2",scheme:"bearer",flows:{implicit:{authorizationUrl:`${e.env.AUTH_URL}/authorize`,scopes:{openid:"Basic user information",email:"User email",profile:"User profile information"}}}}),Pg=!0),await n()))}var nk=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return e(n)}catch{return n}})}},rk=decodeURIComponent,ik=/^[\w!#$%&'*.^`|~+-]+$/,ok=/^[ !#-:<-[\]-~]*$/,sk=(t,e)=>{if(t.indexOf(e)===-1)return{};const n=t.trim().split(";"),r={};for(let i of n){i=i.trim();const s=i.indexOf("=");if(s===-1)continue;const a=i.substring(0,s).trim();if(e!==a||!ik.test(a))continue;let c=i.substring(s+1).trim();if(c.startsWith('"')&&c.endsWith('"')&&(c=c.slice(1,-1)),ok.test(c)){r[a]=c.indexOf("%")!==-1?nk(c,rk):c;break}}return r},ak=(t,e,n={})=>{let r=`${t}=${e}`;if(t.startsWith("__Secure-")&&!n.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(t.startsWith("__Host-")){if(!n.secure)throw new Error("__Host- Cookie must have Secure attributes");if(n.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(n.domain)throw new Error("__Host- Cookie must not have Domain attributes")}if(n&&typeof n.maxAge=="number"&&n.maxAge>=0){if(n.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");r+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!=="host"&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+="; HttpOnly"),n.secure&&(r+="; Secure"),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(r+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw new Error("Partitioned Cookie must have Secure attributes");r+="; Partitioned"}return r},xl=(t,e,n)=>(e=encodeURIComponent(e),ak(t,e,n)),ck=(t,e,n)=>{const r=t.req.raw.headers.get("Cookie");{if(!r)return;let i=e;return sk(r,i)[i]}},lk=(t,e,n)=>{let r;return n?.prefix==="secure"?r=xl("__Secure-"+t,e,{path:"/",...n,secure:!0}):n?.prefix==="host"?r=xl("__Host-"+t,e,{...n,path:"/",secure:!0,domain:void 0}):r=xl(t,e,{path:"/",...n}),r},Og=(t,e,n,r)=>{const i=lk(e,n,r);t.header("Set-Cookie",i,{append:!0})},v1=t=>$1(t.replace(/_|-/g,e=>({_:"/","-":"+"})[e]??e)),$1=t=>{const e=atob(t),n=new Uint8Array(new ArrayBuffer(e.length)),r=e.length/2;for(let i=0,s=e.length-1;i<=r;i++,s--)n[i]=e.charCodeAt(i),n[s]=e.charCodeAt(s);return n},k1=(t=>(t.HS256="HS256",t.HS384="HS384",t.HS512="HS512",t.RS256="RS256",t.RS384="RS384",t.RS512="RS512",t.PS256="PS256",t.PS384="PS384",t.PS512="PS512",t.ES256="ES256",t.ES384="ES384",t.ES512="ES512",t.EdDSA="EdDSA",t))(k1||{}),dk=class extends Error{constructor(t){super(`${t} is not an implemented algorithm`),this.name="JwtAlgorithmNotImplemented"}},x1=class extends Error{constructor(t){super(`invalid JWT token: ${t}`),this.name="JwtTokenInvalid"}},uk=class extends Error{constructor(t){super(`token (${t}) is being used before it's valid`),this.name="JwtTokenNotBefore"}},pk=class extends Error{constructor(t){super(`token (${t}) expired`),this.name="JwtTokenExpired"}},fk=class extends Error{constructor(t,e){super(`Invalid "iat" claim, must be a valid number lower than "${t}" (iat: "${e}")`),this.name="JwtTokenIssuedAt"}},Sl=class extends Error{constructor(t,e){super(`expected issuer "${t}", got ${e?`"${e}"`:"none"} `),this.name="JwtTokenIssuer"}},hk=class extends Error{constructor(t){super(`jwt header is invalid: ${JSON.stringify(t)}`),this.name="JwtHeaderInvalid"}},gk=class extends Error{constructor(t){super(`token(${t}) signature mismatched`),this.name="JwtTokenSignatureMismatched"}},mk=class extends Error{constructor(t){super(`required "aud" in jwt payload: ${JSON.stringify(t)}`),this.name="JwtPayloadRequiresAud"}},_k=class extends Error{constructor(t,e){super(`expected audience "${Array.isArray(t)?t.join(", "):t}", got "${e}"`),this.name="JwtTokenAudience"}},Ma=(t=>(t.Encrypt="encrypt",t.Decrypt="decrypt",t.Sign="sign",t.Verify="verify",t.DeriveKey="deriveKey",t.DeriveBits="deriveBits",t.WrapKey="wrapKey",t.UnwrapKey="unwrapKey",t))(Ma||{}),S1=new TextEncoder,yk=new TextDecoder;async function wk(t,e,n,r){const i=vk(e),s=await bk(t,i);return await crypto.subtle.verify(i,s,n,r)}function Tg(t){return $1(t.replace(/-+(BEGIN|END).*/g,"").replace(/\s/g,""))}async function bk(t,e){if(!crypto.subtle||!crypto.subtle.importKey)throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.");if($k(t)){if(t.type==="public"||t.type==="secret")return t;t=await Rg(t)}if(typeof t=="string"&&t.includes("PRIVATE")){const r=await crypto.subtle.importKey("pkcs8",Tg(t),e,!0,[Ma.Sign]);t=await Rg(r)}const n=[Ma.Verify];return typeof t=="object"?await crypto.subtle.importKey("jwk",t,e,!1,n):t.includes("PUBLIC")?await crypto.subtle.importKey("spki",Tg(t),e,!1,n):await crypto.subtle.importKey("raw",S1.encode(t),e,!1,n)}async function Rg(t){if(t.type!=="private")throw new Error(`unexpected key type: ${t.type}`);if(!t.extractable)throw new Error("unexpected private key is unextractable");const e=await crypto.subtle.exportKey("jwk",t),{kty:n}=e,{alg:r,e:i,n:s}=e,{crv:a,x:c,y:l}=e;return{kty:n,alg:r,e:i,n:s,crv:a,x:c,y:l,key_ops:[Ma.Verify]}}function vk(t){switch(t){case"HS256":return{name:"HMAC",hash:{name:"SHA-256"}};case"HS384":return{name:"HMAC",hash:{name:"SHA-384"}};case"HS512":return{name:"HMAC",hash:{name:"SHA-512"}};case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"RS384":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case"RS512":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case"PS256":return{name:"RSA-PSS",hash:{name:"SHA-256"},saltLength:32};case"PS384":return{name:"RSA-PSS",hash:{name:"SHA-384"},saltLength:48};case"PS512":return{name:"RSA-PSS",hash:{name:"SHA-512"},saltLength:64};case"ES256":return{name:"ECDSA",hash:{name:"SHA-256"},namedCurve:"P-256"};case"ES384":return{name:"ECDSA",hash:{name:"SHA-384"},namedCurve:"P-384"};case"ES512":return{name:"ECDSA",hash:{name:"SHA-512"},namedCurve:"P-521"};case"EdDSA":return{name:"Ed25519",namedCurve:"Ed25519"};default:throw new dk(t)}}function $k(t){return Xm()==="node"&&crypto.webcrypto?t instanceof crypto.webcrypto.CryptoKey:t instanceof CryptoKey}var Bg=t=>JSON.parse(yk.decode(v1(t)));function kk(t){if(typeof t=="object"&&t!==null){const e=t;return"alg"in e&&Object.values(k1).includes(e.alg)&&(!("typ"in e)||e.typ==="JWT")}return!1}var xk=async(t,e,n)=>{const{alg:r="HS256",iss:i,nbf:s=!0,exp:a=!0,iat:c=!0,aud:l}=typeof n=="string"?{alg:n}:n||{},d=t.split(".");if(d.length!==3)throw new x1(t);const{header:u,payload:f}=z1(t);if(!kk(u))throw new hk(u);const g=Date.now()/1e3|0;if(s&&f.nbf&&f.nbf>g)throw new uk(t);if(a&&f.exp&&f.exp<=g)throw new pk(t);if(c&&f.iat&&g<f.iat)throw new fk(g,f.iat);if(i){if(!f.iss)throw new Sl(i,null);if(typeof i=="string"&&f.iss!==i)throw new Sl(i,f.iss);if(i instanceof RegExp&&!i.test(f.iss))throw new Sl(i,f.iss)}if(l){if(!f.aud)throw new mk(f);if(!(Array.isArray(f.aud)?f.aud:[f.aud]).some(N=>l instanceof RegExp?l.test(N):typeof l=="string"?N===l:Array.isArray(l)&&l.includes(N)))throw new _k(l,f.aud)}const _=t.substring(0,t.lastIndexOf("."));if(!await wk(e,r,v1(d[2]),S1.encode(_)))throw new gk(t);return f},z1=t=>{try{const[e,n]=t.split("."),r=Bg(e),i=Bg(n);return{header:r,payload:i}}catch{throw new x1(t)}},A1={verify:xk,decode:z1},Sk=A1.verify,zk=A1.decode;async function pu(t){const{signingKeys:e}=await t.keys.list({q:"type:jwt_signing"});return await Promise.all(e.map(async r=>{const s=await new Wc(r.cert).publicKey.export(),a=await crypto.subtle.exportKey("jwk",s);return Nu.parse({...a,kid:r.kid})}))}o.z.object({alg:o.z.literal("RS256"),kty:o.z.literal("RSA"),use:o.z.literal("sig"),n:o.z.string(),e:o.z.string(),kid:o.z.string(),x5t:o.z.string(),x5c:o.z.array(o.z.string())});async function Ak(t){if(t.JWKS_URL&&t.JWKS_SERVICE){const e=await t.JWKS_SERVICE.fetch(t.JWKS_URL);return e.ok?(await e.json()).keys:(console.warn(`JWKS fetch failed with status ${e.status}, falling back to database`),await pu(t.data))}return await pu(t.data)}async function Ek(t,e){try{const{header:n}=zk(e),i=(await Ak(t.env)).find(c=>c.kid===n.kid);if(!i)throw new B(401,{message:"No matching kid found"});const s=await crypto.subtle.importKey("jwk",i,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return await Sk(e,s,"RS256")}catch(n){throw n instanceof v?n:new B(403,{message:"Invalid JWT signature"})}}function Ck(t){return t.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function Nk(t,e){return e.startsWith(t)?e:t+e}function Pp(t){return async(e,n)=>{const r=e.req.matchedRoutes.find(c=>c.method.toUpperCase()===e.req.method&&c.path!=="/*");if(!r)return await n();const i=Ck(r.path),s="basePath"in r&&typeof r.basePath=="string"?r.basePath:"",a=t.openAPIRegistry.definitions.find(c=>"route"in c&&Nk(s,c.route.path)===i&&c.route.method.toUpperCase()===e.req.method.toUpperCase());if(a&&"route"in a){const c=a.route.security?.[0]?.Bearer;if(!c?.length)return await n();const l=e.req.header("authorization")||"",[d,u]=l.split(" ");if(d?.toLowerCase()!=="bearer"||!u)throw new B(401,{message:"Missing bearer token"});try{const f=await Ek(e,u);e.set("user_id",f.sub),e.set("user",f),!e.var.tenant_id&&f.tenant_id&&e.set("tenant_id",f.tenant_id);const g=f.permissions||[],_=f.scope?.split(" ")||[];if(c.length&&!(c.some(w=>g.includes(w))||c.some(w=>_.includes(w))))throw new B(403,{message:"Unauthorized"})}catch(f){throw f instanceof v?f:new B(403,{message:"Invalid token"})}}return await n()}}const Ik=new o.OpenAPIHono().openapi(o.createRoute({tags:["emails"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:zs}},description:"Email provider"}}}),async t=>{const e=await t.env.data.emailProviders.get(t.var.tenant_id);if(!e)throw new v(404,{message:"Email provider not found"});return t.json(e)}).openapi(o.createRoute({tags:["emails"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(zs.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const e=t.req.valid("json");return await t.env.data.emailProviders.create(t.var.tenant_id,e),t.text("OK",{status:201})}).openapi(o.createRoute({tags:["emails"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(zs.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const e=t.req.valid("json");return await t.env.data.emailProviders.update(t.var.tenant_id,e),t.text("OK")}),jk=new o.OpenAPIHono().openapi(o.createRoute({tags:["sessions"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ja}},description:"A session"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.sessions.get(t.var.tenant_id,e);if(!n)throw new v(404);return t.json(n)}).openapi(o.createRoute({tags:["sessions"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param");if(!await t.env.data.sessions.remove(t.var.tenant_id,e))throw new v(404,{message:"Session not found"});return t.text("OK")}).openapi(o.createRoute({tags:["sessions"],method:"post",path:"/{id}/revoke",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{202:{description:"Sesssion deletion status"}}}),async t=>{const{id:e}=t.req.valid("param");if(!await t.env.data.sessions.update(t.var.tenant_id,e,{revoked_at:new Date().toDateString()}))throw new v(404,{message:"Session not found"});return t.text("Session deletion request accepted.",{status:202})}),Pk=new o.OpenAPIHono().openapi(o.createRoute({tags:["refresh_tokens"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:ju}},description:"A session"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.refreshTokens.get(t.var.tenant_id,e);if(!n)throw new v(404);return t.json(n)}).openapi(o.createRoute({tags:["refresh_tokens"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param");if(!await t.env.data.refreshTokens.remove(t.var.tenant_id,e))throw new v(404,{message:"Session not found"});return t.text("OK")}),Ok=new o.OpenAPIHono().openapi(o.createRoute({tags:["custom-domains"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(xn)}},description:"List of custom domains"}}}),async t=>{const e=await t.env.data.customDomains.list(t.var.tenant_id);return t.json(e)}).openapi(o.createRoute({tags:["custom-domains"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:xn}},description:"A customDomain"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.customDomains.get(t.var.tenant_id,e);if(!n)throw new v(404);return t.json(n)}).openapi(o.createRoute({tags:["custom-domains"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param");if(!await t.env.data.customDomains.remove(t.var.tenant_id,e))throw new v(404,{message:"Custom domain not found"});return t.text("OK")}).openapi(o.createRoute({tags:["custom-domains"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(xn.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:xn}},description:"The updated custom domain"}}}),async t=>{const{id:e}=t.req.valid("param"),n=t.req.valid("json");if(!await t.env.data.customDomains.update(t.var.tenant_id,e,n))throw new v(404);const i=await t.env.data.customDomains.get(t.var.tenant_id,e);if(!i)throw new v(404);return t.json(i)}).openapi(o.createRoute({tags:["custom-domains"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Eu.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:xn}},description:"The created custom domain"}}}),async t=>{const e=t.req.valid("json"),n=await t.env.data.customDomains.create(t.var.tenant_id,e);return t.json(n,{status:201})}).openapi(o.createRoute({tags:["custom-domains"],method:"post",path:"/{id}/verify",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:xn}},description:"The custom domain"}}}),async()=>{throw new v(501,{message:"Not implemented"})});function Xc(t,e){const n={};for(const[r,i]of Object.entries(e)){if(i==null)continue;const s={};for(const[a,c]of Object.entries(i))typeof c=="function"?s[a]=async(...l)=>{const d=performance.now();try{const u=await c(...l),g=performance.now()-d,_=t.res.headers.get("Server-Timing")||"",w=_?`${_}, ${r}-${a};dur=${g.toFixed(2)}`:`${r}-${a};dur=${g.toFixed(2)}`;return t.res.headers.set("Server-Timing",w),u}catch(u){const g=performance.now()-d,_=t.res.headers.get("Server-Timing")||"",w=_?`${_}, ${r}-${a}-error;dur=${g.toFixed(2)}`:`${r}-${a}-error;dur=${g.toFixed(2)}`;throw t.res.headers.set("Server-Timing",w),u}}:s[a]=c;n[r]=s}return n}async function Zc(t,e){const n=t.req.header("x-forwarded-host");if(n){const i=await t.env.data.customDomains.getByDomain(n);if(i)return t.set("tenant_id",i.tenant_id),t.set("custom_domain",n),t.set("host",n),await e()}const r=t.req.header("host");if(r){t.set("host",r);const i=r.split(".");if(i.length>1&&typeof i[0]=="string"){const s=i[0];await t.env.data.tenants.get(s)&&t.set("tenant_id",s)}}else t.set("host",new URL(ic(t.env)).host);if(!t.var.tenant_id){const i=t.req.header("tenant-id");i&&t.set("tenant_id",i)}return await e()}const Tk=o.z.object({name:o.z.string(),version:o.z.string(),env:o.z.object({node:o.z.string().optional()}).optional()});function Rk(t){if(t)try{let e=t;try{e=atob(t)}catch{}try{const n=JSON.parse(e);return Tk.parse(n)}catch{}}catch{return}}const Yc=async(t,e)=>{const n=t.req.query("auth0Client")?.slice(0,255),i=(t.req.header("x-forwarded-host")&&t.req.header("x-forwarded-for")?t.req.header("x-forwarded-for")?.split(",")[0]?.trim():t.req.header("cf-connecting-ip")||t.req.header("x-real-ip"))?.slice(0,45),s=t.req.header("user-agent")?.slice(0,512),a=t.req.header("cf-ipcountry")?.slice(0,2),c=n?Rk(n):void 0;c&&t.set("auth0_client",c),i&&t.set("ip",i),s&&t.set("useragent",s),a&&t.set("countryCode",a),await e()};function Bk(t,e,n,r){try{const i=`${t}:${e}:${JSON.stringify(n)}`;return r?`${r}:${i}`:i}catch{const s=`${t}:${e}:${Date.now()}-${Math.random()}`;return r?`${r}:${s}`:s}}function Qc(t,e){const{cache:n,defaultTtl:r,customTtls:i={},excludeMethods:s=[],cacheEntities:a=[],keyPrefix:c}=e,l=new Set(s),d=a.length===0,u=new Set(a),f={};for(const[g,_]of Object.entries(t)){if(_==null)continue;const w=d||u.has(g),k={};for(const[z,N]of Object.entries(_))if(typeof N=="function"){if(!w){k[z]=N;continue}const I=`${g}:${z}`;if(l.has(I)){k[z]=N;continue}const S=i[I]??r,E=["create","update","remove","delete","set","used"].includes(z);k[z]=async(...P)=>{if(E)return await N.apply(_,P);const G=Bk(g,z,P,c),Z=await n.get(G);if(Z!==null)if(Z&&typeof Z=="object"&&"isCachedNull"in Z){const M=Z;return M.isCachedNull?null:M.value}else return Z;const W=await N.apply(_,P);if(S>=0)if(W!==null)await n.set(G,W,S);else{const M={value:null,isCachedNull:!0};await n.set(G,M,S)}return W}}else k[z]=N;f[g]=k}return f}class Lk{constructor(e={}){this.config=e;const n=e.cleanupIntervalMs;n&&n>0&&(this.cleanupTimer=setInterval(()=>{this.cleanupExpired()},n))}cache=new Map;accessOrder=new Map;accessCounter=0;cleanupTimer;async get(e){const n=this.cache.get(e);return n?n.expiresAt&&n.expiresAt<new Date?(this.cache.delete(e),this.accessOrder.delete(e),null):(this.accessOrder.set(e,++this.accessCounter),n.value):null}async set(e,n,r){let i;const s=r??this.config.defaultTtlSeconds,a=s!==void 0,c=a?Math.max(0,s):0;a&&(i=new Date(Date.now()+(c>0?c*1e3:-1))),this.config.maxEntries&&this.cache.size>=this.config.maxEntries&&!this.cache.has(e)&&this.evictLeastRecentlyUsed();const l={value:n,expiresAt:i};this.cache.set(e,l),this.accessOrder.set(e,++this.accessCounter)}async delete(e){const n=this.cache.has(e);return this.cache.delete(e),this.accessOrder.delete(e),n}async clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}getStats(){return{size:this.cache.size,maxEntries:this.config.maxEntries,defaultTtlSeconds:this.config.defaultTtlSeconds}}cleanupExpired(){const e=new Date,n=[];for(const[r,i]of this.cache.entries())i.expiresAt&&i.expiresAt<e&&n.push(r);for(const r of n)this.cache.delete(r),this.accessOrder.delete(r)}evictLeastRecentlyUsed(){let e=null,n=1/0;for(const[r,i]of this.accessOrder.entries())i<n&&(n=i,e=r);e&&(this.cache.delete(e),this.accessOrder.delete(e))}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0)}}function ds(t={}){return new Lk(t)}const Uk=it.extend({forms:o.z.array(Br)}),Dk=new o.OpenAPIHono().openapi(o.createRoute({tags:["forms"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Br),Uk])}},description:"List of forms"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i=!1,sort:s,q:a}=t.req.valid("query"),c=await t.env.data.forms.list(e,{page:n,per_page:r,include_totals:i,sort:Ke(s),q:a});return i?t.json(c):t.json(c.forms)}).openapi(o.createRoute({tags:["forms"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Br}},description:"A form"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.forms.get(e,n);if(!r)throw new v(404);return t.json(r)}).openapi(o.createRoute({tags:["forms"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.forms.remove(e,n))throw new v(404,{message:"Form not found"});return t.text("OK")}).openapi(o.createRoute({tags:["forms"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(Gs.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Br}},description:"The updated form"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.forms.update(e,n,r))throw new v(404,{message:"Form not found"});const s=await t.env.data.forms.get(e,n);if(!s)throw new v(404,{message:"Form not found"});return t.json(s)}).openapi(o.createRoute({tags:["forms"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Gs.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Br}},description:"A form"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.forms.create(e,n);return t.json(r,{status:201})}),Mk=it.extend({roles:o.z.array(Yn)}),qk=new o.OpenAPIHono().openapi(o.createRoute({tags:["roles"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Yn),Mk])}},description:"List of roles"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),a=await t.env.data.roles.list(t.var.tenant_id,{page:e,per_page:n,include_totals:r,sort:Ke(i),q:s});return r?t.json(a):t.json(a.roles)}).openapi(o.createRoute({tags:["roles"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Yn}},description:"A role"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.roles.get(t.var.tenant_id,e);if(!n)throw new v(404);return t.json(n)}).openapi(o.createRoute({tags:["roles"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:Xs}}}},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Yn}},description:"Role created"}}}),async t=>{const e=t.req.valid("json"),n=await t.env.data.roles.create(t.var.tenant_id,e);return t.json(n,{status:201})}).openapi(o.createRoute({tags:["roles"],method:"patch",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:Xs.partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Yn}},description:"Updated role"}}}),async t=>{const{id:e}=t.req.valid("param"),n=t.req.valid("json");if(!await t.env.data.roles.update(t.var.tenant_id,e,n))throw new v(404);const i=await t.env.data.roles.get(t.var.tenant_id,e);return t.json(i)}).openapi(o.createRoute({tags:["roles"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param");if(!await t.env.data.roles.remove(t.var.tenant_id,e))throw new v(404);return t.text("OK")}).openapi(o.createRoute({tags:["roles"],method:"get",path:"/{id}/permissions",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),query:Te},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Im}},description:"Role permissions"}}}),async t=>{const{id:e}=t.req.valid("param"),{page:n,per_page:r,sort:i,q:s}=t.req.valid("query");if(!await t.env.data.roles.get(t.var.tenant_id,e))throw new v(404,{message:"Role not found"});const c=await t.env.data.rolePermissions.list(t.var.tenant_id,e,{page:n,per_page:r,include_totals:!1,sort:Ke(i),q:s});return t.json(c)}).openapi(o.createRoute({tags:["roles"],method:"post",path:"/{id}/permissions",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),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:["auth:write"]}],responses:{201:{description:"Permissions assigned to role"}}}),async t=>{const{id:e}=t.req.valid("param"),{permissions:n}=t.req.valid("json");if(!await t.env.data.roles.get(t.var.tenant_id,e))throw new v(404,{message:"Role not found"});if(!await t.env.data.rolePermissions.assign(t.var.tenant_id,e,n.map(s=>({role_id:e,resource_server_identifier:s.resource_server_identifier,permission_name:s.permission_name}))))throw new v(500,{message:"Failed to assign permissions to role"});return t.json({message:"Permissions assigned successfully"},{status:201})}).openapi(o.createRoute({tags:["roles"],method:"delete",path:"/{id}/permissions",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),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:["auth:write"]}],responses:{200:{description:"Permissions removed from role"}}}),async t=>{const{id:e}=t.req.valid("param"),{permissions:n}=t.req.valid("json");if(!await t.env.data.roles.get(t.var.tenant_id,e))throw new v(404,{message:"Role not found"});if(!await t.env.data.rolePermissions.remove(t.var.tenant_id,e,n))throw new v(500,{message:"Failed to remove permissions from role"});return t.json({message:"Permissions removed successfully"})}),Fk=it.extend({resource_servers:o.z.array(Zn)}),Hk=new o.OpenAPIHono().openapi(o.createRoute({tags:["resource-servers"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Zn),Fk])}},description:"List of resource servers"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i=!1,sort:s,q:a}=t.req.valid("query"),c=await t.env.data.resourceServers.list(e,{page:n,per_page:r,include_totals:i,sort:Ke(s),q:a});return i?t.json(c):t.json(c.resource_servers)}).openapi(o.createRoute({tags:["resource-servers"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Zn}},description:"A resource server"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.resourceServers.get(e,n);if(!r)throw new v(404);return t.json(r)}).openapi(o.createRoute({tags:["resource-servers"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.resourceServers.remove(e,n))throw new v(404,{message:"Resource server not found"});return t.text("OK")}).openapi(o.createRoute({tags:["resource-servers"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(Js.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Zn}},description:"The updated resource server"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.resourceServers.update(e,n,r))throw new v(404,{message:"Resource server not found"});const s=await t.env.data.resourceServers.get(e,n);if(!s)throw new v(404,{message:"Resource server not found"});return t.json(s)}).openapi(o.createRoute({tags:["resource-servers"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Js.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Zn}},description:"A resource server"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.resourceServers.create(e,n);return t.json(r,{status:201})}),Vk=o.z.object({per_page:o.z.string().min(1).optional().default("50").transform(t=>parseInt(t,10)).openapi({description:"Number of results per page. Defaults to 50."}),page:o.z.string().min(0).optional().default("0").transform(t=>parseInt(t,10)).openapi({description:"Page index of the results to return. First page is 0."}),include_totals:o.z.string().optional().default("false").transform(t=>t==="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().min(1).optional().transform(t=>t?parseInt(t,10):void 0).openapi({description:"Number of results per page. Defaults to 50."}),audience:o.z.string().optional().openapi({description:"Optional filter on audience."}),client_id:o.z.string().optional().openapi({description:"Optional filter on client_id."}),allow_any_organization:o.z.string().optional().transform(t=>t==="true"?!0:t==="false"?!1:void 0).openapi({description:"Optional filter on allow_any_organization."}),subject_type:o.z.enum(["client","user"]).optional().openapi({description:"EA 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."})}),Kk=it.extend({client_grants:o.z.array(Xn)}),Gk=new o.OpenAPIHono().openapi(o.createRoute({tags:["client-grants"],method:"get",path:"/",request:{query:Vk,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Xn),Kk])}},description:"List of client grants"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i=!1,from:s,take:a,audience:c,client_id:l,allow_any_organization:d,subject_type:u}=t.req.valid("query"),f=[];l&&f.push(`client_id:"${l}"`),c&&f.push(`audience:"${c}"`),d!==void 0&&f.push(`allow_any_organization:${d}`),u&&f.push(`subject_type:"${u}"`),s&&f.push(`id:>${s}`);const g=f.length>0?f.join(" AND "):void 0,_=a??r,w=await t.env.data.clientGrants.list(e,{page:n,per_page:_,include_totals:i,q:g});return i?t.json(w):t.json(w.client_grants)}).openapi(o.createRoute({tags:["client-grants"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Xn}},description:"A client grant"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.clientGrants.get(e,n);if(!r)throw new v(404,{message:"Client grant not found"});return t.json(r)}).openapi(o.createRoute({tags:["client-grants"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.clientGrants.remove(e,n))throw new v(404,{message:"Client grant not found"});return t.text("OK")}).openapi(o.createRoute({tags:["client-grants"],method:"patch",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Vs.shape).partial()}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Xn}},description:"The updated client grant"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.clientGrants.get(e,n))throw new v(404,{message:"Client grant not found"});if(!await t.env.data.clientGrants.update(e,n,r))throw new v(500,{message:"Failed to update client grant"});const a=await t.env.data.clientGrants.get(e,n);if(!a)throw new v(404,{message:"Client grant not found"});return t.json(a)}).openapi(o.createRoute({tags:["client-grants"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Vs.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Xn}},description:"A client grant"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.clientGrants.create(e,n);return t.json(r,{status:201})}),Wk=o.z.object({page:o.z.string().optional().default("0").transform(t=>parseInt(t,10)).openapi({description:"Page index of the results to return. First page is 0."}),per_page:o.z.string().optional().default("50").transform(t=>parseInt(t,10)).openapi({description:"Number of results per page. Defaults to 50."}),include_totals:o.z.string().optional().default("false").transform(t=>t==="true").openapi({description:"When true, return results inside an object that also contains the start and limit. When false (default), a direct array of results is returned."}),fields:o.z.string().optional().openapi({description:"Comma-separated list of fields to include or exclude (based on value provided for include_fields) in the result. Leave empty to retrieve all fields."}),include_fields:o.z.string().optional().default("true").transform(t=>t==="true").openapi({description:"Whether specified fields are to be included (true) or excluded (false). Defaults to true."}),sort:o.z.string().optional().default("created_at:-1").openapi({description:"Field to sort by. Use field:order where order is 1 for ascending and -1 for descending. Defaults to created_at:-1."})}),Jk=o.z.object({invitations:o.z.array(io),start:o.z.number(),limit:o.z.number(),length:o.z.number()}),Xk=Cu.omit({organization_id:!0,invitation_url:!0}),Zk=it.extend({organizations:o.z.array(zn)}),Op=o.z.object({user_id:o.z.string().openapi({description:"ID of this user"}),email:o.z.string().email().optional().openapi({description:"Email address of this user",format:"email"}),roles:o.z.array(o.z.object({})).default([]).openapi({description:"Array of roles assigned to this user in the organization"})}),Yk=o.z.object({start:o.z.number().openapi({description:"Start index of the current page"}),limit:o.z.number().openapi({description:"Number of items per page"}),total:o.z.number().openapi({description:"Total number of members"}),members:o.z.array(Op).openapi({description:"Array of organization members"})}),Qk=o.z.object({next:o.z.string().optional().openapi({description:"Checkpoint ID to be used to retrieve the next set of results"}),members:o.z.array(Op).openapi({description:"Array of organization members"})}),e5=o.z.object({members:o.z.array(o.z.string()).openapi({description:"Array of user IDs to add to the organization"})}),t5=o.z.object({members:o.z.array(o.z.string()).openapi({description:"Array of user IDs to remove from the organization"})}),n5=new o.OpenAPIHono().openapi(o.createRoute({tags:["organizations"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([Zk,o.z.array(zn)])}},description:"List of organizations"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i,sort:s,q:a}=t.req.valid("query"),c=await t.env.data.organizations.list(e,{page:n,per_page:r,include_totals:i,sort:Ke(s),q:a});return i?t.json(c):t.json(c.organizations)}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:zn}},description:"An organization"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.organizations.get(e,n);if(!r)throw new v(404,{message:"Organization not found"});return t.json(r)}).openapi(o.createRoute({tags:["organizations"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Organization deleted successfully"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.organizations.remove(e,n))throw new v(404,{message:"Organization not found"});return t.text("OK")}).openapi(o.createRoute({tags:["organizations"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:Ys.partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:zn}},description:"The updated organization"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.organizations.update(e,n,r))throw new v(404,{message:"Organization not found"});const s=await t.env.data.organizations.get(e,n);if(!s)throw new v(404,{message:"Organization not found"});return t.json(s)}).openapi(o.createRoute({tags:["organizations"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:Ys}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:zn}},description:"The created organization"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r={...n,id:n.id||V$()},i=await t.env.data.organizations.create(e,r);return t.json(i,{status:201})}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/members",request:{params:o.z.object({id:o.z.string()}),query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Op),Yk,Qk])}},description:"List of organization members"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),{page:r,per_page:i,include_totals:s,sort:a}=t.req.valid("query");if(!await t.env.data.organizations.get(e,n))throw new v(404,{message:"Organization not found"});const l=await t.env.data.userOrganizations.list(e,{page:r,per_page:i,include_totals:s,sort:Ke(a),q:`organization_id:${n}`}),d=[];for(const u of l.userOrganizations){const f=await t.env.data.users.get(e,u.user_id);f&&d.push({user_id:f.user_id,email:f.email||void 0,roles:[]})}return s?t.json({start:l.start,limit:l.limit,total:l.length,members:d}):t.json(d)}).openapi(o.createRoute({tags:["organizations"],method:"post",path:"/{id}/members",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:e5}}}},security:[{Bearer:["auth:write"]}],responses:{204:{description:"Members added successfully"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),{members:r}=t.req.valid("json");if(!await t.env.data.organizations.get(e,n))throw new v(404,{message:"Organization not found"});for(const s of r)(await t.env.data.userOrganizations.list(e,{q:`user_id:${s}`,per_page:1})).userOrganizations.some(l=>l.organization_id===n)||await t.env.data.userOrganizations.create(e,{user_id:s,organization_id:n});return new Response(null,{status:204})}).openapi(o.createRoute({tags:["organizations"],method:"delete",path:"/{id}/members",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:t5}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Members removed successfully"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),{members:r}=t.req.valid("json");for(const i of r){const a=(await t.env.data.userOrganizations.list(e,{q:`user_id:${i}`,per_page:100})).userOrganizations.find(c=>c.organization_id===n);a&&await t.env.data.userOrganizations.remove(e,a.id)}return t.json({message:"Members removed successfully"})}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/members/{user_id}/roles",request:{params:o.z.object({id:o.z.string(),user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),query:Te},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Zs}},description:"User roles in organization"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n,user_id:r}=t.req.valid("param");if(!await t.env.data.organizations.get(e,n))throw new v(404,{message:"Organization not found"});if(!await t.env.data.users.get(e,r))throw new v(404,{message:"User not found"});const a=await t.env.data.userRoles.list(e,r,void 0,n);return t.json(a)}).openapi(o.createRoute({tags:["organizations"],method:"post",path:"/{id}/members/{user_id}/roles",request:{params:o.z.object({id:o.z.string(),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()).openapi({description:"List of role IDs to associate with the user"})})}}}},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Roles assigned successfully"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n,user_id:r}=t.req.valid("param"),{roles:i}=t.req.valid("json");if(!await t.env.data.organizations.get(e,n))throw new v(404,{message:"Organization not found"});if(!await t.env.data.users.get(e,r))throw new v(404,{message:"User not found"});for(const c of i){if(!await t.env.data.roles.get(e,c))throw new v(400,{message:`Role ${c} not found`});if(!await t.env.data.userRoles.create(e,r,c,n))throw new v(500,{message:`Failed to assign role ${c} to user`})}return t.json({message:"Roles assigned successfully"},{status:201})}).openapi(o.createRoute({tags:["organizations"],method:"delete",path:"/{id}/members/{user_id}/roles",request:{params:o.z.object({id:o.z.string(),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()).openapi({description:"List of role IDs to remove from the user"})})}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Roles removed successfully"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n,user_id:r}=t.req.valid("param"),{roles:i}=t.req.valid("json");if(!await t.env.data.organizations.get(e,n))throw new v(404,{message:"Organization not found"});if(!await t.env.data.users.get(e,r))throw new v(404,{message:"User not found"});for(const c of i)if(!await t.env.data.userRoles.remove(e,r,c,n))throw new v(500,{message:`Failed to remove role ${c} from user`});return t.json({message:"Roles removed successfully"})}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/roles",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),query:Te},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Zs}},description:"List of roles available in organization"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),{page:r,per_page:i,sort:s,q:a}=t.req.valid("query");if(!await t.env.data.organizations.get(e,n))throw new v(404,{message:"Organization not found"});const l=await t.env.data.roles.list(e,{page:r,per_page:i,sort:Ke(s),q:a});return t.json(l.roles)}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/invitations",request:{params:o.z.object({id:o.z.string().openapi({description:"Organization ID",param:{name:"id",in:"path"}})}),query:Wk,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(io),Jk])}},description:"List of organization invitations"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),{page:r,per_page:i,include_totals:s,fields:a,include_fields:c,sort:l}=t.req.valid("query");if(!await t.env.data.organizations.get(e,n))throw new v(404,{message:"Organization not found"});let f=(await t.env.data.invites.list(e,{page:r,per_page:i})).invites.filter(g=>g.organization_id===n);if(l){const g=Ke(l);if(g){const{sort_by:_,sort_order:w}=g;f.sort((k,z)=>{const N=k[_],I=z[_];if(N===void 0||I===void 0||N===I)return 0;const S=N<I?-1:1;return w==="asc"?S:-S})}}if(a){const g=a.split(",").map(_=>_.trim());f=f.map(_=>{const w={};for(const k of Object.keys(_))(c?g.includes(k):!g.includes(k))&&(w[k]=_[k]);return w})}return s?t.json({invitations:f,start:r*i,limit:i,length:f.length}):t.json(f)}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/invitations/{invitation_id}",request:{params:o.z.object({id:o.z.string().openapi({description:"Organization ID",param:{name:"id",in:"path"}}),invitation_id:o.z.string().openapi({description:"Invitation ID",param:{name:"invitation_id",in:"path"}})}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:io}},description:"An invitation"},404:{description:"Invitation not found"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n,invitation_id:r}=t.req.valid("param"),i=await t.env.data.invites.get(e,r);if(!i||i.organization_id!==n)throw new v(404,{message:"Invitation not found"});return t.json(i)}).openapi(o.createRoute({tags:["organizations"],method:"post",path:"/{id}/invitations",request:{params:o.z.object({id:o.z.string().openapi({description:"Organization ID",param:{name:"id",in:"path"}})}),body:{content:{"application/json":{schema:Xk}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:io}},description:"The created invitation"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.organizations.get(e,n))throw new v(404,{message:"Organization not found"});const a=`https://invite.placeholder/${W$()}`,c={...r,organization_id:n,invitation_url:a},l=await t.env.data.invites.create(e,c);return t.json(l,{status:201})}).openapi(o.createRoute({tags:["organizations"],method:"delete",path:"/{id}/invitations/{invitation_id}",request:{params:o.z.object({id:o.z.string().openapi({description:"Organization ID",param:{name:"id",in:"path"}}),invitation_id:o.z.string().openapi({description:"Invitation ID",param:{name:"invitation_id",in:"path"}})}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{204:{description:"Invitation deleted successfully"},404:{description:"Invitation not found"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n,invitation_id:r}=t.req.valid("param"),i=await t.env.data.invites.get(e,r);if(!i||i.organization_id!==n)throw new v(404,{message:"Invitation not found"});if(!await t.env.data.invites.remove(e,r))throw new v(404,{message:"Invitation not found"});return t.body(null,{status:204})});function r5(t){const e=new o.OpenAPIHono;e.use(M0({origin:r=>r&&t.allowedOrigins?.includes(r)?r:"",allowHeaders:["Tenant-Id","Content-Type","Content-Range","Auth0-Client","Authorization","Range","Upgrade-Insecure-Requests"],allowMethods:["POST","PUT","GET","DELETE","PATCH","OPTIONS"],exposeHeaders:["Content-Length","Content-Range"],maxAge:600,credentials:!0})),jp(e),e.use(async(r,i)=>{const s=qo(r,t.dataAdapter),a=ds({defaultTtlSeconds:0,maxEntries:100,cleanupIntervalMs:0}),c=Qc(s,{defaultTtl:0,cacheEntities:["tenants","connections","clients","legacyClients","branding","themes","promptSettings","forms"],cache:a});return r.env.data=Xc(r,c),i()}),e.use(Yc).use(Zc).use(Pp(e));const n=e.route("/branding",Ab).route("/custom-domains",Ok).route("/email/providers",Ik).route("/users",P3).route("/keys",O$).route("/users-by-email",T$).route("/clients",L$).route("/client-grants",Gk).route("/tenants",D$).route("/logs",q$).route("/hooks",X$).route("/connections",ek).route("/prompts",tk).route("/sessions",jk).route("/refresh_tokens",Pk).route("/forms",Dk).route("/roles",qk).route("/resource-servers",Hk).route("/organizations",n5);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Management API"},servers:[{url:"/api/v2",description:"API V2"}],security:[{oauth2:["openid","email","profile"]}]}),n}function i5(t,e){Object.keys(e).forEach(n=>{const r=e[n];r!=null&&r.length&&t.searchParams.set(n,r)})}function mn(t){if(t)return`${t.name}/${t.version}${t.env?.node?` (env: node/${t.env.node})`:""}`}async function zi(t,e){const n=await t.data.legacyClients.get(e);if(!n)throw new B(403,{message:"Client not found"});let r=n;if(t.DEFAULT_CLIENT_ID||t.DEFAULT_TENANT_ID){const i=t.DEFAULT_CLIENT_ID?await t.data.legacyClients.get(t.DEFAULT_CLIENT_ID):void 0,s=await t.data.connections.list(n.tenant.id),a=t.DEFAULT_TENANT_ID?await t.data.connections.list(t.DEFAULT_TENANT_ID):{connections:[]},c=s.connections.map(l=>{const d=a.connections?.find(f=>f.name===l.name);if(!d?.options)return l;const u=ht.parse({...d||{},...l});return u.options=Dr.parse({...d.options||{},...l.options}),u}).filter(l=>l);r={...n,web_origins:[...i?.web_origins||[],...n.web_origins||[]],allowed_logout_urls:[...i?.allowed_logout_urls||[],...n.allowed_logout_urls||[]],callbacks:[...i?.callbacks||[],...n.callbacks||[]],connections:c,tenant:{...i?.tenant||{},...n.tenant}}}return{...r,web_origins:[...r.web_origins||[],`${De(t)}login`],allowed_logout_urls:[...r.allowed_logout_urls||[],t.ISSUER],callbacks:[...r.callbacks||[],`${De(t)}info`]}}async function Lg(t,e,n,r){if(!r.state)throw new B(400,{message:"State not found"});const i=e.connections.find(l=>l.name===n);if(!i)throw t.set("client_id",e.client_id),await ie(t,e.tenant.id,{type:te.FAILED_LOGIN,description:"Connection not found"}),new B(403,{message:"Connection Not Found"});let s=await t.env.data.loginSessions.get(e.tenant.id,r.state);if(!s){const l=t.get("ip"),d=t.get("useragent"),u=t.get("auth0_client");s=await t.env.data.loginSessions.create(e.tenant.id,{expires_at:new Date(Date.now()+or*1e3).toISOString(),authParams:r,csrf_token:pe(),ip:l,useragent:d,auth0Client:mn(u)})}const c=await j_(t,i.strategy).getRedirect(t,i);return await t.env.data.codes.create(e.tenant.id,{login_id:s.id,code_id:c.code,code_type:"oauth2_state",connection_id:i.id,code_verifier:c.codeVerifier,expires_at:new Date(Date.now()+av*1e3).toISOString()}),new Response(null,{status:302,headers:{location:c.redirectUrl}})}async function Ug(t,{code:e,state:n}){const{env:r}=t,i=await r.data.codes.get(t.var.tenant_id||"",n,"oauth2_state");if(!i||!i.connection_id)throw new B(403,{message:"State not found"});const s=await r.data.loginSessions.get(t.var.tenant_id||"",i.login_id);if(!s)throw new B(403,{message:"Session not found"});if(s.authorization_url){const w=new URL(s.authorization_url).hostname,k=t.var.host||"";if(w!==k&&w){const z=new URL(`https://${w}/callback`);return z.searchParams.set("state",n),z.searchParams.set("code",e),new Response("Redirecting",{status:307,headers:{location:z.toString()}})}}const a=await zi(r,s.authParams.client_id);t.set("client_id",a.client_id),t.set("tenant_id",a.tenant.id);const c=a.connections.find(w=>w.id===i.connection_id);if(!c)throw await ie(t,a.tenant.id,{type:te.FAILED_LOGIN,description:"Connection not found"}),new B(403,{message:"Connection not found"});if(t.set("connection",c.name),!s.authParams.redirect_uri)throw await ie(t,a.tenant.id,{type:te.FAILED_LOGIN,description:"Redirect URI not defined"}),new B(403,{message:"Redirect URI not defined"});const d=await j_(t,c.strategy).validateAuthorizationCodeAndGetUser(t,c,e,i.code_verifier),{sub:u,...f}=d;t.set("user_id",u);const g=d.email?.toLocaleLowerCase()||`${c.name}.${u}@${new URL(t.env.ISSUER).hostname}`;t.set("username",g);const _=await nc(t,{client:a,username:g,provider:c.strategy,connection:c.name,userId:u,profileData:f,isSocial:!0,ip:t.var.ip});return Gt(t,{client:a,authParams:s.authParams,loginSession:s,user:_,authStrategy:{strategy:c.strategy,strategy_type:"social"}})}function Dg(t){return t===Ct.WEB_MESSAGE}async function $s(t,e,n,r,i,s){const a=await t.env.data.codes.get(t.var.tenant_id||"",e,"oauth2_state");if(!a)throw new v(400,{message:"State not found"});const c=await t.env.data.loginSessions.get(t.var.tenant_id,a.login_id);if(!c)throw new v(400,{message:"Login not found"});const{redirect_uri:l}=c.authParams;if(!l)throw new v(400,{message:"Redirect uri not found"});ie(t,t.var.tenant_id,{type:te.FAILED_LOGIN,description:`Failed connection login: ${i} ${n}, ${r}`});const d=new URL(l);return i5(d,{error:n,error_description:r,error_reason:s,error_code:i,state:c.authParams.state}),t.redirect(`${De(t.env)}login/identifier?state=${c.id}&error=${n}`)}const o5=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string(),code:o.z.string().optional(),scope:o.z.string().optional(),hd:o.z.string().optional(),error:o.z.string().optional(),error_description:o.z.string().optional(),error_code:o.z.string().optional(),error_reason:o.z.string().optional()})},responses:{302:{description:"Redirect to the client's redirect uri"},400:{description:"Bad Request",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}},500:{description:"Internal Server Error",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async t=>{const{state:e,code:n,error:r,error_description:i,error_code:s,error_reason:a}=t.req.valid("query");if(r)return $s(t,e,r,i,s,a);if(!n)throw new v(400,{message:"Code is required"});try{const c=await Ug(t,{code:n,state:e});if(!(c instanceof Response))throw new v(500,{message:"Internal server error"});return c}catch(c){if(c instanceof B&&c.status===400){const l=await t.env.data.codes.get(t.var.tenant_id||"",e,"oauth2_state");if(l){const d=await t.env.data.loginSessions.get(t.var.tenant_id,l.login_id);if(d&&Dg(d.authParams.response_mode)){let u="access_denied";try{u=JSON.parse(c.message).message||u}catch{u=c.message||u}return $s(t,e,"access_denied",u)}}}throw c}}).openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({state:o.z.string(),code:o.z.string().optional(),scope:o.z.string().optional(),hd:o.z.string().optional(),error:o.z.string().optional(),error_description:o.z.string().optional(),error_code:o.z.string().optional(),error_reason:o.z.string().optional()})}}}},responses:{302:{description:"Redirect to the client's redirect uri"},400:{description:"Bad Request",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}},500:{description:"Internal Server Error",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async t=>{const{state:e,code:n,error:r,error_description:i,error_code:s,error_reason:a}=t.req.valid("form");if(r)return $s(t,e,r,i,s,a);if(!n)throw new v(400,{message:"Code is required"});try{const c=await Ug(t,{code:n,state:e});if(!(c instanceof Response))throw new v(500,{message:"Internal server error"});return c}catch(c){if(c instanceof B&&c.status===400){const l=await t.env.data.codes.get(t.var.tenant_id||"",e,"oauth2_state");if(l){const d=await t.env.data.loginSessions.get(t.var.tenant_id,l.login_id);if(d&&Dg(d.authParams.response_mode)){let u="access_denied";try{u=JSON.parse(c.message).message||u}catch{u=c.message||u}return $s(t,e,"access_denied",u)}}}throw c}});function Tp(t,e=[],n={}){try{const r=new URL(t);return e.some(i=>{try{return s5(r,new URL(i),n)}catch{return!1}})}catch{return!1}}function s5(t,e,n={}){if(t.protocol!==e.protocol)return!1;if(n.allowPathWildcards&&e.pathname.includes("*")){const r=e.pathname.replace(/\*/g,".*").replace(/\//g,"\\/");if(!new RegExp(`^${r}$`).test(t.pathname))return!1}else if(t.pathname!==e.pathname)return!1;if(n.allowSubDomainWildcards&&e.hostname.startsWith("*.")&&e.hostname.split(".").length>2&&["http:","https:"].includes(e.protocol)){const r=e.hostname.split(".").slice(1).join(".");return t.hostname===r||t.hostname.endsWith("."+r)}return t.hostname===e.hostname}const a5=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{query:o.z.object({client_id:o.z.string(),returnTo:o.z.string().optional()}),header:o.z.object({cookie:o.z.string().optional()})},responses:{302:{description:"Log the user out"}}}),async t=>{const{client_id:e,returnTo:n}=t.req.valid("query"),r=await t.env.data.legacyClients.get(e);if(!r)return t.text("OK");const i=await t.env.data.legacyClients.get("DEFAULT_CLIENT");t.set("client_id",e),t.set("tenant_id",r.tenant.id);const s=n||t.req.header("referer");if(!s)return t.text("OK");if(!Tp(s,[...r.allowed_logout_urls||[],...i?.allowed_logout_urls||[]],{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new v(400,{message:"Invalid redirect uri"});const a=t.req.header("cookie");if(a){const c=Wr(r.tenant.id,a);if(c){const l=await t.env.data.sessions.get(r.tenant.id,c);if(l){const d=await t.env.data.users.get(r.tenant.id,l.user_id);d&&(t.set("user_id",d.user_id),t.set("connection",d.connection));const u=await t.env.data.refreshTokens.list(r.tenant.id,{q:`session_id=${c}`,page:0,per_page:100,include_totals:!1});await Promise.all(u.refresh_tokens.map(f=>t.env.data.refreshTokens.remove(r.tenant.id,f.id))),await t.env.data.sessions.update(r.tenant.id,c,{revoked_at:new Date().toISOString()})}}}return ie(t,r.tenant.id,{type:te.SUCCESS_LOGOUT,description:"User successfully logged out"}),new Response("Redirecting",{status:302,headers:{"set-cookie":r_(r.tenant.id,t.req.header("host")),location:s}})}),Mg=o.z.object({sub:o.z.string(),email:o.z.string().optional(),family_name:o.z.string().optional(),given_name:o.z.string().optional(),email_verified:o.z.boolean()}),c5=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:Mg}},description:"Userinfo"}}}),async t=>{if(!t.var.user)throw new v(404,{message:"User not found"});const e=await t.env.data.users.get(t.var.user.tenant_id,t.var.user.sub);if(!e)throw new v(404,{message:"User not found"});return t.json(Mg.parse({...e,sub:e.user_id}))}),l5=new o.OpenAPIHono().openapi(o.createRoute({tags:["well known"],method:"get",path:"/jwks.json",request:{},responses:{200:{content:{"application/json":{schema:fm}},description:"List of tenants"}}}),async t=>{const e=await pu(t.env.data);return t.json({keys:e},{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${ms}, stale-while-revalidate=${ms*2}, stale-if-error=86400`}})}).openapi(o.createRoute({tags:["well known"],method:"get",path:"/openid-configuration",request:{},responses:{200:{content:{"application/json":{schema:Ll}},description:"List of tenants"}}}),async t=>{const e=Ll.parse({issuer:ic(t.env),authorization_endpoint:`${me(t.env)}authorize`,token_endpoint:`${me(t.env)}oauth/token`,device_authorization_endpoint:`${me(t.env)}oauth/device/code`,userinfo_endpoint:`${me(t.env)}userinfo`,mfa_challenge_endpoint:`${me(t.env)}mfa/challenge`,jwks_uri:`${me(t.env)}.well-known/jwks.json`,registration_endpoint:`${me(t.env)}oidc/register`,revocation_endpoint:`${me(t.env)}oauth/revoke`,scopes_supported:["openid","profile","offline_access","name","given_name","family_name","nickname","email","email_verified","picture","created_at","identities","phone","address"],response_types_supported:["code","token","id_token","code token","code id_token","token id_token","code token id_token"],code_challenge_methods_supported:["S256","plain"],response_modes_supported:["query","fragment","form_post"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256"],token_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post"],claims_supported:["aud","auth_time","created_at","email","email_verified","exp","family_name","given_name","iat","identities","iss","name","nickname","phone_number","picture","sub"],request_uri_parameter_supported:!1,request_parameter_supported:!1,token_endpoint_auth_signing_alg_values_supported:["RS256","RS384","PS256"]});return t.json(e,{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${ms}, stale-while-revalidate=${ms*2}, stale-if-error=86400`}})});function fo(t,e){if(!t||!e||t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}const E1=o.z.object({grant_type:o.z.literal("client_credentials"),scope:o.z.string().optional(),client_secret:o.z.string(),client_id:o.z.string(),audience:o.z.string().optional()});async function d5(t,e){const n=await t.env.data.legacyClients.get(e.client_id);if(!n)throw new B(403,{message:"Invalid client credentials"});if(n.client_secret&&!fo(n.client_secret,e.client_secret))throw new B(403,{message:"Invalid client credentials"});const r={client_id:n.client_id,scope:e.scope,audience:e.audience||n.tenant.default_audience};return{client:n,authParams:r}}const u5=o.z.object({grant_type:o.z.literal("authorization_code"),client_id:o.z.string(),code:o.z.string(),redirect_uri:o.z.string().optional(),client_secret:o.z.string().optional(),code_verifier:o.z.string().optional(),organization:o.z.string().optional()}).refine(t=>"client_secret"in t&&!("code_verifier"in t)||!("client_secret"in t)&&"code_verifier"in t,{message:"Must provide either client_secret (standard flow) or code_verifier/code_verifier_mode (PKCE flow), but not both"});async function p5(t,e){const n=await t.env.data.legacyClients.get(e.client_id);if(!n)throw new B(403,{message:"Client not found"});const r=await t.env.data.codes.get(n.tenant.id,e.code,"authorization_code");if(!r||!r.user_id)throw ie(t,n.tenant.id,{type:te.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid client credentials"}),new B(403,{message:"Invalid client credentials"});if(new Date(r.expires_at)<new Date)throw ie(t,n.tenant.id,{type:te.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Code expired",userId:r.user_id}),new B(403,{message:"Code expired"});if(r.used_at)throw ie(t,n.tenant.id,{type:te.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid authorization code",userId:r.user_id}),new B(403,{error:"invalid_grant",error_description:"Invalid authorization code"});const i=await t.env.data.loginSessions.get(n.tenant.id,r.login_id);if(!i)throw new B(403,{message:"Invalid login"});if(e.organization&&i.authParams.organization&&e.organization!==i.authParams.organization)throw new B(400,{error:"invalid_request",error_description:"Organization parameter does not match login session organization"});if("client_secret"in e){const l=await t.env.data.legacyClients.get("DEFAULT_CLIENT");if(!fo(n.client_secret,e.client_secret)&&!fo(l?.client_secret,e.client_secret))throw ie(t,n.tenant.id,{type:te.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid client credentials",userId:r.user_id}),new B(403,{message:"Invalid client credentials"})}else if(r.code_challenge&&r.code_challenge_method&&e.code_verifier){const l=await iv(e.code_verifier,r.code_challenge_method);if(!fo(l,r.code_challenge))throw ie(t,n.tenant.id,{type:te.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid client credentials",userId:r.user_id}),new B(403,{message:"Invalid client credentials"})}if(r.redirect_uri&&r.redirect_uri!==e.redirect_uri)throw ie(t,n.tenant.id,{type:te.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid redirect uri",userId:r.user_id}),new B(403,{message:"Invalid redirect uri"});const s=await t.env.data.users.get(n.tenant.id,r.user_id);if(!s)throw new B(403,{message:"User not found"});await t.env.data.codes.used(n.tenant.id,e.code);let a;i.session_id&&i.authParams.scope?.split(" ").includes("offline_access")&&(a=await d_(t,{user:s,client:n,session_id:i.session_id,scope:i.authParams.scope,audience:i.authParams.audience}));let c;if(i.authParams.organization){const l=await t.env.data.organizations.get(n.tenant.id,i.authParams.organization);l?c={id:l.id,name:l.name}:c={id:i.authParams.organization,name:"Unknown"}}return{user:s,client:n,loginSession:i,session_id:i.session_id,refresh_token:a?.id,organization:c,authParams:{...i.authParams,state:r.state,nonce:r.nonce,response_mode:Ct.WEB_MESSAGE,client_id:n.client_id,scope:i.authParams.scope,audience:i.authParams.audience}}}function qg(t,e){const n=t.var.log;n?t.set("log",`${n}
82
- ${e}`):t.set("log",e)}const f5=o.z.object({grant_type:o.z.literal("refresh_token"),client_id:o.z.string(),redirect_uri:o.z.string().optional(),refresh_token:o.z.string(),client_secret:o.z.string().optional()});async function h5(t,e){const n=await t.env.data.legacyClients.get(e.client_id);if(!n)throw new B(403,{message:"Client not found"});if(e.client_secret&&n.client_secret&&!fo(n.client_secret,e.client_secret))throw new B(403,{error:"invalid_client",error_description:"Client authentication failed"});const r=await t.env.data.refreshTokens.get(n.tenant.id,e.refresh_token);if(r){if(r.expires_at&&new Date(r.expires_at)<new Date||r.idle_expires_at&&new Date(r.idle_expires_at)<new Date)throw qg(t,`Refresh token has expired: ${e.refresh_token}`),new B(400,{error:"invalid_grant",error_description:"Refresh token has expired"})}else throw qg(t,`Invalid refresh token: ${e.refresh_token}`),new B(400,{error:"invalid_grant",error_description:"Invalid refresh token"});const i=await t.env.data.users.get(n.tenant.id,r.user_id);if(!i)throw new B(403,{message:"User not found"});t.set("user_id",i.user_id);const s=r.resource_servers[0];if(r.idle_expires_at){const a=new Date(Date.now()+2592e6);await t.env.data.refreshTokens.update(n.tenant.id,r.id,{idle_expires_at:a.toISOString(),last_exchanged_at:new Date().toISOString(),device:{...r.device,last_ip:t.req.header["x-real-ip"]||"",last_user_agent:t.req.header["user-agent"]||""}})}return{user:i,client:n,refresh_token:r.id,session_id:r.session_id,authParams:{client_id:n.client_id,audience:s?.audience,scope:s?.scopes,response_mode:Ct.WEB_MESSAGE}}}const g5={version:4,country_calling_codes:{1:["US","AG","AI","AS","BB","BM","BS","CA","DM","DO","GD","GU","JM","KN","KY","LC","MP","MS","PR","SX","TC","TT","VC","VG","VI"],7:["RU","KZ"],20:["EG"],27:["ZA"],30:["GR"],31:["NL"],32:["BE"],33:["FR"],34:["ES"],36:["HU"],39:["IT","VA"],40:["RO"],41:["CH"],43:["AT"],44:["GB","GG","IM","JE"],45:["DK"],46:["SE"],47:["NO","SJ"],48:["PL"],49:["DE"],51:["PE"],52:["MX"],53:["CU"],54:["AR"],55:["BR"],56:["CL"],57:["CO"],58:["VE"],60:["MY"],61:["AU","CC","CX"],62:["ID"],63:["PH"],64:["NZ"],65:["SG"],66:["TH"],81:["JP"],82:["KR"],84:["VN"],86:["CN"],90:["TR"],91:["IN"],92:["PK"],93:["AF"],94:["LK"],95:["MM"],98:["IR"],211:["SS"],212:["MA","EH"],213:["DZ"],216:["TN"],218:["LY"],220:["GM"],221:["SN"],222:["MR"],223:["ML"],224:["GN"],225:["CI"],226:["BF"],227:["NE"],228:["TG"],229:["BJ"],230:["MU"],231:["LR"],232:["SL"],233:["GH"],234:["NG"],235:["TD"],236:["CF"],237:["CM"],238:["CV"],239:["ST"],240:["GQ"],241:["GA"],242:["CG"],243:["CD"],244:["AO"],245:["GW"],246:["IO"],247:["AC"],248:["SC"],249:["SD"],250:["RW"],251:["ET"],252:["SO"],253:["DJ"],254:["KE"],255:["TZ"],256:["UG"],257:["BI"],258:["MZ"],260:["ZM"],261:["MG"],262:["RE","YT"],263:["ZW"],264:["NA"],265:["MW"],266:["LS"],267:["BW"],268:["SZ"],269:["KM"],290:["SH","TA"],291:["ER"],297:["AW"],298:["FO"],299:["GL"],350:["GI"],351:["PT"],352:["LU"],353:["IE"],354:["IS"],355:["AL"],356:["MT"],357:["CY"],358:["FI","AX"],359:["BG"],370:["LT"],371:["LV"],372:["EE"],373:["MD"],374:["AM"],375:["BY"],376:["AD"],377:["MC"],378:["SM"],380:["UA"],381:["RS"],382:["ME"],383:["XK"],385:["HR"],386:["SI"],387:["BA"],389:["MK"],420:["CZ"],421:["SK"],423:["LI"],500:["FK"],501:["BZ"],502:["GT"],503:["SV"],504:["HN"],505:["NI"],506:["CR"],507:["PA"],508:["PM"],509:["HT"],590:["GP","BL","MF"],591:["BO"],592:["GY"],593:["EC"],594:["GF"],595:["PY"],596:["MQ"],597:["SR"],598:["UY"],599:["CW","BQ"],670:["TL"],672:["NF"],673:["BN"],674:["NR"],675:["PG"],676:["TO"],677:["SB"],678:["VU"],679:["FJ"],680:["PW"],681:["WF"],682:["CK"],683:["NU"],685:["WS"],686:["KI"],687:["NC"],688:["TV"],689:["PF"],690:["TK"],691:["FM"],692:["MH"],850:["KP"],852:["HK"],853:["MO"],855:["KH"],856:["LA"],880:["BD"],886:["TW"],960:["MV"],961:["LB"],962:["JO"],963:["SY"],964:["IQ"],965:["KW"],966:["SA"],967:["YE"],968:["OM"],970:["PS"],971:["AE"],972:["IL"],973:["BH"],974:["QA"],975:["BT"],976:["MN"],977:["NP"],992:["TJ"],993:["TM"],994:["AZ"],995:["GE"],996:["KG"],998:["UZ"]},countries:{AC:["247","00","(?:[01589]\\d|[46])\\d{4}",[5,6]],AD:["376","00","(?:1|6\\d)\\d{7}|[135-9]\\d{5}",[6,8,9],[["(\\d{3})(\\d{3})","$1 $2",["[135-9]"]],["(\\d{4})(\\d{4})","$1 $2",["1"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["6"]]]],AE:["971","00","(?:[4-7]\\d|9[0-689])\\d{7}|800\\d{2,9}|[2-4679]\\d{7}",[5,6,7,8,9,10,11,12],[["(\\d{3})(\\d{2,9})","$1 $2",["60|8"]],["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["[236]|[479][2-8]"],"0$1"],["(\\d{3})(\\d)(\\d{5})","$1 $2 $3",["[479]"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["5"],"0$1"]],"0"],AF:["93","00","[2-7]\\d{8}",[9],[["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[2-7]"],"0$1"]],"0"],AG:["1","011","(?:268|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([457]\\d{6})$|1","268$1",0,"268"],AI:["1","011","(?:264|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2457]\\d{6})$|1","264$1",0,"264"],AL:["355","00","(?:700\\d\\d|900)\\d{3}|8\\d{5,7}|(?:[2-5]|6\\d)\\d{7}",[6,7,8,9],[["(\\d{3})(\\d{3,4})","$1 $2",["80|9"],"0$1"],["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["4[2-6]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[2358][2-5]|4"],"0$1"],["(\\d{3})(\\d{5})","$1 $2",["[23578]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["6"],"0$1"]],"0"],AM:["374","00","(?:[1-489]\\d|55|60|77)\\d{6}",[8],[["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["[89]0"],"0 $1"],["(\\d{3})(\\d{5})","$1 $2",["2|3[12]"],"(0$1)"],["(\\d{2})(\\d{6})","$1 $2",["1|47"],"(0$1)"],["(\\d{2})(\\d{6})","$1 $2",["[3-9]"],"0$1"]],"0"],AO:["244","00","[29]\\d{8}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[29]"]]]],AR:["54","00","(?:11|[89]\\d\\d)\\d{8}|[2368]\\d{9}",[10,11],[["(\\d{4})(\\d{2})(\\d{4})","$1 $2-$3",["2(?:2[024-9]|3[0-59]|47|6[245]|9[02-8])|3(?:3[28]|4[03-9]|5[2-46-8]|7[1-578]|8[2-9])","2(?:[23]02|6(?:[25]|4[6-8])|9(?:[02356]|4[02568]|72|8[23]))|3(?:3[28]|4(?:[04679]|3[5-8]|5[4-68]|8[2379])|5(?:[2467]|3[237]|8[2-5])|7[1-578]|8(?:[2469]|3[2578]|5[4-8]|7[36-8]|8[5-8]))|2(?:2[24-9]|3[1-59]|47)","2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3[78]|5(?:4[46]|8)|8[2379])|5(?:[2467]|3[237]|8[23])|7[1-578]|8(?:[2469]|3[278]|5[56][46]|86[3-6]))|2(?:2[24-9]|3[1-59]|47)|38(?:[58][78]|7[378])|3(?:4[35][56]|58[45]|8(?:[38]5|54|76))[4-6]","2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3(?:5(?:4[0-25689]|[56])|[78])|58|8[2379])|5(?:[2467]|3[237]|8(?:[23]|4(?:[45]|60)|5(?:4[0-39]|5|64)))|7[1-578]|8(?:[2469]|3[278]|54(?:4|5[13-7]|6[89])|86[3-6]))|2(?:2[24-9]|3[1-59]|47)|38(?:[58][78]|7[378])|3(?:454|85[56])[46]|3(?:4(?:36|5[56])|8(?:[38]5|76))[4-6]"],"0$1",1],["(\\d{2})(\\d{4})(\\d{4})","$1 $2-$3",["1"],"0$1",1],["(\\d{3})(\\d{3})(\\d{4})","$1-$2-$3",["[68]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2-$3",["[23]"],"0$1",1],["(\\d)(\\d{4})(\\d{2})(\\d{4})","$2 15-$3-$4",["9(?:2[2-469]|3[3-578])","9(?:2(?:2[024-9]|3[0-59]|47|6[245]|9[02-8])|3(?:3[28]|4[03-9]|5[2-46-8]|7[1-578]|8[2-9]))","9(?:2(?:[23]02|6(?:[25]|4[6-8])|9(?:[02356]|4[02568]|72|8[23]))|3(?:3[28]|4(?:[04679]|3[5-8]|5[4-68]|8[2379])|5(?:[2467]|3[237]|8[2-5])|7[1-578]|8(?:[2469]|3[2578]|5[4-8]|7[36-8]|8[5-8])))|92(?:2[24-9]|3[1-59]|47)","9(?:2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3[78]|5(?:4[46]|8)|8[2379])|5(?:[2467]|3[237]|8[23])|7[1-578]|8(?:[2469]|3[278]|5(?:[56][46]|[78])|7[378]|8(?:6[3-6]|[78]))))|92(?:2[24-9]|3[1-59]|47)|93(?:4[35][56]|58[45]|8(?:[38]5|54|76))[4-6]","9(?:2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3(?:5(?:4[0-25689]|[56])|[78])|5(?:4[46]|8)|8[2379])|5(?:[2467]|3[237]|8(?:[23]|4(?:[45]|60)|5(?:4[0-39]|5|64)))|7[1-578]|8(?:[2469]|3[278]|5(?:4(?:4|5[13-7]|6[89])|[56][46]|[78])|7[378]|8(?:6[3-6]|[78]))))|92(?:2[24-9]|3[1-59]|47)|93(?:4(?:36|5[56])|8(?:[38]5|76))[4-6]"],"0$1",0,"$1 $2 $3-$4"],["(\\d)(\\d{2})(\\d{4})(\\d{4})","$2 15-$3-$4",["91"],"0$1",0,"$1 $2 $3-$4"],["(\\d{3})(\\d{3})(\\d{5})","$1-$2-$3",["8"],"0$1"],["(\\d)(\\d{3})(\\d{3})(\\d{4})","$2 15-$3-$4",["9"],"0$1",0,"$1 $2 $3-$4"]],"0",0,"0?(?:(11|2(?:2(?:02?|[13]|2[13-79]|4[1-6]|5[2457]|6[124-8]|7[1-4]|8[13-6]|9[1267])|3(?:02?|1[467]|2[03-6]|3[13-8]|[49][2-6]|5[2-8]|[67])|4(?:7[3-578]|9)|6(?:[0136]|2[24-6]|4[6-8]?|5[15-8])|80|9(?:0[1-3]|[19]|2\\d|3[1-6]|4[02568]?|5[2-4]|6[2-46]|72?|8[23]?))|3(?:3(?:2[79]|6|8[2578])|4(?:0[0-24-9]|[12]|3[5-8]?|4[24-7]|5[4-68]?|6[02-9]|7[126]|8[2379]?|9[1-36-8])|5(?:1|2[1245]|3[237]?|4[1-46-9]|6[2-4]|7[1-6]|8[2-5]?)|6[24]|7(?:[069]|1[1568]|2[15]|3[145]|4[13]|5[14-8]|7[2-57]|8[126])|8(?:[01]|2[15-7]|3[2578]?|4[13-6]|5[4-8]?|6[1-357-9]|7[36-8]?|8[5-8]?|9[124])))15)?","9$1"],AS:["1","011","(?:[58]\\d\\d|684|900)\\d{7}",[10],0,"1",0,"([267]\\d{6})$|1","684$1",0,"684"],AT:["43","00","1\\d{3,12}|2\\d{6,12}|43(?:(?:0\\d|5[02-9])\\d{3,9}|2\\d{4,5}|[3467]\\d{4}|8\\d{4,6}|9\\d{4,7})|5\\d{4,12}|8\\d{7,12}|9\\d{8,12}|(?:[367]\\d|4[0-24-9])\\d{4,11}",[4,5,6,7,8,9,10,11,12,13],[["(\\d)(\\d{3,12})","$1 $2",["1(?:11|[2-9])"],"0$1"],["(\\d{3})(\\d{2})","$1 $2",["517"],"0$1"],["(\\d{2})(\\d{3,5})","$1 $2",["5[079]"],"0$1"],["(\\d{3})(\\d{3,10})","$1 $2",["(?:31|4)6|51|6(?:48|5[0-3579]|[6-9])|7(?:20|32|8)|[89]","(?:31|4)6|51|6(?:485|5[0-3579]|[6-9])|7(?:20|32|8)|[89]"],"0$1"],["(\\d{4})(\\d{3,9})","$1 $2",["[2-467]|5[2-6]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["5"],"0$1"],["(\\d{2})(\\d{4})(\\d{4,7})","$1 $2 $3",["5"],"0$1"]],"0"],AU:["61","001[14-689]|14(?:1[14]|34|4[17]|[56]6|7[47]|88)0011","1(?:[0-79]\\d{7}(?:\\d(?:\\d{2})?)?|8[0-24-9]\\d{7})|[2-478]\\d{8}|1\\d{4,7}",[5,6,7,8,9,10,12],[["(\\d{2})(\\d{3,4})","$1 $2",["16"],"0$1"],["(\\d{2})(\\d{3})(\\d{2,4})","$1 $2 $3",["16"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["14|4"],"0$1"],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["[2378]"],"(0$1)"],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1(?:30|[89])"]]],"0",0,"(183[12])|0",0,0,0,[["(?:(?:241|349)0\\d\\d|8(?:51(?:0(?:0[03-9]|[12479]\\d|3[2-9]|5[0-8]|6[1-9]|8[0-7])|1(?:[0235689]\\d|1[0-69]|4[0-589]|7[0-47-9])|2(?:0[0-79]|[18][13579]|2[14-9]|3[0-46-9]|[4-6]\\d|7[89]|9[0-4])|[34]\\d\\d)|91(?:(?:[0-58]\\d|6[0135-9])\\d|7(?:0[0-24-9]|[1-9]\\d)|9(?:[0-46-9]\\d|5[0-79]))))\\d{3}|(?:2(?:[0-26-9]\\d|3[0-8]|4[02-9]|5[0135-9])|3(?:[0-3589]\\d|4[0-578]|6[1-9]|7[0-35-9])|7(?:[013-57-9]\\d|2[0-8])|8(?:55|6[0-8]|[78]\\d|9[02-9]))\\d{6}",[9]],["4(?:79[01]|83[0-36-9]|95[0-3])\\d{5}|4(?:[0-36]\\d|4[047-9]|[58][0-24-9]|7[02-8]|9[0-47-9])\\d{6}",[9]],["180(?:0\\d{3}|2)\\d{3}",[7,10]],["190[0-26]\\d{6}",[10]],0,0,0,["163\\d{2,6}",[5,6,7,8,9]],["14(?:5(?:1[0458]|[23][458])|71\\d)\\d{4}",[9]],["13(?:00\\d{6}(?:\\d{2})?|45[0-4]\\d{3})|13\\d{4}",[6,8,10,12]]],"0011"],AW:["297","00","(?:[25-79]\\d\\d|800)\\d{4}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[25-9]"]]]],AX:["358","00|99(?:[01469]|5(?:[14]1|3[23]|5[59]|77|88|9[09]))","2\\d{4,9}|35\\d{4,5}|(?:60\\d\\d|800)\\d{4,6}|7\\d{5,11}|(?:[14]\\d|3[0-46-9]|50)\\d{4,8}",[5,6,7,8,9,10,11,12],0,"0",0,0,0,0,"18",0,"00"],AZ:["994","00","365\\d{6}|(?:[124579]\\d|60|88)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["90"],"0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["1[28]|2|365|46","1[28]|2|365[45]|46","1[28]|2|365(?:4|5[02])|46"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[13-9]"],"0$1"]],"0"],BA:["387","00","6\\d{8}|(?:[35689]\\d|49|70)\\d{6}",[8,9],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["6[1-3]|[7-9]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2-$3",["[3-5]|6[56]"],"0$1"],["(\\d{2})(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3 $4",["6"],"0$1"]],"0"],BB:["1","011","(?:246|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","246$1",0,"246"],BD:["880","00","[1-469]\\d{9}|8[0-79]\\d{7,8}|[2-79]\\d{8}|[2-9]\\d{7}|[3-9]\\d{6}|[57-9]\\d{5}",[6,7,8,9,10],[["(\\d{2})(\\d{4,6})","$1-$2",["31[5-8]|[459]1"],"0$1"],["(\\d{3})(\\d{3,7})","$1-$2",["3(?:[67]|8[013-9])|4(?:6[168]|7|[89][18])|5(?:6[128]|9)|6(?:[15]|28|4[14])|7[2-589]|8(?:0[014-9]|[12])|9[358]|(?:3[2-5]|4[235]|5[2-578]|6[0389]|76|8[3-7]|9[24])1|(?:44|66)[01346-9]"],"0$1"],["(\\d{4})(\\d{3,6})","$1-$2",["[13-9]|2[23]"],"0$1"],["(\\d)(\\d{7,8})","$1-$2",["2"],"0$1"]],"0"],BE:["32","00","4\\d{8}|[1-9]\\d{7}",[8,9],[["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["(?:80|9)0"],"0$1"],["(\\d)(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[239]|4[23]"],"0$1"],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[15-8]"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["4"],"0$1"]],"0"],BF:["226","00","(?:[025-7]\\d|44)\\d{6}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[024-7]"]]]],BG:["359","00","00800\\d{7}|[2-7]\\d{6,7}|[89]\\d{6,8}|2\\d{5}",[6,7,8,9,12],[["(\\d)(\\d)(\\d{2})(\\d{2})","$1 $2 $3 $4",["2"],"0$1"],["(\\d{3})(\\d{4})","$1 $2",["43[1-6]|70[1-9]"],"0$1"],["(\\d)(\\d{3})(\\d{3,4})","$1 $2 $3",["2"],"0$1"],["(\\d{2})(\\d{3})(\\d{2,3})","$1 $2 $3",["[356]|4[124-7]|7[1-9]|8[1-6]|9[1-7]"],"0$1"],["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["(?:70|8)0"],"0$1"],["(\\d{3})(\\d{3})(\\d{2})","$1 $2 $3",["43[1-7]|7"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[48]|9[08]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["9"],"0$1"]],"0"],BH:["973","00","[136-9]\\d{7}",[8],[["(\\d{4})(\\d{4})","$1 $2",["[13679]|8[02-4679]"]]]],BI:["257","00","(?:[267]\\d|31)\\d{6}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2367]"]]]],BJ:["229","00","(?:01\\d|8)\\d{7}",[8,10],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4 $5",["0"]]]],BL:["590","00","(?:590\\d|7090)\\d{5}|(?:69|80|9\\d)\\d{7}",[9],0,"0",0,0,0,0,0,[["590(?:2[7-9]|3[3-7]|5[12]|87)\\d{4}"],["(?:69(?:0\\d\\d|1(?:2[2-9]|3[0-5])|4(?:0[89]|1[2-6]|9\\d)|6(?:1[016-9]|5[0-4]|[67]\\d))|7090[0-4])\\d{4}"],["80[0-5]\\d{6}"],0,0,0,0,0,["9(?:(?:39[5-7]|76[018])\\d|475[0-6])\\d{4}"]]],BM:["1","011","(?:441|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","441$1",0,"441"],BN:["673","00","[2-578]\\d{6}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[2-578]"]]]],BO:["591","00(?:1\\d)?","8001\\d{5}|(?:[2-467]\\d|50)\\d{6}",[8,9],[["(\\d)(\\d{7})","$1 $2",["[235]|4[46]"]],["(\\d{8})","$1",["[67]"]],["(\\d{3})(\\d{2})(\\d{4})","$1 $2 $3",["8"]]],"0",0,"0(1\\d)?"],BQ:["599","00","(?:[34]1|7\\d)\\d{5}",[7],0,0,0,0,0,0,"[347]"],BR:["55","00(?:1[245]|2[1-35]|31|4[13]|[56]5|99)","[1-467]\\d{9,10}|55[0-46-9]\\d{8}|[34]\\d{7}|55\\d{7,8}|(?:5[0-46-9]|[89]\\d)\\d{7,9}",[8,9,10,11],[["(\\d{4})(\\d{4})","$1-$2",["300|4(?:0[02]|37|86)","300|4(?:0(?:0|20)|370|864)"]],["(\\d{3})(\\d{2,3})(\\d{4})","$1 $2 $3",["(?:[358]|90)0"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1 $2-$3",["(?:[14689][1-9]|2[12478]|3[1-578]|5[13-5]|7[13-579])[2-57]"],"($1)"],["(\\d{2})(\\d{5})(\\d{4})","$1 $2-$3",["[16][1-9]|[2-57-9]"],"($1)"]],"0",0,"(?:0|90)(?:(1[245]|2[1-35]|31|4[13]|[56]5|99)(\\d{10,11}))?","$2"],BS:["1","011","(?:242|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([3-8]\\d{6})$|1","242$1",0,"242"],BT:["975","00","[178]\\d{7}|[2-8]\\d{6}",[7,8],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["[2-6]|7[246]|8[2-4]"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["1[67]|[78]"]]]],BW:["267","00","(?:0800|(?:[37]|800)\\d)\\d{6}|(?:[2-6]\\d|90)\\d{5}",[7,8,10],[["(\\d{2})(\\d{5})","$1 $2",["90"]],["(\\d{3})(\\d{4})","$1 $2",["[24-6]|3[15-9]"]],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[37]"]],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["0"]],["(\\d{3})(\\d{4})(\\d{3})","$1 $2 $3",["8"]]]],BY:["375","810","(?:[12]\\d|33|44|902)\\d{7}|8(?:0[0-79]\\d{5,7}|[1-7]\\d{9})|8(?:1[0-489]|[5-79]\\d)\\d{7}|8[1-79]\\d{6,7}|8[0-79]\\d{5}|8\\d{5}",[6,7,8,9,10,11],[["(\\d{3})(\\d{3})","$1 $2",["800"],"8 $1"],["(\\d{3})(\\d{2})(\\d{2,4})","$1 $2 $3",["800"],"8 $1"],["(\\d{4})(\\d{2})(\\d{3})","$1 $2-$3",["1(?:5[169]|6[3-5]|7[179])|2(?:1[35]|2[34]|3[3-5])","1(?:5[169]|6(?:3[1-3]|4|5[125])|7(?:1[3-9]|7[0-24-6]|9[2-7]))|2(?:1[35]|2[34]|3[3-5])"],"8 0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2-$3-$4",["1(?:[56]|7[467])|2[1-3]"],"8 0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2-$3-$4",["[1-4]"],"8 0$1"],["(\\d{3})(\\d{3,4})(\\d{4})","$1 $2 $3",["[89]"],"8 $1"]],"8",0,"0|80?",0,0,0,0,"8~10"],BZ:["501","00","(?:0800\\d|[2-8])\\d{6}",[7,11],[["(\\d{3})(\\d{4})","$1-$2",["[2-8]"]],["(\\d)(\\d{3})(\\d{4})(\\d{3})","$1-$2-$3-$4",["0"]]]],CA:["1","011","[2-9]\\d{9}|3\\d{6}",[7,10],0,"1",0,0,0,0,0,[["(?:2(?:04|[23]6|[48]9|5[07]|63)|3(?:06|43|54|6[578]|82)|4(?:03|1[68]|[26]8|3[178]|50|74)|5(?:06|1[49]|48|79|8[147])|6(?:04|[18]3|39|47|72)|7(?:0[59]|42|53|78|8[02])|8(?:[06]7|19|25|7[39])|9(?:0[25]|42))[2-9]\\d{6}",[10]],["",[10]],["8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",[10]],["900[2-9]\\d{6}",[10]],["52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|(?:5(?:2[125-9]|33|44|66|77|88)|6(?:22|33))[2-9]\\d{6}",[10]],0,["310\\d{4}",[7]],0,["600[2-9]\\d{6}",[10]]]],CC:["61","001[14-689]|14(?:1[14]|34|4[17]|[56]6|7[47]|88)0011","1(?:[0-79]\\d{8}(?:\\d{2})?|8[0-24-9]\\d{7})|[148]\\d{8}|1\\d{5,7}",[6,7,8,9,10,12],0,"0",0,"([59]\\d{7})$|0","8$1",0,0,[["8(?:51(?:0(?:02|31|60|89)|1(?:18|76)|223)|91(?:0(?:1[0-2]|29)|1(?:[28]2|50|79)|2(?:10|64)|3(?:[06]8|22)|4[29]8|62\\d|70[23]|959))\\d{3}",[9]],["4(?:79[01]|83[0-36-9]|95[0-3])\\d{5}|4(?:[0-36]\\d|4[047-9]|[58][0-24-9]|7[02-8]|9[0-47-9])\\d{6}",[9]],["180(?:0\\d{3}|2)\\d{3}",[7,10]],["190[0-26]\\d{6}",[10]],0,0,0,0,["14(?:5(?:1[0458]|[23][458])|71\\d)\\d{4}",[9]],["13(?:00\\d{6}(?:\\d{2})?|45[0-4]\\d{3})|13\\d{4}",[6,8,10,12]]],"0011"],CD:["243","00","(?:(?:[189]|5\\d)\\d|2)\\d{7}|[1-68]\\d{6}",[7,8,9,10],[["(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3",["88"],"0$1"],["(\\d{2})(\\d{5})","$1 $2",["[1-6]"],"0$1"],["(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3",["2"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["1"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[89]"],"0$1"],["(\\d{2})(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3 $4",["5"],"0$1"]],"0"],CF:["236","00","(?:[27]\\d{3}|8776)\\d{4}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[278]"]]]],CG:["242","00","222\\d{6}|(?:0\\d|80)\\d{7}",[9],[["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["8"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[02]"]]]],CH:["41","00","8\\d{11}|[2-9]\\d{8}",[9,12],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["8[047]|90"],"0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2-79]|81"],"0$1"],["(\\d{3})(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4 $5",["8"],"0$1"]],"0"],CI:["225","00","[02]\\d{9}",[10],[["(\\d{2})(\\d{2})(\\d)(\\d{5})","$1 $2 $3 $4",["2"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3 $4",["0"]]]],CK:["682","00","[2-578]\\d{4}",[5],[["(\\d{2})(\\d{3})","$1 $2",["[2-578]"]]]],CL:["56","(?:0|1(?:1[0-69]|2[02-5]|5[13-58]|69|7[0167]|8[018]))0","12300\\d{6}|6\\d{9,10}|[2-9]\\d{8}",[9,10,11],[["(\\d{5})(\\d{4})","$1 $2",["219","2196"],"($1)"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["60|809"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["44"]],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["2[1-36]"],"($1)"],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["9(?:10|[2-9])"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["3[2-5]|[47]|5[1-3578]|6[13-57]|8(?:0[1-8]|[1-9])"],"($1)"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["60|8"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["1"]],["(\\d{3})(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3 $4",["60"]]]],CM:["237","00","[26]\\d{8}|88\\d{6,7}",[8,9],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["88"]],["(\\d)(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4 $5",["[26]|88"]]]],CN:["86","00|1(?:[12]\\d|79)\\d\\d00","(?:(?:1[03-689]|2\\d)\\d\\d|6)\\d{8}|1\\d{10}|[126]\\d{6}(?:\\d(?:\\d{2})?)?|86\\d{5,6}|(?:[3-579]\\d|8[0-57-9])\\d{5,9}",[7,8,9,10,11,12],[["(\\d{2})(\\d{5,6})","$1 $2",["(?:10|2[0-57-9])[19]|3(?:[157]|35|49|9[1-68])|4(?:1[124-9]|2[179]|6[47-9]|7|8[23])|5(?:[1357]|2[37]|4[36]|6[1-46]|80)|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:07|1[236-8]|2[5-7]|[37]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3|4[13]|5[1-5]|7[0-79]|9[0-35-9])|(?:4[35]|59|85)[1-9]","(?:10|2[0-57-9])(?:1[02]|9[56])|8078|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))1","10(?:1(?:0|23)|9[56])|2[0-57-9](?:1(?:00|23)|9[56])|80781|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))12","10(?:1(?:0|23)|9[56])|2[0-57-9](?:1(?:00|23)|9[56])|807812|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))123","10(?:1(?:0|23)|9[56])|2[0-57-9](?:1(?:00|23)|9[56])|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:078|1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))123"],"0$1"],["(\\d{3})(\\d{5,6})","$1 $2",["3(?:[157]|35|49|9[1-68])|4(?:[17]|2[179]|6[47-9]|8[23])|5(?:[1357]|2[37]|4[36]|6[1-46]|80)|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]|4[13]|5[1-5])|(?:4[35]|59|85)[1-9]","(?:3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))[19]","85[23](?:10|95)|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[14-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))(?:10|9[56])","85[23](?:100|95)|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[14-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))(?:100|9[56])"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["(?:4|80)0"]],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["10|2(?:[02-57-9]|1[1-9])","10|2(?:[02-57-9]|1[1-9])","10[0-79]|2(?:[02-57-9]|1[1-79])|(?:10|21)8(?:0[1-9]|[1-9])"],"0$1",1],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["3(?:[3-59]|7[02-68])|4(?:[26-8]|3[3-9]|5[2-9])|5(?:3[03-9]|[468]|7[028]|9[2-46-9])|6|7(?:[0-247]|3[04-9]|5[0-4689]|6[2368])|8(?:[1-358]|9[1-7])|9(?:[013479]|5[1-5])|(?:[34]1|55|79|87)[02-9]"],"0$1",1],["(\\d{3})(\\d{7,8})","$1 $2",["9"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["80"],"0$1",1],["(\\d{3})(\\d{4})(\\d{4})","$1 $2 $3",["[3-578]"],"0$1",1],["(\\d{3})(\\d{4})(\\d{4})","$1 $2 $3",["1[3-9]"]],["(\\d{2})(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3 $4",["[12]"],"0$1",1]],"0",0,"(1(?:[12]\\d|79)\\d\\d)|0",0,0,0,0,"00"],CO:["57","00(?:4(?:[14]4|56)|[579])","(?:46|60\\d\\d)\\d{6}|(?:1\\d|[39])\\d{9}",[8,10,11],[["(\\d{4})(\\d{4})","$1 $2",["46"]],["(\\d{3})(\\d{7})","$1 $2",["6|90"],"($1)"],["(\\d{3})(\\d{7})","$1 $2",["3[0-357]|9[14]"]],["(\\d)(\\d{3})(\\d{7})","$1-$2-$3",["1"],"0$1",0,"$1 $2 $3"]],"0",0,"0([3579]|4(?:[14]4|56))?"],CR:["506","00","(?:8\\d|90)\\d{8}|(?:[24-8]\\d{3}|3005)\\d{4}",[8,10],[["(\\d{4})(\\d{4})","$1 $2",["[2-7]|8[3-9]"]],["(\\d{3})(\\d{3})(\\d{4})","$1-$2-$3",["[89]"]]],0,0,"(19(?:0[0-2468]|1[09]|20|66|77|99))"],CU:["53","119","(?:[2-7]|8\\d\\d)\\d{7}|[2-47]\\d{6}|[34]\\d{5}",[6,7,8,10],[["(\\d{2})(\\d{4,6})","$1 $2",["2[1-4]|[34]"],"(0$1)"],["(\\d)(\\d{6,7})","$1 $2",["7"],"(0$1)"],["(\\d)(\\d{7})","$1 $2",["[56]"],"0$1"],["(\\d{3})(\\d{7})","$1 $2",["8"],"0$1"]],"0"],CV:["238","0","(?:[2-59]\\d\\d|800)\\d{4}",[7],[["(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3",["[2-589]"]]]],CW:["599","00","(?:[34]1|60|(?:7|9\\d)\\d)\\d{5}",[7,8],[["(\\d{3})(\\d{4})","$1 $2",["[3467]"]],["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["9[4-8]"]]],0,0,0,0,0,"[69]"],CX:["61","001[14-689]|14(?:1[14]|34|4[17]|[56]6|7[47]|88)0011","1(?:[0-79]\\d{8}(?:\\d{2})?|8[0-24-9]\\d{7})|[148]\\d{8}|1\\d{5,7}",[6,7,8,9,10,12],0,"0",0,"([59]\\d{7})$|0","8$1",0,0,[["8(?:51(?:0(?:01|30|59|88)|1(?:17|46|75)|2(?:22|35))|91(?:00[6-9]|1(?:[28]1|49|78)|2(?:09|63)|3(?:12|26|75)|4(?:56|97)|64\\d|7(?:0[01]|1[0-2])|958))\\d{3}",[9]],["4(?:79[01]|83[0-36-9]|95[0-3])\\d{5}|4(?:[0-36]\\d|4[047-9]|[58][0-24-9]|7[02-8]|9[0-47-9])\\d{6}",[9]],["180(?:0\\d{3}|2)\\d{3}",[7,10]],["190[0-26]\\d{6}",[10]],0,0,0,0,["14(?:5(?:1[0458]|[23][458])|71\\d)\\d{4}",[9]],["13(?:00\\d{6}(?:\\d{2})?|45[0-4]\\d{3})|13\\d{4}",[6,8,10,12]]],"0011"],CY:["357","00","(?:[279]\\d|[58]0)\\d{6}",[8],[["(\\d{2})(\\d{6})","$1 $2",["[257-9]"]]]],CZ:["420","00","(?:[2-578]\\d|60)\\d{7}|9\\d{8,11}",[9,10,11,12],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[2-8]|9[015-7]"]],["(\\d{2})(\\d{3})(\\d{3})(\\d{2})","$1 $2 $3 $4",["96"]],["(\\d{2})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["9"]],["(\\d{3})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["9"]]]],DE:["49","00","[2579]\\d{5,14}|49(?:[34]0|69|8\\d)\\d\\d?|49(?:37|49|60|7[089]|9\\d)\\d{1,3}|49(?:2[024-9]|3[2-689]|7[1-7])\\d{1,8}|(?:1|[368]\\d|4[0-8])\\d{3,13}|49(?:[015]\\d|2[13]|31|[46][1-8])\\d{1,9}",[4,5,6,7,8,9,10,11,12,13,14,15],[["(\\d{2})(\\d{3,13})","$1 $2",["3[02]|40|[68]9"],"0$1"],["(\\d{3})(\\d{3,12})","$1 $2",["2(?:0[1-389]|1[124]|2[18]|3[14])|3(?:[35-9][15]|4[015])|906|(?:2[4-9]|4[2-9]|[579][1-9]|[68][1-8])1","2(?:0[1-389]|12[0-8])|3(?:[35-9][15]|4[015])|906|2(?:[13][14]|2[18])|(?:2[4-9]|4[2-9]|[579][1-9]|[68][1-8])1"],"0$1"],["(\\d{4})(\\d{2,11})","$1 $2",["[24-6]|3(?:[3569][02-46-9]|4[2-4679]|7[2-467]|8[2-46-8])|70[2-8]|8(?:0[2-9]|[1-8])|90[7-9]|[79][1-9]","[24-6]|3(?:3(?:0[1-467]|2[127-9]|3[124578]|7[1257-9]|8[1256]|9[145])|4(?:2[135]|4[13578]|9[1346])|5(?:0[14]|2[1-3589]|6[1-4]|7[13468]|8[13568])|6(?:2[1-489]|3[124-6]|6[13]|7[12579]|8[1-356]|9[135])|7(?:2[1-7]|4[145]|6[1-5]|7[1-4])|8(?:21|3[1468]|6|7[1467]|8[136])|9(?:0[12479]|2[1358]|4[134679]|6[1-9]|7[136]|8[147]|9[1468]))|70[2-8]|8(?:0[2-9]|[1-8])|90[7-9]|[79][1-9]|3[68]4[1347]|3(?:47|60)[1356]|3(?:3[46]|46|5[49])[1246]|3[4579]3[1357]"],"0$1"],["(\\d{3})(\\d{4})","$1 $2",["138"],"0$1"],["(\\d{5})(\\d{2,10})","$1 $2",["3"],"0$1"],["(\\d{3})(\\d{5,11})","$1 $2",["181"],"0$1"],["(\\d{3})(\\d)(\\d{4,10})","$1 $2 $3",["1(?:3|80)|9"],"0$1"],["(\\d{3})(\\d{7,8})","$1 $2",["1[67]"],"0$1"],["(\\d{3})(\\d{7,12})","$1 $2",["8"],"0$1"],["(\\d{5})(\\d{6})","$1 $2",["185","1850","18500"],"0$1"],["(\\d{3})(\\d{4})(\\d{4})","$1 $2 $3",["7"],"0$1"],["(\\d{4})(\\d{7})","$1 $2",["18[68]"],"0$1"],["(\\d{4})(\\d{7})","$1 $2",["15[1279]"],"0$1"],["(\\d{5})(\\d{6})","$1 $2",["15[03568]","15(?:[0568]|3[13])"],"0$1"],["(\\d{3})(\\d{8})","$1 $2",["18"],"0$1"],["(\\d{3})(\\d{2})(\\d{7,8})","$1 $2 $3",["1(?:6[023]|7)"],"0$1"],["(\\d{4})(\\d{2})(\\d{7})","$1 $2 $3",["15[279]"],"0$1"],["(\\d{3})(\\d{2})(\\d{8})","$1 $2 $3",["15"],"0$1"]],"0"],DJ:["253","00","(?:2\\d|77)\\d{6}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[27]"]]]],DK:["45","00","[2-9]\\d{7}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2-9]"]]]],DM:["1","011","(?:[58]\\d\\d|767|900)\\d{7}",[10],0,"1",0,"([2-7]\\d{6})$|1","767$1",0,"767"],DO:["1","011","(?:[58]\\d\\d|900)\\d{7}",[10],0,"1",0,0,0,0,"8001|8[024]9"],DZ:["213","00","(?:[1-4]|[5-79]\\d|80)\\d{7}",[8,9],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[1-4]"],"0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["9"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-8]"],"0$1"]],"0"],EC:["593","00","1\\d{9,10}|(?:[2-7]|9\\d)\\d{7}",[8,9,10,11],[["(\\d)(\\d{3})(\\d{4})","$1 $2-$3",["[2-7]"],"(0$1)",0,"$1-$2-$3"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["9"],"0$1"],["(\\d{4})(\\d{3})(\\d{3,4})","$1 $2 $3",["1"]]],"0"],EE:["372","00","8\\d{9}|[4578]\\d{7}|(?:[3-8]\\d|90)\\d{5}",[7,8,10],[["(\\d{3})(\\d{4})","$1 $2",["[369]|4[3-8]|5(?:[0-2]|5[0-478]|6[45])|7[1-9]|88","[369]|4[3-8]|5(?:[02]|1(?:[0-8]|95)|5[0-478]|6(?:4[0-4]|5[1-589]))|7[1-9]|88"]],["(\\d{4})(\\d{3,4})","$1 $2",["[45]|8(?:00|[1-49])","[45]|8(?:00[1-9]|[1-49])"]],["(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3",["7"]],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["8"]]]],EG:["20","00","[189]\\d{8,9}|[24-6]\\d{8}|[135]\\d{7}",[8,9,10],[["(\\d)(\\d{7,8})","$1 $2",["[23]"],"0$1"],["(\\d{2})(\\d{6,7})","$1 $2",["1[35]|[4-6]|8[2468]|9[235-7]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[89]"],"0$1"],["(\\d{2})(\\d{8})","$1 $2",["1"],"0$1"]],"0"],EH:["212","00","[5-8]\\d{8}",[9],0,"0",0,0,0,0,"528[89]"],ER:["291","00","[178]\\d{6}",[7],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["[178]"],"0$1"]],"0"],ES:["34","00","[5-9]\\d{8}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[89]00"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-9]"]]]],ET:["251","00","(?:11|[2-579]\\d)\\d{7}",[9],[["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[1-579]"],"0$1"]],"0"],FI:["358","00|99(?:[01469]|5(?:[14]1|3[23]|5[59]|77|88|9[09]))","[1-35689]\\d{4}|7\\d{10,11}|(?:[124-7]\\d|3[0-46-9])\\d{8}|[1-9]\\d{5,8}",[5,6,7,8,9,10,11,12],[["(\\d{5})","$1",["20[2-59]"],"0$1"],["(\\d{3})(\\d{3,7})","$1 $2",["(?:[1-3]0|[68])0|70[07-9]"],"0$1"],["(\\d{2})(\\d{4,8})","$1 $2",["[14]|2[09]|50|7[135]"],"0$1"],["(\\d{2})(\\d{6,10})","$1 $2",["7"],"0$1"],["(\\d)(\\d{4,9})","$1 $2",["(?:19|[2568])[1-8]|3(?:0[1-9]|[1-9])|9"],"0$1"]],"0",0,0,0,0,"1[03-79]|[2-9]",0,"00"],FJ:["679","0(?:0|52)","45\\d{5}|(?:0800\\d|[235-9])\\d{6}",[7,11],[["(\\d{3})(\\d{4})","$1 $2",["[235-9]|45"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["0"]]],0,0,0,0,0,0,0,"00"],FK:["500","00","[2-7]\\d{4}",[5]],FM:["691","00","(?:[39]\\d\\d|820)\\d{4}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[389]"]]]],FO:["298","00","[2-9]\\d{5}",[6],[["(\\d{6})","$1",["[2-9]"]]],0,0,"(10(?:01|[12]0|88))"],FR:["33","00","[1-9]\\d{8}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"],"0 $1"],["(\\d)(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4 $5",["[1-79]"],"0$1"]],"0"],GA:["241","00","(?:[067]\\d|11)\\d{6}|[2-7]\\d{6}",[7,8],[["(\\d)(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2-7]"],"0$1"],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["0"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["11|[67]"],"0$1"]],0,0,"0(11\\d{6}|60\\d{6}|61\\d{6}|6[256]\\d{6}|7[467]\\d{6})","$1"],GB:["44","00","[1-357-9]\\d{9}|[18]\\d{8}|8\\d{6}",[7,9,10],[["(\\d{3})(\\d{4})","$1 $2",["800","8001","80011","800111","8001111"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3",["845","8454","84546","845464"],"0$1"],["(\\d{3})(\\d{6})","$1 $2",["800"],"0$1"],["(\\d{5})(\\d{4,5})","$1 $2",["1(?:38|5[23]|69|76|94)","1(?:(?:38|69)7|5(?:24|39)|768|946)","1(?:3873|5(?:242|39[4-6])|(?:697|768)[347]|9467)"],"0$1"],["(\\d{4})(\\d{5,6})","$1 $2",["1(?:[2-69][02-9]|[78])"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["[25]|7(?:0|6[02-9])","[25]|7(?:0|6(?:[03-9]|2[356]))"],"0$1"],["(\\d{4})(\\d{6})","$1 $2",["7"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[1389]"],"0$1"]],"0",0,"0|180020",0,0,0,[["(?:1(?:1(?:3(?:[0-58]\\d\\d|73[0-5])|4(?:(?:[0-5]\\d|70)\\d|69[7-9])|(?:(?:5[0-26-9]|[78][0-49])\\d|6(?:[0-4]\\d|5[01]))\\d)|(?:2(?:(?:0[024-9]|2[3-9]|3[3-79]|4[1-689]|[58][02-9]|6[0-47-9]|7[013-9]|9\\d)\\d|1(?:[0-7]\\d|8[0-3]))|(?:3(?:0\\d|1[0-8]|[25][02-9]|3[02-579]|[468][0-46-9]|7[1-35-79]|9[2-578])|4(?:0[03-9]|[137]\\d|[28][02-57-9]|4[02-69]|5[0-8]|[69][0-79])|5(?:0[1-35-9]|[16]\\d|2[024-9]|3[015689]|4[02-9]|5[03-9]|7[0-35-9]|8[0-468]|9[0-57-9])|6(?:0[034689]|1\\d|2[0-35689]|[38][013-9]|4[1-467]|5[0-69]|6[13-9]|7[0-8]|9[0-24578])|7(?:0[0246-9]|2\\d|3[0236-8]|4[03-9]|5[0-46-9]|6[013-9]|7[0-35-9]|8[024-9]|9[02-9])|8(?:0[35-9]|2[1-57-9]|3[02-578]|4[0-578]|5[124-9]|6[2-69]|7\\d|8[02-9]|9[02569])|9(?:0[02-589]|[18]\\d|2[02-689]|3[1-57-9]|4[2-9]|5[0-579]|6[2-47-9]|7[0-24578]|9[2-57]))\\d)\\d)|2(?:0[013478]|3[0189]|4[017]|8[0-46-9]|9[0-2])\\d{3})\\d{4}|1(?:2(?:0(?:46[1-4]|87[2-9])|545[1-79]|76(?:2\\d|3[1-8]|6[1-6])|9(?:7(?:2[0-4]|3[2-5])|8(?:2[2-8]|7[0-47-9]|8[3-5])))|3(?:6(?:38[2-5]|47[23])|8(?:47[04-9]|64[0157-9]))|4(?:044[1-7]|20(?:2[23]|8\\d)|6(?:0(?:30|5[2-57]|6[1-8]|7[2-8])|140)|8(?:052|87[1-3]))|5(?:2(?:4(?:3[2-79]|6\\d)|76\\d)|6(?:26[06-9]|686))|6(?:06(?:4\\d|7[4-79])|295[5-7]|35[34]\\d|47(?:24|61)|59(?:5[08]|6[67]|74)|9(?:55[0-4]|77[23]))|7(?:26(?:6[13-9]|7[0-7])|(?:442|688)\\d|50(?:2[0-3]|[3-68]2|76))|8(?:27[56]\\d|37(?:5[2-5]|8[239])|843[2-58])|9(?:0(?:0(?:6[1-8]|85)|52\\d)|3583|4(?:66[1-8]|9(?:2[01]|81))|63(?:23|3[1-4])|9561))\\d{3}",[9,10]],["7(?:457[0-57-9]|700[01]|911[028])\\d{5}|7(?:[1-3]\\d\\d|4(?:[0-46-9]\\d|5[0-689])|5(?:0[0-8]|[13-9]\\d|2[0-35-9])|7(?:0[1-9]|[1-7]\\d|8[02-9]|9[0-689])|8(?:[014-9]\\d|[23][0-8])|9(?:[024-9]\\d|1[02-9]|3[0-689]))\\d{6}",[10]],["80[08]\\d{7}|800\\d{6}|8001111"],["(?:8(?:4[2-5]|7[0-3])|9(?:[01]\\d|8[2-49]))\\d{7}|845464\\d",[7,10]],["70\\d{8}",[10]],0,["(?:3[0347]|55)\\d{8}",[10]],["76(?:464|652)\\d{5}|76(?:0[0-28]|2[356]|34|4[01347]|5[49]|6[0-369]|77|8[14]|9[139])\\d{6}",[10]],["56\\d{8}",[10]]],0," x"],GD:["1","011","(?:473|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","473$1",0,"473"],GE:["995","00","(?:[3-57]\\d\\d|800)\\d{6}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["70"],"0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["32"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[57]"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[348]"],"0$1"]],"0"],GF:["594","00","(?:[56]94\\d|7093)\\d{5}|(?:80|9\\d)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-7]|9[47]"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[89]"],"0$1"]],"0"],GG:["44","00","(?:1481|[357-9]\\d{3})\\d{6}|8\\d{6}(?:\\d{2})?",[7,9,10],0,"0",0,"([25-9]\\d{5})$|0|180020","1481$1",0,0,[["1481[25-9]\\d{5}",[10]],["7(?:(?:781|839)\\d|911[17])\\d{5}",[10]],["80[08]\\d{7}|800\\d{6}|8001111"],["(?:8(?:4[2-5]|7[0-3])|9(?:[01]\\d|8[0-3]))\\d{7}|845464\\d",[7,10]],["70\\d{8}",[10]],0,["(?:3[0347]|55)\\d{8}",[10]],["76(?:464|652)\\d{5}|76(?:0[0-28]|2[356]|34|4[01347]|5[49]|6[0-369]|77|8[14]|9[139])\\d{6}",[10]],["56\\d{8}",[10]]]],GH:["233","00","(?:[235]\\d{3}|800)\\d{5}",[8,9],[["(\\d{3})(\\d{5})","$1 $2",["8"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[235]"],"0$1"]],"0"],GI:["350","00","(?:[25]\\d|60)\\d{6}",[8],[["(\\d{3})(\\d{5})","$1 $2",["2"]]]],GL:["299","00","(?:19|[2-689]\\d|70)\\d{4}",[6],[["(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3",["19|[2-9]"]]]],GM:["220","00","[2-9]\\d{6}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[2-9]"]]]],GN:["224","00","722\\d{6}|(?:3|6\\d)\\d{7}",[8,9],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["3"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[67]"]]]],GP:["590","00","(?:590\\d|7090)\\d{5}|(?:69|80|9\\d)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-79]"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"],"0$1"]],"0",0,0,0,0,0,[["590(?:0[1-68]|[14][0-24-9]|2[0-68]|3[1-9]|5[3-579]|[68][0-689]|7[08]|9\\d)\\d{4}"],["(?:69(?:0\\d\\d|1(?:2[2-9]|3[0-5])|4(?:0[89]|1[2-6]|9\\d)|6(?:1[016-9]|5[0-4]|[67]\\d))|7090[0-4])\\d{4}"],["80[0-5]\\d{6}"],0,0,0,0,0,["9(?:(?:39[5-7]|76[018])\\d|475[0-6])\\d{4}"]]],GQ:["240","00","222\\d{6}|(?:3\\d|55|[89]0)\\d{7}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[235]"]],["(\\d{3})(\\d{6})","$1 $2",["[89]"]]]],GR:["30","00","5005000\\d{3}|8\\d{9,11}|(?:[269]\\d|70)\\d{8}",[10,11,12],[["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["21|7"]],["(\\d{4})(\\d{6})","$1 $2",["2(?:2|3[2-57-9]|4[2-469]|5[2-59]|6[2-9]|7[2-69]|8[2-49])|5"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[2689]"]],["(\\d{3})(\\d{3,4})(\\d{5})","$1 $2 $3",["8"]]]],GT:["502","00","80\\d{6}|(?:1\\d{3}|[2-7])\\d{7}",[8,11],[["(\\d{4})(\\d{4})","$1 $2",["[2-8]"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["1"]]]],GU:["1","011","(?:[58]\\d\\d|671|900)\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","671$1",0,"671"],GW:["245","00","[49]\\d{8}|4\\d{6}",[7,9],[["(\\d{3})(\\d{4})","$1 $2",["40"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[49]"]]]],GY:["592","001","(?:[2-8]\\d{3}|9008)\\d{3}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[2-9]"]]]],HK:["852","00(?:30|5[09]|[126-9]?)","8[0-46-9]\\d{6,7}|9\\d{4,7}|(?:[2-7]|9\\d{3})\\d{7}",[5,6,7,8,9,11],[["(\\d{3})(\\d{2,5})","$1 $2",["900","9003"]],["(\\d{4})(\\d{4})","$1 $2",["[2-7]|8[1-4]|9(?:0[1-9]|[1-8])"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["8"]],["(\\d{3})(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3 $4",["9"]]],0,0,0,0,0,0,0,"00"],HN:["504","00","8\\d{10}|[237-9]\\d{7}",[8,11],[["(\\d{4})(\\d{4})","$1-$2",["[237-9]"]]]],HR:["385","00","[2-69]\\d{8}|80\\d{5,7}|[1-79]\\d{7}|6\\d{6}",[7,8,9],[["(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3",["6[01]"],"0$1"],["(\\d{3})(\\d{2})(\\d{2,3})","$1 $2 $3",["8"],"0$1"],["(\\d)(\\d{4})(\\d{3})","$1 $2 $3",["1"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["6|7[245]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["9"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[2-57]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["8"],"0$1"]],"0"],HT:["509","00","[2-589]\\d{7}",[8],[["(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3",["[2-589]"]]]],HU:["36","00","[235-7]\\d{8}|[1-9]\\d{7}",[8,9],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["1"],"(06 $1)"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[27][2-9]|3[2-7]|4[24-9]|5[2-79]|6|8[2-57-9]|9[2-69]"],"(06 $1)"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[2-9]"],"06 $1"]],"06"],ID:["62","00[89]","00[1-9]\\d{9,14}|(?:[1-36]|8\\d{5})\\d{6}|00\\d{9}|[1-9]\\d{8,10}|[2-9]\\d{7}",[7,8,9,10,11,12,13,14,15,16,17],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["15"]],["(\\d{2})(\\d{5,9})","$1 $2",["2[124]|[36]1"],"(0$1)"],["(\\d{3})(\\d{5,7})","$1 $2",["800"],"0$1"],["(\\d{3})(\\d{5,8})","$1 $2",["[2-79]"],"(0$1)"],["(\\d{3})(\\d{3,4})(\\d{3})","$1-$2-$3",["8[1-35-9]"],"0$1"],["(\\d{3})(\\d{6,8})","$1 $2",["1"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["804"],"0$1"],["(\\d{3})(\\d)(\\d{3})(\\d{3})","$1 $2 $3 $4",["80"],"0$1"],["(\\d{3})(\\d{4})(\\d{4,5})","$1-$2-$3",["8"],"0$1"]],"0"],IE:["353","00","(?:1\\d|[2569])\\d{6,8}|4\\d{6,9}|7\\d{8}|8\\d{8,9}",[7,8,9,10],[["(\\d{2})(\\d{5})","$1 $2",["2[24-9]|47|58|6[237-9]|9[35-9]"],"(0$1)"],["(\\d{3})(\\d{5})","$1 $2",["[45]0"],"(0$1)"],["(\\d)(\\d{3,4})(\\d{4})","$1 $2 $3",["1"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[2569]|4[1-69]|7[14]"],"(0$1)"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["70"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["81"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[78]"],"0$1"],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1"]],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["4"],"(0$1)"],["(\\d{2})(\\d)(\\d{3})(\\d{4})","$1 $2 $3 $4",["8"],"0$1"]],"0"],IL:["972","0(?:0|1[2-9])","1\\d{6}(?:\\d{3,5})?|[57]\\d{8}|[1-489]\\d{7}",[7,8,9,10,11,12],[["(\\d{4})(\\d{3})","$1-$2",["125"]],["(\\d{4})(\\d{2})(\\d{2})","$1-$2-$3",["121"]],["(\\d)(\\d{3})(\\d{4})","$1-$2-$3",["[2-489]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1-$2-$3",["[57]"],"0$1"],["(\\d{4})(\\d{3})(\\d{3})","$1-$2-$3",["12"]],["(\\d{4})(\\d{6})","$1-$2",["159"]],["(\\d)(\\d{3})(\\d{3})(\\d{3})","$1-$2-$3-$4",["1[7-9]"]],["(\\d{3})(\\d{1,2})(\\d{3})(\\d{4})","$1-$2 $3-$4",["15"]]],"0"],IM:["44","00","1624\\d{6}|(?:[3578]\\d|90)\\d{8}",[10],0,"0",0,"([25-8]\\d{5})$|0|180020","1624$1",0,"74576|(?:16|7[56])24"],IN:["91","00","(?:000800|[2-9]\\d\\d)\\d{7}|1\\d{7,12}",[8,9,10,11,12,13],[["(\\d{8})","$1",["5(?:0|2[23]|3[03]|[67]1|88)","5(?:0|2(?:21|3)|3(?:0|3[23])|616|717|888)","5(?:0|2(?:21|3)|3(?:0|3[23])|616|717|8888)"],0,1],["(\\d{4})(\\d{4,5})","$1 $2",["180","1800"],0,1],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["140"],0,1],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["11|2[02]|33|4[04]|79[1-7]|80[2-46]","11|2[02]|33|4[04]|79(?:[1-6]|7[19])|80(?:[2-4]|6[0-589])","11|2[02]|33|4[04]|79(?:[124-6]|3(?:[02-9]|1[0-24-9])|7(?:1|9[1-6]))|80(?:[2-4]|6[0-589])"],"0$1",1],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["1(?:2[0-249]|3[0-25]|4[145]|[68]|7[1257])|2(?:1[257]|3[013]|4[01]|5[0137]|6[0158]|78|8[1568])|3(?:26|4[1-3]|5[34]|6[01489]|7[02-46]|8[159])|4(?:1[36]|2[1-47]|5[12]|6[0-26-9]|7[0-24-9]|8[013-57]|9[014-7])|5(?:1[025]|22|[36][25]|4[28]|5[12]|[78]1)|6(?:12|[2-4]1|5[17]|6[13]|80)|7(?:12|3[134]|4[47]|61|88)|8(?:16|2[014]|3[126]|6[136]|7[078]|8[34]|91)|(?:43|59|75)[15]|(?:1[59]|29|67|72)[14]","1(?:2[0-24]|3[0-25]|4[145]|[59][14]|6[1-9]|7[1257]|8[1-57-9])|2(?:1[257]|3[013]|4[01]|5[0137]|6[058]|78|8[1568]|9[14])|3(?:26|4[1-3]|5[34]|6[01489]|7[02-46]|8[159])|4(?:1[36]|2[1-47]|3[15]|5[12]|6[0-26-9]|7[0-24-9]|8[013-57]|9[014-7])|5(?:1[025]|22|[36][25]|4[28]|[578]1|9[15])|674|7(?:(?:2[14]|3[34]|5[15])[2-6]|61[346]|88[0-8])|8(?:70[2-6]|84[235-7]|91[3-7])|(?:1(?:29|60|8[06])|261|552|6(?:12|[2-47]1|5[17]|6[13]|80)|7(?:12|31|4[47])|8(?:16|2[014]|3[126]|6[136]|7[78]|83))[2-7]","1(?:2[0-24]|3[0-25]|4[145]|[59][14]|6[1-9]|7[1257]|8[1-57-9])|2(?:1[257]|3[013]|4[01]|5[0137]|6[058]|78|8[1568]|9[14])|3(?:26|4[1-3]|5[34]|6[01489]|7[02-46]|8[159])|4(?:1[36]|2[1-47]|3[15]|5[12]|6[0-26-9]|7[0-24-9]|8[013-57]|9[014-7])|5(?:1[025]|22|[36][25]|4[28]|[578]1|9[15])|6(?:12(?:[2-6]|7[0-8])|74[2-7])|7(?:(?:2[14]|5[15])[2-6]|3171|61[346]|88(?:[2-7]|82))|8(?:70[2-6]|84(?:[2356]|7[19])|91(?:[3-6]|7[19]))|73[134][2-6]|(?:74[47]|8(?:16|2[014]|3[126]|6[136]|7[78]|83))(?:[2-6]|7[19])|(?:1(?:29|60|8[06])|261|552|6(?:[2-4]1|5[17]|6[13]|7(?:1|4[0189])|80)|7(?:12|88[01]))[2-7]"],"0$1",1],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1(?:[2-479]|5[0235-9])|[2-5]|6(?:1[1358]|2[2457-9]|3[2-5]|4[235-7]|5[2-689]|6[24578]|7[235689]|8[1-6])|7(?:1[013-9]|28|3[129]|4[1-35689]|5[29]|6[02-5]|70)|807","1(?:[2-479]|5[0235-9])|[2-5]|6(?:1[1358]|2(?:[2457]|84|95)|3(?:[2-4]|55)|4[235-7]|5[2-689]|6[24578]|7[235689]|8[1-6])|7(?:1(?:[013-8]|9[6-9])|28[6-8]|3(?:17|2[0-49]|9[2-57])|4(?:1[2-4]|[29][0-7]|3[0-8]|[56]|8[0-24-7])|5(?:2[1-3]|9[0-6])|6(?:0[5689]|2[5-9]|3[02-8]|4|5[0-367])|70[13-7])|807[19]","1(?:[2-479]|5(?:[0236-9]|5[013-9]))|[2-5]|6(?:2(?:84|95)|355|8(?:28[235-7]|3))|73179|807(?:1|9[1-3])|(?:1552|6(?:(?:1[1358]|2[2457]|3[2-4]|4[235-7]|5[2-689]|6[24578]|7[235689])\\d|8(?:[14-6]\\d|2[0-79]))|7(?:1(?:[013-8]\\d|9[6-9])|28[6-8]|3(?:2[0-49]|9[2-57])|4(?:1[2-4]|[29][0-7]|3[0-8]|[56]\\d|8[0-24-7])|5(?:2[1-3]|9[0-6])|6(?:0[5689]|2[5-9]|3[02-8]|4\\d|5[0-367])|70[13-7]))[2-7]"],"0$1",1],["(\\d{5})(\\d{5})","$1 $2",["[6-9]"],"0$1",1],["(\\d{4})(\\d{2,4})(\\d{4})","$1 $2 $3",["1(?:6|8[06])","1(?:6|8[06]0)"],0,1],["(\\d{4})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["18"],0,1]],"0"],IO:["246","00","3\\d{6}",[7],[["(\\d{3})(\\d{4})","$1 $2",["3"]]]],IQ:["964","00","(?:1|7\\d\\d)\\d{7}|[2-6]\\d{7,8}",[8,9,10],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["1"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[2-6]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["7"],"0$1"]],"0"],IR:["98","00","[1-9]\\d{9}|(?:[1-8]\\d\\d|9)\\d{3,4}",[4,5,6,7,10],[["(\\d{4,5})","$1",["96"],"0$1"],["(\\d{2})(\\d{4,5})","$1 $2",["(?:1[137]|2[13-68]|3[1458]|4[145]|5[1468]|6[16]|7[1467]|8[13467])[12689]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["9"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["[1-8]"],"0$1"]],"0"],IS:["354","00|1(?:0(?:01|[12]0)|100)","(?:38\\d|[4-9])\\d{6}",[7,9],[["(\\d{3})(\\d{4})","$1 $2",["[4-9]"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["3"]]],0,0,0,0,0,0,0,"00"],IT:["39","00","0\\d{5,11}|1\\d{8,10}|3(?:[0-8]\\d{7,10}|9\\d{7,8})|(?:43|55|70)\\d{8}|8\\d{5}(?:\\d{2,4})?",[6,7,8,9,10,11,12],[["(\\d{2})(\\d{4,6})","$1 $2",["0[26]"]],["(\\d{3})(\\d{3,6})","$1 $2",["0[13-57-9][0159]|8(?:03|4[17]|9[2-5])","0[13-57-9][0159]|8(?:03|4[17]|9(?:2|3[04]|[45][0-4]))"]],["(\\d{4})(\\d{2,6})","$1 $2",["0(?:[13-579][2-46-8]|8[236-8])"]],["(\\d{4})(\\d{4})","$1 $2",["894"]],["(\\d{2})(\\d{3,4})(\\d{4})","$1 $2 $3",["0[26]|5"]],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["1(?:44|[679])|[378]|43"]],["(\\d{3})(\\d{3,4})(\\d{4})","$1 $2 $3",["0[13-57-9][0159]|14"]],["(\\d{2})(\\d{4})(\\d{5})","$1 $2 $3",["0[26]"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["0"]],["(\\d{3})(\\d{4})(\\d{4,5})","$1 $2 $3",["[03]"]]],0,0,0,0,0,0,[["0(?:669[0-79]\\d{1,6}|831\\d{2,8})|0(?:1(?:[0159]\\d|[27][1-5]|31|4[1-4]|6[1356]|8[2-57])|2\\d\\d|3(?:[0159]\\d|2[1-4]|3[12]|[48][1-6]|6[2-59]|7[1-7])|4(?:[0159]\\d|[23][1-9]|4[245]|6[1-5]|7[1-4]|81)|5(?:[0159]\\d|2[1-5]|3[2-6]|4[1-79]|6[4-6]|7[1-578]|8[3-8])|6(?:[0-57-9]\\d|6[0-8])|7(?:[0159]\\d|2[12]|3[1-7]|4[2-46]|6[13569]|7[13-6]|8[1-59])|8(?:[0159]\\d|2[3-578]|3[2356]|[6-8][1-5])|9(?:[0159]\\d|[238][1-5]|4[12]|6[1-8]|7[1-6]))\\d{2,7}"],["3[2-9]\\d{7,8}|(?:31|43)\\d{8}",[9,10]],["80(?:0\\d{3}|3)\\d{3}",[6,9]],["(?:0878\\d{3}|89(?:2\\d|3[04]|4(?:[0-4]|[5-9]\\d\\d)|5[0-4]))\\d\\d|(?:1(?:44|6[346])|89(?:38|5[5-9]|9))\\d{6}",[6,8,9,10]],["1(?:78\\d|99)\\d{6}",[9,10]],["3[2-8]\\d{9,10}",[11,12]],0,0,["55\\d{8}",[10]],["84(?:[08]\\d{3}|[17])\\d{3}",[6,9]]]],JE:["44","00","1534\\d{6}|(?:[3578]\\d|90)\\d{8}",[10],0,"0",0,"([0-24-8]\\d{5})$|0|180020","1534$1",0,0,[["1534[0-24-8]\\d{5}"],["7(?:(?:(?:50|82)9|937)\\d|7(?:00[378]|97\\d))\\d{5}"],["80(?:07(?:35|81)|8901)\\d{4}"],["(?:8(?:4(?:4(?:4(?:05|42|69)|703)|5(?:041|800))|7(?:0002|1206))|90(?:066[59]|1810|71(?:07|55)))\\d{4}"],["701511\\d{4}"],0,["(?:3(?:0(?:07(?:35|81)|8901)|3\\d{4}|4(?:4(?:4(?:05|42|69)|703)|5(?:041|800))|7(?:0002|1206))|55\\d{4})\\d{4}"],["76(?:464|652)\\d{5}|76(?:0[0-28]|2[356]|34|4[01347]|5[49]|6[0-369]|77|8[14]|9[139])\\d{6}"],["56\\d{8}"]]],JM:["1","011","(?:[58]\\d\\d|658|900)\\d{7}",[10],0,"1",0,0,0,0,"658|876"],JO:["962","00","(?:(?:[2689]|7\\d)\\d|32|427|53)\\d{6}",[8,9],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["[2356]|87"],"(0$1)"],["(\\d{3})(\\d{5,6})","$1 $2",["[89]"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["70"],"0$1"],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["[47]"],"0$1"]],"0"],JP:["81","010","00[1-9]\\d{6,14}|[25-9]\\d{9}|(?:00|[1-9]\\d\\d)\\d{6}",[8,9,10,11,12,13,14,15,16,17],[["(\\d{3})(\\d{3})(\\d{3})","$1-$2-$3",["(?:12|57|99)0"],"0$1"],["(\\d{4})(\\d)(\\d{4})","$1-$2-$3",["1(?:26|3[79]|4[56]|5[4-68]|6[3-5])|499|5(?:76|97)|746|8(?:3[89]|47|51)|9(?:80|9[16])","1(?:267|3(?:7[247]|9[278])|466|5(?:47|58|64)|6(?:3[245]|48|5[4-68]))|499[2468]|5(?:76|97)9|7468|8(?:3(?:8[7-9]|96)|477|51[2-9])|9(?:802|9(?:1[23]|69))|1(?:45|58)[67]","1(?:267|3(?:7[247]|9[278])|466|5(?:47|58|64)|6(?:3[245]|48|5[4-68]))|499[2468]|5(?:769|979[2-69])|7468|8(?:3(?:8[7-9]|96[2457-9])|477|51[2-9])|9(?:802|9(?:1[23]|69))|1(?:45|58)[67]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1-$2-$3",["60"],"0$1"],["(\\d)(\\d{4})(\\d{4})","$1-$2-$3",["3|4(?:2[09]|7[01])|6[1-9]","3|4(?:2(?:0|9[02-69])|7(?:0[019]|1))|6[1-9]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1-$2-$3",["1(?:1|5[45]|77|88|9[69])|2(?:2[1-37]|3[0-269]|4[59]|5|6[24]|7[1-358]|8[1369]|9[0-38])|4(?:[28][1-9]|3[0-57]|[45]|6[248]|7[2-579]|9[29])|5(?:2|3[0459]|4[0-369]|5[29]|8[02389]|9[0-389])|7(?:2[02-46-9]|34|[58]|6[0249]|7[57]|9[2-6])|8(?:2[124589]|3[26-9]|49|51|6|7[0-468]|8[68]|9[019])|9(?:[23][1-9]|4[15]|5[138]|6[1-3]|7[156]|8[189]|9[1-489])","1(?:1|5(?:4[018]|5[017])|77|88|9[69])|2(?:2(?:[127]|3[014-9])|3[0-269]|4[59]|5(?:[1-3]|5[0-69]|9[19])|62|7(?:[1-35]|8[0189])|8(?:[16]|3[0134]|9[0-5])|9(?:[028]|17))|4(?:2(?:[13-79]|8[014-6])|3[0-57]|[45]|6[248]|7[2-47]|8[1-9]|9[29])|5(?:2|3(?:[045]|9[0-8])|4[0-369]|5[29]|8[02389]|9[0-3])|7(?:2[02-46-9]|34|[58]|6[0249]|7[57]|9(?:[23]|4[0-59]|5[01569]|6[0167]))|8(?:2(?:[1258]|4[0-39]|9[0-2469])|3(?:[29]|60)|49|51|6(?:[0-24]|36|5[0-3589]|7[23]|9[01459])|7[0-468]|8[68])|9(?:[23][1-9]|4[15]|5[138]|6[1-3]|7[156]|8[189]|9(?:[1289]|3[34]|4[0178]))|(?:264|837)[016-9]|2(?:57|93)[015-9]|(?:25[0468]|422|838)[01]|(?:47[59]|59[89]|8(?:6[68]|9))[019]","1(?:1|5(?:4[018]|5[017])|77|88|9[69])|2(?:2[127]|3[0-269]|4[59]|5(?:[1-3]|5[0-69]|9(?:17|99))|6(?:2|4[016-9])|7(?:[1-35]|8[0189])|8(?:[16]|3[0134]|9[0-5])|9(?:[028]|17))|4(?:2(?:[13-79]|8[014-6])|3[0-57]|[45]|6[248]|7[2-47]|9[29])|5(?:2|3(?:[045]|9(?:[0-58]|6[4-9]|7[0-35689]))|4[0-369]|5[29]|8[02389]|9[0-3])|7(?:2[02-46-9]|34|[58]|6[0249]|7[57]|9(?:[23]|4[0-59]|5[01569]|6[0167]))|8(?:2(?:[1258]|4[0-39]|9[0169])|3(?:[29]|60|7(?:[017-9]|6[6-8]))|49|51|6(?:[0-24]|36[2-57-9]|5(?:[0-389]|5[23])|6(?:[01]|9[178])|7(?:2[2-468]|3[78])|9[0145])|7[0-468]|8[68])|9(?:4[15]|5[138]|7[156]|8[189]|9(?:[1289]|3(?:31|4[357])|4[0178]))|(?:8294|96)[1-3]|2(?:57|93)[015-9]|(?:223|8699)[014-9]|(?:25[0468]|422|838)[01]|(?:48|8292|9[23])[1-9]|(?:47[59]|59[89]|8(?:68|9))[019]"],"0$1"],["(\\d{3})(\\d{2})(\\d{4})","$1-$2-$3",["[14]|[289][2-9]|5[3-9]|7[2-4679]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1-$2-$3",["800"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1-$2-$3",["[25-9]"],"0$1"]],"0",0,"(000[2569]\\d{4,6})$|(?:(?:003768)0?)|0","$1"],KE:["254","000","(?:[17]\\d\\d|900)\\d{6}|(?:2|80)0\\d{6,7}|[4-6]\\d{6,8}",[7,8,9,10],[["(\\d{2})(\\d{5,7})","$1 $2",["[24-6]"],"0$1"],["(\\d{3})(\\d{6})","$1 $2",["[17]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["[89]"],"0$1"]],"0"],KG:["996","00","8\\d{9}|[235-9]\\d{8}",[9,10],[["(\\d{4})(\\d{5})","$1 $2",["3(?:1[346]|[24-79])"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[235-79]|88"],"0$1"],["(\\d{3})(\\d{3})(\\d)(\\d{2,3})","$1 $2 $3 $4",["8"],"0$1"]],"0"],KH:["855","00[14-9]","1\\d{9}|[1-9]\\d{7,8}",[8,9,10],[["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[1-9]"],"0$1"],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1"]]],"0"],KI:["686","00","(?:[37]\\d|6[0-79])\\d{6}|(?:[2-48]\\d|50)\\d{3}",[5,8],0,"0"],KM:["269","00","[3478]\\d{6}",[7],[["(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3",["[3478]"]]]],KN:["1","011","(?:[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-7]\\d{6})$|1","869$1",0,"869"],KP:["850","00|99","85\\d{6}|(?:19\\d|[2-7])\\d{7}",[8,10],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["8"],"0$1"],["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["[2-7]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["1"],"0$1"]],"0"],KR:["82","00(?:[125689]|3(?:[46]5|91)|7(?:00|27|3|55|6[126]))","00[1-9]\\d{8,11}|(?:[12]|5\\d{3})\\d{7}|[13-6]\\d{9}|(?:[1-6]\\d|80)\\d{7}|[3-6]\\d{4,5}|(?:00|7)0\\d{8}",[5,6,8,9,10,11,12,13,14],[["(\\d{2})(\\d{3,4})","$1-$2",["(?:3[1-3]|[46][1-4]|5[1-5])1"],"0$1"],["(\\d{4})(\\d{4})","$1-$2",["1"]],["(\\d)(\\d{3,4})(\\d{4})","$1-$2-$3",["2"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1-$2-$3",["[36]0|8"],"0$1"],["(\\d{2})(\\d{3,4})(\\d{4})","$1-$2-$3",["[1346]|5[1-5]"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1-$2-$3",["[57]"],"0$1"],["(\\d{2})(\\d{5})(\\d{4})","$1-$2-$3",["5"],"0$1"]],"0",0,"0(8(?:[1-46-8]|5\\d\\d))?"],KW:["965","00","18\\d{5}|(?:[2569]\\d|41)\\d{6}",[7,8],[["(\\d{4})(\\d{3,4})","$1 $2",["[169]|2(?:[235]|4[1-35-9])|52"]],["(\\d{3})(\\d{5})","$1 $2",["[245]"]]]],KY:["1","011","(?:345|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","345$1",0,"345"],KZ:["7","810","(?:33622|8\\d{8})\\d{5}|[78]\\d{9}",[10,14],0,"8",0,0,0,0,"33622|7",0,"8~10"],LA:["856","00","[23]\\d{9}|3\\d{8}|(?:[235-8]\\d|41)\\d{6}",[8,9,10],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["2[13]|3[14]|[4-8]"],"0$1"],["(\\d{2})(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3 $4",["3"],"0$1"],["(\\d{2})(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3 $4",["[23]"],"0$1"]],"0"],LB:["961","00","[27-9]\\d{7}|[13-9]\\d{6}",[7,8],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["[13-69]|7(?:[2-57]|62|8[0-6]|9[04-9])|8[02-9]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[27-9]"]]],"0"],LC:["1","011","(?:[58]\\d\\d|758|900)\\d{7}",[10],0,"1",0,"([2-8]\\d{6})$|1","758$1",0,"758"],LI:["423","00","[68]\\d{8}|(?:[2378]\\d|90)\\d{5}",[7,9],[["(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3",["[2379]|8(?:0[09]|7)","[2379]|8(?:0(?:02|9)|7)"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["8"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["69"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["6"]]],"0",0,"(1001)|0"],LK:["94","00","[1-9]\\d{8}",[9],[["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["7"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[1-689]"],"0$1"]],"0"],LR:["231","00","(?:[2457]\\d|33|88)\\d{7}|(?:2\\d|[4-6])\\d{6}",[7,8,9],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["4[67]|[56]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["2"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[2-578]"],"0$1"]],"0"],LS:["266","00","(?:[256]\\d\\d|800)\\d{5}",[8],[["(\\d{4})(\\d{4})","$1 $2",["[2568]"]]]],LT:["370","00","(?:[3469]\\d|52|[78]0)\\d{6}",[8],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["52[0-7]"],"(0-$1)",1],["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["[7-9]"],"0 $1",1],["(\\d{2})(\\d{6})","$1 $2",["37|4(?:[15]|6[1-8])"],"(0-$1)",1],["(\\d{3})(\\d{5})","$1 $2",["[3-6]"],"(0-$1)",1]],"0",0,"[08]"],LU:["352","00","35[013-9]\\d{4,8}|6\\d{8}|35\\d{2,4}|(?:[2457-9]\\d|3[0-46-9])\\d{2,9}",[4,5,6,7,8,9,10,11],[["(\\d{2})(\\d{3})","$1 $2",["2(?:0[2-689]|[2-9])|[3-57]|8(?:0[2-9]|[13-9])|9(?:0[89]|[2-579])"]],["(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3",["2(?:0[2-689]|[2-9])|[3-57]|8(?:0[2-9]|[13-9])|9(?:0[89]|[2-579])"]],["(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3",["20[2-689]"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{1,2})","$1 $2 $3 $4",["2(?:[0367]|4[3-8])"]],["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["80[01]|90[015]"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3 $4",["20"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["6"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{1,2})","$1 $2 $3 $4 $5",["2(?:[0367]|4[3-8])"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{1,5})","$1 $2 $3 $4",["[3-57]|8[13-9]|9(?:0[89]|[2-579])|(?:2|80)[2-9]"]]],0,0,"(15(?:0[06]|1[12]|[35]5|4[04]|6[26]|77|88|99)\\d)"],LV:["371","00","(?:[268]\\d|78|90)\\d{6}",[8],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[2679]|8[01]"]]]],LY:["218","00","[2-9]\\d{8}",[9],[["(\\d{2})(\\d{7})","$1-$2",["[2-9]"],"0$1"]],"0"],MA:["212","00","[5-8]\\d{8}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["5[45]"],"0$1"],["(\\d{4})(\\d{5})","$1-$2",["5(?:[19]|2[2-46-9]|3[3-9])|8(?:0[89]|92)"],"0$1"],["(\\d{2})(\\d{7})","$1-$2",["8"],"0$1"],["(\\d{3})(\\d{6})","$1-$2",["[5-7]"],"0$1"]],"0",0,0,0,0,0,[["5(?:(?:18|4[0679]|5[03])\\d|2(?:[0-25-79]\\d|3[1-578]|4[02-46-8]|8[0235-7])|3(?:[0-47]\\d|5[02-9]|6[02-8]|8[014-9]|9[3-9]))\\d{5}"],["(?:6(?:[0-79]\\d|8[0-247-9])|7(?:[016-8]\\d|2[0-8]|5[0-5]))\\d{6}"],["80[0-7]\\d{6}"],["89\\d{7}"],0,0,0,0,["(?:592(?:4[0-2]|93)|80[89]\\d\\d)\\d{4}"]]],MC:["377","00","(?:[3489]|[67]\\d)\\d{7}",[8,9],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["4"],"0$1"],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[389]"]],["(\\d)(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4 $5",["[67]"],"0$1"]],"0"],MD:["373","00","(?:[235-7]\\d|[89]0)\\d{6}",[8],[["(\\d{3})(\\d{5})","$1 $2",["[89]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["22|3"],"0$1"],["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["[25-7]"],"0$1"]],"0"],ME:["382","00","(?:20|[3-79]\\d)\\d{6}|80\\d{6,7}",[8,9],[["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[2-9]"],"0$1"]],"0"],MF:["590","00","(?:590\\d|7090)\\d{5}|(?:69|80|9\\d)\\d{7}",[9],0,"0",0,0,0,0,0,[["590(?:0[079]|[14]3|[27][79]|3[03-7]|5[0-268]|87)\\d{4}"],["(?:69(?:0\\d\\d|1(?:2[2-9]|3[0-5])|4(?:0[89]|1[2-6]|9\\d)|6(?:1[016-9]|5[0-4]|[67]\\d))|7090[0-4])\\d{4}"],["80[0-5]\\d{6}"],0,0,0,0,0,["9(?:(?:39[5-7]|76[018])\\d|475[0-6])\\d{4}"]]],MG:["261","00","[23]\\d{8}",[9],[["(\\d{2})(\\d{2})(\\d{3})(\\d{2})","$1 $2 $3 $4",["[23]"],"0$1"]],"0",0,"([24-9]\\d{6})$|0","20$1"],MH:["692","011","329\\d{4}|(?:[256]\\d|45)\\d{5}",[7],[["(\\d{3})(\\d{4})","$1-$2",["[2-6]"]]],"1"],MK:["389","00","[2-578]\\d{7}",[8],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["2|34[47]|4(?:[37]7|5[47]|64)"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[347]"],"0$1"],["(\\d{3})(\\d)(\\d{2})(\\d{2})","$1 $2 $3 $4",["[58]"],"0$1"]],"0"],ML:["223","00","[24-9]\\d{7}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[24-9]"]]]],MM:["95","00","1\\d{5,7}|95\\d{6}|(?:[4-7]|9[0-46-9])\\d{6,8}|(?:2|8\\d)\\d{5,8}",[6,7,8,9,10],[["(\\d)(\\d{2})(\\d{3})","$1 $2 $3",["16|2"],"0$1"],["(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3",["4(?:[2-46]|5[3-5])|5|6(?:[1-689]|7[235-7])|7(?:[0-4]|5[2-7])|8[1-5]|(?:60|86)[23]"],"0$1"],["(\\d)(\\d{3})(\\d{3,4})","$1 $2 $3",["[12]|452|678|86","[12]|452|6788|86"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[4-7]|8[1-35]"],"0$1"],["(\\d)(\\d{3})(\\d{4,6})","$1 $2 $3",["9(?:2[0-4]|[35-9]|4[137-9])"],"0$1"],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["2"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["8"],"0$1"],["(\\d)(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["92"],"0$1"],["(\\d)(\\d{5})(\\d{4})","$1 $2 $3",["9"],"0$1"]],"0"],MN:["976","001","[12]\\d{7,9}|[5-9]\\d{7}",[8,9,10],[["(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3",["[12]1"],"0$1"],["(\\d{4})(\\d{4})","$1 $2",["[5-9]"]],["(\\d{3})(\\d{5,6})","$1 $2",["[12]2[1-3]"],"0$1"],["(\\d{4})(\\d{5,6})","$1 $2",["[12](?:27|3[2-8]|4[2-68]|5[1-4689])","[12](?:27|3[2-8]|4[2-68]|5[1-4689])[0-3]"],"0$1"],["(\\d{5})(\\d{4,5})","$1 $2",["[12]"],"0$1"]],"0"],MO:["853","00","0800\\d{3}|(?:28|[68]\\d)\\d{6}",[7,8],[["(\\d{4})(\\d{3})","$1 $2",["0"]],["(\\d{4})(\\d{4})","$1 $2",["[268]"]]]],MP:["1","011","[58]\\d{9}|(?:67|90)0\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","670$1",0,"670"],MQ:["596","00","(?:596\\d|7091)\\d{5}|(?:69|[89]\\d)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-79]|8(?:0[6-9]|[36])"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"],"0$1"]],"0"],MR:["222","00","(?:[2-4]\\d\\d|800)\\d{5}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2-48]"]]]],MS:["1","011","(?:[58]\\d\\d|664|900)\\d{7}",[10],0,"1",0,"([34]\\d{6})$|1","664$1",0,"664"],MT:["356","00","3550\\d{4}|(?:[2579]\\d\\d|800)\\d{5}",[8],[["(\\d{4})(\\d{4})","$1 $2",["[2357-9]"]]]],MU:["230","0(?:0|[24-7]0|3[03])","(?:[57]|8\\d\\d)\\d{7}|[2-468]\\d{6}",[7,8,10],[["(\\d{3})(\\d{4})","$1 $2",["[2-46]|8[013]"]],["(\\d{4})(\\d{4})","$1 $2",["[57]"]],["(\\d{5})(\\d{5})","$1 $2",["8"]]],0,0,0,0,0,0,0,"020"],MV:["960","0(?:0|19)","(?:800|9[0-57-9]\\d)\\d{7}|[34679]\\d{6}",[7,10],[["(\\d{3})(\\d{4})","$1-$2",["[34679]"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[89]"]]],0,0,0,0,0,0,0,"00"],MW:["265","00","(?:[1289]\\d|31|77)\\d{7}|1\\d{6}",[7,9],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["1[2-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["2"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[137-9]"],"0$1"]],"0"],MX:["52","0[09]","[2-9]\\d{9}",[10],[["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["33|5[56]|81"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[2-9]"]]],0,0,0,0,0,0,0,"00"],MY:["60","00","1\\d{8,9}|(?:3\\d|[4-9])\\d{7}",[8,9,10],[["(\\d)(\\d{3})(\\d{4})","$1-$2 $3",["[4-79]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1-$2 $3",["1(?:[02469]|[378][1-9]|53)|8","1(?:[02469]|[37][1-9]|53|8(?:[1-46-9]|5[7-9]))|8"],"0$1"],["(\\d)(\\d{4})(\\d{4})","$1-$2 $3",["3"],"0$1"],["(\\d)(\\d{3})(\\d{2})(\\d{4})","$1-$2-$3-$4",["1(?:[367]|80)"]],["(\\d{3})(\\d{3})(\\d{4})","$1-$2 $3",["15"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1-$2 $3",["1"],"0$1"]],"0"],MZ:["258","00","(?:2|8\\d)\\d{7}",[8,9],[["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["2|8[2-79]"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["8"]]]],NA:["264","00","[68]\\d{7,8}",[8,9],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["88"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["6"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["87"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["8"],"0$1"]],"0"],NC:["687","00","(?:050|[2-57-9]\\d\\d)\\d{3}",[6],[["(\\d{2})(\\d{2})(\\d{2})","$1.$2.$3",["[02-57-9]"]]]],NE:["227","00","[027-9]\\d{7}",[8],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["08"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[089]|2[013]|7[0467]"]]]],NF:["672","00","[13]\\d{5}",[6],[["(\\d{2})(\\d{4})","$1 $2",["1[0-3]"]],["(\\d)(\\d{5})","$1 $2",["[13]"]]],0,0,"([0-258]\\d{4})$","3$1"],NG:["234","009","(?:20|9\\d)\\d{8}|[78]\\d{9,13}",[10,11,12,13,14],[["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["[7-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["20[129]"],"0$1"],["(\\d{4})(\\d{2})(\\d{4})","$1 $2 $3",["2"],"0$1"],["(\\d{3})(\\d{4})(\\d{4,5})","$1 $2 $3",["[78]"],"0$1"],["(\\d{3})(\\d{5})(\\d{5,6})","$1 $2 $3",["[78]"],"0$1"]],"0"],NI:["505","00","(?:1800|[25-8]\\d{3})\\d{4}",[8],[["(\\d{4})(\\d{4})","$1 $2",["[125-8]"]]]],NL:["31","00","(?:[124-7]\\d\\d|3(?:[02-9]\\d|1[0-8]))\\d{6}|8\\d{6,9}|9\\d{6,10}|1\\d{4,5}",[5,6,7,8,9,10,11],[["(\\d{3})(\\d{4,7})","$1 $2",["[89]0"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["66"],"0$1"],["(\\d)(\\d{8})","$1 $2",["6"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["1[16-8]|2[259]|3[124]|4[17-9]|5[124679]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[1-578]|91"],"0$1"],["(\\d{3})(\\d{3})(\\d{5})","$1 $2 $3",["9"],"0$1"]],"0"],NO:["47","00","(?:0|[2-9]\\d{3})\\d{4}",[5,8],[["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["8"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2-79]"]]],0,0,0,0,0,"[02-689]|7[0-8]"],NP:["977","00","(?:1\\d|9)\\d{9}|[1-9]\\d{7}",[8,10,11],[["(\\d)(\\d{7})","$1-$2",["1[2-6]"],"0$1"],["(\\d{2})(\\d{6})","$1-$2",["1[01]|[2-8]|9(?:[1-59]|[67][2-6])"],"0$1"],["(\\d{3})(\\d{7})","$1-$2",["9"]]],"0"],NR:["674","00","(?:222|444|(?:55|8\\d)\\d|666|777|999)\\d{4}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[24-9]"]]]],NU:["683","00","(?:[4-7]|888\\d)\\d{3}",[4,7],[["(\\d{3})(\\d{4})","$1 $2",["8"]]]],NZ:["64","0(?:0|161)","[1289]\\d{9}|50\\d{5}(?:\\d{2,3})?|[27-9]\\d{7,8}|(?:[34]\\d|6[0-35-9])\\d{6}|8\\d{4,6}",[5,6,7,8,9,10],[["(\\d{2})(\\d{3,8})","$1 $2",["8[1-79]"],"0$1"],["(\\d{3})(\\d{2})(\\d{2,3})","$1 $2 $3",["50[036-8]|8|90","50(?:[0367]|88)|8|90"],"0$1"],["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["24|[346]|7[2-57-9]|9[2-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["2(?:10|74)|[589]"],"0$1"],["(\\d{2})(\\d{3,4})(\\d{4})","$1 $2 $3",["1|2[028]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,5})","$1 $2 $3",["2(?:[169]|7[0-35-9])|7"],"0$1"]],"0",0,0,0,0,0,0,"00"],OM:["968","00","(?:1505|[279]\\d{3}|500)\\d{4}|800\\d{5,6}",[7,8,9],[["(\\d{3})(\\d{4,6})","$1 $2",["[58]"]],["(\\d{2})(\\d{6})","$1 $2",["2"]],["(\\d{4})(\\d{4})","$1 $2",["[179]"]]]],PA:["507","00","(?:00800|8\\d{3})\\d{6}|[68]\\d{7}|[1-57-9]\\d{6}",[7,8,10,11],[["(\\d{3})(\\d{4})","$1-$2",["[1-57-9]"]],["(\\d{4})(\\d{4})","$1-$2",["[68]"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["8"]]]],PE:["51","00|19(?:1[124]|77|90)00","(?:[14-8]|9\\d)\\d{7}",[8,9],[["(\\d{3})(\\d{5})","$1 $2",["80"],"(0$1)"],["(\\d)(\\d{7})","$1 $2",["1"],"(0$1)"],["(\\d{2})(\\d{6})","$1 $2",["[4-8]"],"(0$1)"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["9"]]],"0",0,0,0,0,0,0,"00"," Anexo "],PF:["689","00","4\\d{5}(?:\\d{2})?|8\\d{7,8}",[6,8,9],[["(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3",["44"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["4|8[7-9]"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"]]]],PG:["675","00|140[1-3]","(?:180|[78]\\d{3})\\d{4}|(?:[2-589]\\d|64)\\d{5}",[7,8],[["(\\d{3})(\\d{4})","$1 $2",["18|[2-69]|85"]],["(\\d{4})(\\d{4})","$1 $2",["[78]"]]],0,0,0,0,0,0,0,"00"],PH:["63","00","(?:[2-7]|9\\d)\\d{8}|2\\d{5}|(?:1800|8)\\d{7,9}",[6,8,9,10,11,12,13],[["(\\d)(\\d{5})","$1 $2",["2"],"(0$1)"],["(\\d{4})(\\d{4,6})","$1 $2",["3(?:23|39|46)|4(?:2[3-6]|[35]9|4[26]|76)|544|88[245]|(?:52|64|86)2","3(?:230|397|461)|4(?:2(?:35|[46]4|51)|396|4(?:22|63)|59[347]|76[15])|5(?:221|446)|642[23]|8(?:622|8(?:[24]2|5[13]))"],"(0$1)"],["(\\d{5})(\\d{4})","$1 $2",["346|4(?:27|9[35])|883","3469|4(?:279|9(?:30|56))|8834"],"(0$1)"],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["2"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[3-7]|8[2-8]"],"(0$1)"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[89]"],"0$1"],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["1"]],["(\\d{4})(\\d{1,2})(\\d{3})(\\d{4})","$1 $2 $3 $4",["1"]]],"0"],PK:["92","00","122\\d{6}|[24-8]\\d{10,11}|9(?:[013-9]\\d{8,10}|2(?:[01]\\d\\d|2(?:[06-8]\\d|1[01]))\\d{7})|(?:[2-8]\\d{3}|92(?:[0-7]\\d|8[1-9]))\\d{6}|[24-9]\\d{8}|[89]\\d{7}",[8,9,10,11,12],[["(\\d{3})(\\d{3})(\\d{2,7})","$1 $2 $3",["[89]0"],"0$1"],["(\\d{4})(\\d{5})","$1 $2",["1"]],["(\\d{3})(\\d{6,7})","$1 $2",["2(?:3[2358]|4[2-4]|9[2-8])|45[3479]|54[2-467]|60[468]|72[236]|8(?:2[2-689]|3[23578]|4[3478]|5[2356])|9(?:2[2-8]|3[27-9]|4[2-6]|6[3569]|9[25-8])","9(?:2[3-8]|98)|(?:2(?:3[2358]|4[2-4]|9[2-8])|45[3479]|54[2-467]|60[468]|72[236]|8(?:2[2-689]|3[23578]|4[3478]|5[2356])|9(?:22|3[27-9]|4[2-6]|6[3569]|9[25-7]))[2-9]"],"(0$1)"],["(\\d{2})(\\d{7,8})","$1 $2",["(?:2[125]|4[0-246-9]|5[1-35-7]|6[1-8]|7[14]|8[16]|91)[2-9]"],"(0$1)"],["(\\d{5})(\\d{5})","$1 $2",["58"],"(0$1)"],["(\\d{3})(\\d{7})","$1 $2",["3"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["2[125]|4[0-246-9]|5[1-35-7]|6[1-8]|7[14]|8[16]|91"],"(0$1)"],["(\\d{3})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["[24-9]"],"(0$1)"]],"0"],PL:["48","00","(?:6|8\\d\\d)\\d{7}|[1-9]\\d{6}(?:\\d{2})?|[26]\\d{5}",[6,7,8,9,10],[["(\\d{5})","$1",["19"]],["(\\d{3})(\\d{3})","$1 $2",["11|20|64"]],["(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3",["(?:1[2-8]|2[2-69]|3[2-4]|4[1-468]|5[24-689]|6[1-3578]|7[14-7]|8[1-79]|9[145])1","(?:1[2-8]|2[2-69]|3[2-4]|4[1-468]|5[24-689]|6[1-3578]|7[14-7]|8[1-79]|9[145])19"]],["(\\d{3})(\\d{2})(\\d{2,3})","$1 $2 $3",["64"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["21|39|45|5[0137]|6[0469]|7[02389]|8(?:0[14]|8)"]],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["1[2-8]|[2-7]|8[1-79]|9[145]"]],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["8"]]]],PM:["508","00","[45]\\d{5}|(?:708|8\\d\\d)\\d{6}",[6,9],[["(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3",["[45]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["7"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"],"0$1"]],"0"],PR:["1","011","(?:[589]\\d\\d|787)\\d{7}",[10],0,"1",0,0,0,0,"787|939"],PS:["970","00","[2489]2\\d{6}|(?:1\\d|5)\\d{8}",[8,9,10],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["[2489]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["5"],"0$1"],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1"]]],"0"],PT:["351","00","1693\\d{5}|(?:[26-9]\\d|30)\\d{7}",[9],[["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["2[12]"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["16|[236-9]"]]]],PW:["680","01[12]","(?:[24-8]\\d\\d|345|900)\\d{4}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[2-9]"]]]],PY:["595","00","59\\d{4,6}|9\\d{5,10}|(?:[2-46-8]\\d|5[0-8])\\d{4,7}",[6,7,8,9,10,11],[["(\\d{3})(\\d{3,6})","$1 $2",["[2-9]0"],"0$1"],["(\\d{2})(\\d{5})","$1 $2",["[26]1|3[289]|4[1246-8]|7[1-3]|8[1-36]"],"(0$1)"],["(\\d{3})(\\d{4,5})","$1 $2",["2[279]|3[13-5]|4[359]|5|6(?:[34]|7[1-46-8])|7[46-8]|85"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["2[14-68]|3[26-9]|4[1246-8]|6(?:1|75)|7[1-35]|8[1-36]"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["87"]],["(\\d{3})(\\d{6})","$1 $2",["9(?:[5-79]|8[1-7])"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[2-8]"],"0$1"],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["9"]]],"0"],QA:["974","00","800\\d{4}|(?:2|800)\\d{6}|(?:0080|[3-7])\\d{7}",[7,8,9,11],[["(\\d{3})(\\d{4})","$1 $2",["2[136]|8"]],["(\\d{4})(\\d{4})","$1 $2",["[3-7]"]]]],RE:["262","00","709\\d{6}|(?:26|[689]\\d)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[26-9]"],"0$1"]],"0",0,0,0,0,0,[["26(?:2\\d\\d|3(?:0\\d|1[0-6]))\\d{4}"],["(?:69(?:2\\d\\d|3(?:[06][0-6]|1[0-3]|2[0-2]|3[0-39]|4\\d|5[0-5]|7[0-37]|8[0-8]|9[0-479]))|7092[0-3])\\d{4}"],["80\\d{7}"],["89[1-37-9]\\d{6}"],0,0,0,0,["9(?:399[0-3]|479[0-6]|76(?:2[278]|3[0-37]))\\d{4}"],["8(?:1[019]|2[0156]|84|90)\\d{6}"]]],RO:["40","00","(?:[236-8]\\d|90)\\d{7}|[23]\\d{5}",[6,9],[["(\\d{3})(\\d{3})","$1 $2",["2[3-6]","2[3-6]\\d9"],"0$1"],["(\\d{2})(\\d{4})","$1 $2",["219|31"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[23]1"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[236-9]"],"0$1"]],"0",0,0,0,0,0,0,0," int "],RS:["381","00","38[02-9]\\d{6,9}|6\\d{7,9}|90\\d{4,8}|38\\d{5,6}|(?:7\\d\\d|800)\\d{3,9}|(?:[12]\\d|3[0-79])\\d{5,10}",[6,7,8,9,10,11,12],[["(\\d{3})(\\d{3,9})","$1 $2",["(?:2[389]|39)0|[7-9]"],"0$1"],["(\\d{2})(\\d{5,10})","$1 $2",["[1-36]"],"0$1"]],"0"],RU:["7","810","8\\d{13}|[347-9]\\d{9}",[10,14],[["(\\d{4})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["7(?:1[0-8]|2[1-9])","7(?:1(?:[0-356]2|4[29]|7|8[27])|2(?:1[23]|[2-9]2))","7(?:1(?:[0-356]2|4[29]|7|8[27])|2(?:13[03-69]|62[013-9]))|72[1-57-9]2"],"8 ($1)",1],["(\\d{5})(\\d)(\\d{2})(\\d{2})","$1 $2 $3 $4",["7(?:1[0-68]|2[1-9])","7(?:1(?:[06][3-6]|[18]|2[35]|[3-5][3-5])|2(?:[13][3-5]|[24-689]|7[457]))","7(?:1(?:0(?:[356]|4[023])|[18]|2(?:3[013-9]|5)|3[45]|43[013-79]|5(?:3[1-8]|4[1-7]|5)|6(?:3[0-35-9]|[4-6]))|2(?:1(?:3[178]|[45])|[24-689]|3[35]|7[457]))|7(?:14|23)4[0-8]|71(?:33|45)[1-79]"],"8 ($1)",1],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["7"],"8 ($1)",1],["(\\d{3})(\\d{3})(\\d{2})(\\d{2})","$1 $2-$3-$4",["[349]|8(?:[02-7]|1[1-8])"],"8 ($1)",1],["(\\d{4})(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3 $4",["8"],"8 ($1)"]],"8",0,0,0,0,0,[["336(?:[013-9]\\d|2[013-9])\\d{5}|(?:3(?:0[12]|4[1-35-79]|5[1-3]|65|8[1-58]|9[0145])|4(?:01|1[1356]|2[13467]|7[1-5]|8[1-7]|9[1-689])|8(?:1[1-8]|2[01]|3[13-6]|4[0-8]|5[15-7]|6[0-35-79]|7[1-37-9]))\\d{7}",[10]],["9\\d{9}",[10]],["8(?:0[04]|108\\d{3})\\d{7}"],["80[39]\\d{7}",[10]],["808\\d{7}",[10]]],"8~10"],RW:["250","00","(?:06|[27]\\d\\d|[89]00)\\d{6}",[8,9],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["0"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["2"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[7-9]"],"0$1"]],"0"],SA:["966","00","(?:[15]\\d|800|92)\\d{7}",[9,10],[["(\\d{4})(\\d{5})","$1 $2",["9"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["1"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["5"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["8"]]],"0"],SB:["677","0[01]","[6-9]\\d{6}|[1-6]\\d{4}",[5,7],[["(\\d{2})(\\d{5})","$1 $2",["6[89]|7|8[4-9]|9(?:[1-8]|9[0-8])"]]]],SC:["248","010|0[0-2]","(?:[2489]\\d|64)\\d{5}",[7],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["[246]|9[57]"]]],0,0,0,0,0,0,0,"00"],SD:["249","00","[19]\\d{8}",[9],[["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[19]"],"0$1"]],"0"],SE:["46","00","(?:[26]\\d\\d|9)\\d{9}|[1-9]\\d{8}|[1-689]\\d{7}|[1-4689]\\d{6}|2\\d{5}",[6,7,8,9,10,12],[["(\\d{2})(\\d{2,3})(\\d{2})","$1-$2 $3",["20"],"0$1",0,"$1 $2 $3"],["(\\d{3})(\\d{4})","$1-$2",["9(?:00|39|44|9)"],"0$1",0,"$1 $2"],["(\\d{2})(\\d{3})(\\d{2})","$1-$2 $3",["[12][136]|3[356]|4[0246]|6[03]|90[1-9]"],"0$1",0,"$1 $2 $3"],["(\\d)(\\d{2,3})(\\d{2})(\\d{2})","$1-$2 $3 $4",["8"],"0$1",0,"$1 $2 $3 $4"],["(\\d{3})(\\d{2,3})(\\d{2})","$1-$2 $3",["1[2457]|2(?:[247-9]|5[0138])|3[0247-9]|4[1357-9]|5[0-35-9]|6(?:[125689]|4[02-57]|7[0-2])|9(?:[125-8]|3[02-5]|4[0-3])"],"0$1",0,"$1 $2 $3"],["(\\d{3})(\\d{2,3})(\\d{3})","$1-$2 $3",["9(?:00|39|44)"],"0$1",0,"$1 $2 $3"],["(\\d{2})(\\d{2,3})(\\d{2})(\\d{2})","$1-$2 $3 $4",["1[13689]|2[0136]|3[1356]|4[0246]|54|6[03]|90[1-9]"],"0$1",0,"$1 $2 $3 $4"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1-$2 $3 $4",["10|7"],"0$1",0,"$1 $2 $3 $4"],["(\\d)(\\d{3})(\\d{3})(\\d{2})","$1-$2 $3 $4",["8"],"0$1",0,"$1 $2 $3 $4"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1-$2 $3 $4",["[13-5]|2(?:[247-9]|5[0138])|6(?:[124-689]|7[0-2])|9(?:[125-8]|3[02-5]|4[0-3])"],"0$1",0,"$1 $2 $3 $4"],["(\\d{3})(\\d{2})(\\d{2})(\\d{3})","$1-$2 $3 $4",["9"],"0$1",0,"$1 $2 $3 $4"],["(\\d{3})(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1-$2 $3 $4 $5",["[26]"],"0$1",0,"$1 $2 $3 $4 $5"]],"0"],SG:["65","0[0-3]\\d","(?:(?:1\\d|8)\\d\\d|7000)\\d{7}|[3689]\\d{7}",[8,10,11],[["(\\d{4})(\\d{4})","$1 $2",["[369]|8(?:0[1-9]|[1-9])"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["8"]],["(\\d{4})(\\d{4})(\\d{3})","$1 $2 $3",["7"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["1"]]]],SH:["290","00","(?:[256]\\d|8)\\d{3}",[4,5],0,0,0,0,0,0,"[256]"],SI:["386","00|10(?:22|66|88|99)","[1-7]\\d{7}|8\\d{4,7}|90\\d{4,6}",[5,6,7,8],[["(\\d{2})(\\d{3,6})","$1 $2",["8[09]|9"],"0$1"],["(\\d{3})(\\d{5})","$1 $2",["59|8"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[37][01]|4[0139]|51|6"],"0$1"],["(\\d)(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[1-57]"],"(0$1)"]],"0",0,0,0,0,0,0,"00"],SJ:["47","00","0\\d{4}|(?:[489]\\d|79)\\d{6}",[5,8],0,0,0,0,0,0,"79"],SK:["421","00","[2-689]\\d{8}|[2-59]\\d{6}|[2-5]\\d{5}",[6,7,9],[["(\\d)(\\d{2})(\\d{3,4})","$1 $2 $3",["21"],"0$1"],["(\\d{2})(\\d{2})(\\d{2,3})","$1 $2 $3",["[3-5][1-8]1","[3-5][1-8]1[67]"],"0$1"],["(\\d)(\\d{3})(\\d{3})(\\d{2})","$1/$2 $3 $4",["2"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[689]"],"0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1/$2 $3 $4",["[3-5]"],"0$1"]],"0"],SL:["232","00","(?:[237-9]\\d|66)\\d{6}",[8],[["(\\d{2})(\\d{6})","$1 $2",["[236-9]"],"(0$1)"]],"0"],SM:["378","00","(?:0549|[5-7]\\d)\\d{6}",[8,10],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-7]"]],["(\\d{4})(\\d{6})","$1 $2",["0"]]],0,0,"([89]\\d{5})$","0549$1"],SN:["221","00","(?:[378]\\d|93)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"]],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[379]"]]]],SO:["252","00","[346-9]\\d{8}|[12679]\\d{7}|[1-5]\\d{6}|[1348]\\d{5}",[6,7,8,9],[["(\\d{2})(\\d{4})","$1 $2",["8[125]"]],["(\\d{6})","$1",["[134]"]],["(\\d)(\\d{6})","$1 $2",["[15]|2[0-79]|3[0-46-8]|4[0-7]"]],["(\\d)(\\d{7})","$1 $2",["(?:2|90)4|[67]"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[348]|64|79|90"]],["(\\d{2})(\\d{5,7})","$1 $2",["1|28|6[0-35-9]|7[67]|9[2-9]"]]],"0"],SR:["597","00","(?:[2-5]|[6-8]\\d|90)\\d{5}",[6,7],[["(\\d{2})(\\d{2})(\\d{2})","$1-$2-$3",["56"]],["(\\d{3})(\\d{3})","$1-$2",["[2-5]"]],["(\\d{3})(\\d{4})","$1-$2",["[6-9]"]]]],SS:["211","00","[19]\\d{8}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[19]"],"0$1"]],"0"],ST:["239","00","(?:22|9\\d)\\d{5}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[29]"]]]],SV:["503","00","[25-7]\\d{7}|(?:80\\d|900)\\d{4}(?:\\d{4})?",[7,8,11],[["(\\d{3})(\\d{4})","$1 $2",["[89]"]],["(\\d{4})(\\d{4})","$1 $2",["[25-7]"]],["(\\d{3})(\\d{4})(\\d{4})","$1 $2 $3",["[89]"]]]],SX:["1","011","7215\\d{6}|(?:[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"(5\\d{6})$|1","721$1",0,"721"],SY:["963","00","[1-359]\\d{8}|[1-5]\\d{7}",[8,9],[["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[1-4]|5[1-3]"],"0$1",1],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[59]"],"0$1",1]],"0"],SZ:["268","00","0800\\d{4}|(?:[237]\\d|900)\\d{6}",[8,9],[["(\\d{4})(\\d{4})","$1 $2",["[0237]"]],["(\\d{5})(\\d{4})","$1 $2",["9"]]]],TA:["290","00","8\\d{3}",[4],0,0,0,0,0,0,"8"],TC:["1","011","(?:[58]\\d\\d|649|900)\\d{7}",[10],0,"1",0,"([2-479]\\d{6})$|1","649$1",0,"649"],TD:["235","00|16","(?:22|30|[689]\\d|77)\\d{6}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[236-9]"]]],0,0,0,0,0,0,0,"00"],TG:["228","00","[279]\\d{7}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[279]"]]]],TH:["66","00[1-9]","(?:001800|[2-57]|[689]\\d)\\d{7}|1\\d{7,9}",[8,9,10,13],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["2"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[13-9]"],"0$1"],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1"]]],"0"],TJ:["992","810","(?:[0-57-9]\\d|66)\\d{7}",[9],[["(\\d{6})(\\d)(\\d{2})","$1 $2 $3",["331","3317"]],["(\\d{3})(\\d{2})(\\d{4})","$1 $2 $3",["44[02-479]|[34]7"]],["(\\d{4})(\\d)(\\d{4})","$1 $2 $3",["3(?:[1245]|3[12])"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["\\d"]]],0,0,0,0,0,0,0,"8~10"],TK:["690","00","[2-47]\\d{3,6}",[4,5,6,7]],TL:["670","00","7\\d{7}|(?:[2-47]\\d|[89]0)\\d{5}",[7,8],[["(\\d{3})(\\d{4})","$1 $2",["[2-489]|70"]],["(\\d{4})(\\d{4})","$1 $2",["7"]]]],TM:["993","810","(?:[1-6]\\d|71)\\d{6}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2-$3-$4",["12"],"(8 $1)"],["(\\d{3})(\\d)(\\d{2})(\\d{2})","$1 $2-$3-$4",["[1-5]"],"(8 $1)"],["(\\d{2})(\\d{6})","$1 $2",["[67]"],"8 $1"]],"8",0,0,0,0,0,0,"8~10"],TN:["216","00","[2-57-9]\\d{7}",[8],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[2-57-9]"]]]],TO:["676","00","(?:0800|(?:[5-8]\\d\\d|999)\\d)\\d{3}|[2-8]\\d{4}",[5,7],[["(\\d{2})(\\d{3})","$1-$2",["[2-4]|50|6[09]|7[0-24-69]|8[05]"]],["(\\d{4})(\\d{3})","$1 $2",["0"]],["(\\d{3})(\\d{4})","$1 $2",["[5-9]"]]]],TR:["90","00","4\\d{6}|8\\d{11,12}|(?:[2-58]\\d\\d|900)\\d{7}",[7,10,12,13],[["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["512|8[01589]|90"],"0$1",1],["(\\d{3})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["5(?:[0-59]|61)","5(?:[0-59]|61[06])","5(?:[0-59]|61[06]1)"],"0$1",1],["(\\d{3})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[24][1-8]|3[1-9]"],"(0$1)",1],["(\\d{3})(\\d{3})(\\d{6,7})","$1 $2 $3",["80"],"0$1",1]],"0"],TT:["1","011","(?:[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-46-8]\\d{6})$|1","868$1",0,"868"],TV:["688","00","(?:2|7\\d\\d|90)\\d{4}",[5,6,7],[["(\\d{2})(\\d{3})","$1 $2",["2"]],["(\\d{2})(\\d{4})","$1 $2",["90"]],["(\\d{2})(\\d{5})","$1 $2",["7"]]]],TW:["886","0(?:0[25-79]|19)","[2-689]\\d{8}|7\\d{9,10}|[2-8]\\d{7}|2\\d{6}",[7,8,9,10,11],[["(\\d{2})(\\d)(\\d{4})","$1 $2 $3",["202"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[258]0"],"0$1"],["(\\d)(\\d{3,4})(\\d{4})","$1 $2 $3",["[23568]|4(?:0[02-48]|[1-47-9])|7[1-9]","[23568]|4(?:0[2-48]|[1-47-9])|(?:400|7)[1-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[49]"],"0$1"],["(\\d{2})(\\d{4})(\\d{4,5})","$1 $2 $3",["7"],"0$1"]],"0",0,0,0,0,0,0,0,"#"],TZ:["255","00[056]","(?:[25-8]\\d|41|90)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{4})","$1 $2 $3",["[89]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[24]"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["5"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[67]"],"0$1"]],"0"],UA:["380","00","[89]\\d{9}|[3-9]\\d{8}",[9,10],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["6[12][29]|(?:3[1-8]|4[136-8]|5[12457]|6[49])2|(?:56|65)[24]","6[12][29]|(?:35|4[1378]|5[12457]|6[49])2|(?:56|65)[24]|(?:3[1-46-8]|46)2[013-9]"],"0$1"],["(\\d{4})(\\d{5})","$1 $2",["3[1-8]|4(?:[1367]|[45][6-9]|8[4-6])|5(?:[1-5]|6[0135689]|7[4-6])|6(?:[12][3-7]|[459])","3[1-8]|4(?:[1367]|[45][6-9]|8[4-6])|5(?:[1-5]|6(?:[015689]|3[02389])|7[4-6])|6(?:[12][3-7]|[459])"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[3-7]|89|9[1-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["[89]"],"0$1"]],"0",0,0,0,0,0,0,"0~0"],UG:["256","00[057]","800\\d{6}|(?:[29]0|[347]\\d)\\d{7}",[9],[["(\\d{4})(\\d{5})","$1 $2",["202","2024"],"0$1"],["(\\d{3})(\\d{6})","$1 $2",["[27-9]|4(?:6[45]|[7-9])"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["[34]"],"0$1"]],"0"],US:["1","011","[2-9]\\d{9}|3\\d{6}",[10],[["(\\d{3})(\\d{4})","$1-$2",["310"],0,1],["(\\d{3})(\\d{3})(\\d{4})","($1) $2-$3",["[2-9]"],0,1,"$1-$2-$3"]],"1",0,0,0,0,0,[["3052(?:0[0-8]|[1-9]\\d)\\d{4}|(?:2742|305[3-9])\\d{6}|(?:472|983)[2-47-9]\\d{6}|(?:2(?:0[1-35-9]|1[02-9]|2[03-57-9]|3[1459]|4[08]|5[1-46]|6[0279]|7[0269]|8[13])|3(?:0[1-47-9]|1[02-9]|2[013-79]|3[0-24679]|4[167]|5[0-2]|6[01349]|8[056])|4(?:0[124-9]|1[02-579]|2[3-5]|3[0245]|4[023578]|58|6[349]|7[0589]|8[04])|5(?:0[1-57-9]|1[0235-8]|20|3[0149]|4[01]|5[179]|6[1-47]|7[0-5]|8[0256])|6(?:0[1-35-9]|1[024-9]|2[03689]|3[016]|4[0156]|5[01679]|6[0-279]|78|8[0-269])|7(?:0[1-46-8]|1[2-9]|2[04-8]|3[0-247]|4[0378]|5[47]|6[02359]|7[0-59]|8[156])|8(?:0[1-68]|1[02-8]|2[0168]|3[0-2589]|4[03578]|5[046-9]|6[02-5]|7[028])|9(?:0[1346-9]|1[02-9]|2[0589]|3[0146-8]|4[01357-9]|5[12469]|7[0-3589]|8[04-69]))[2-9]\\d{6}"],[""],["8(?:00|33|44|55|66|77|88)[2-9]\\d{6}"],["900[2-9]\\d{6}"],["52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}"],0,0,0,["305209\\d{4}"]]],UY:["598","0(?:0|1[3-9]\\d)","0004\\d{2,9}|[1249]\\d{7}|2\\d{3,4}|(?:[49]\\d|80)\\d{5}",[4,5,6,7,8,9,10,11,12,13],[["(\\d{4,5})","$1",["21"]],["(\\d{3})(\\d{3,4})","$1 $2",["0"]],["(\\d{3})(\\d{4})","$1 $2",["[49]0|8"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["9"],"0$1"],["(\\d{4})(\\d{4})","$1 $2",["[124]"]],["(\\d{3})(\\d{3})(\\d{2,4})","$1 $2 $3",["0"]],["(\\d{3})(\\d{3})(\\d{3})(\\d{2,4})","$1 $2 $3 $4",["0"]]],"0",0,0,0,0,0,0,"00"," int. "],UZ:["998","00","(?:20|33|[5-9]\\d)\\d{7}",[9],[["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[235-9]"]]]],VA:["39","00","0\\d{5,10}|3[0-8]\\d{7,10}|55\\d{8}|8\\d{5}(?:\\d{2,4})?|(?:1\\d|39)\\d{7,8}",[6,7,8,9,10,11,12],0,0,0,0,0,0,"06698"],VC:["1","011","(?:[58]\\d\\d|784|900)\\d{7}",[10],0,"1",0,"([2-7]\\d{6})$|1","784$1",0,"784"],VE:["58","00","[68]00\\d{7}|(?:[24]\\d|[59]0)\\d{8}",[10],[["(\\d{3})(\\d{7})","$1-$2",["[24-689]"],"0$1"]],"0"],VG:["1","011","(?:284|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-578]\\d{6})$|1","284$1",0,"284"],VI:["1","011","[58]\\d{9}|(?:34|90)0\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","340$1",0,"340"],VN:["84","00","[12]\\d{9}|[135-9]\\d{8}|[16]\\d{7}|[16-8]\\d{6}",[7,8,9,10],[["(\\d{2})(\\d{5})","$1 $2",["80"],"0$1",1],["(\\d{4})(\\d{4,6})","$1 $2",["1"],0,1],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["6"],"0$1",1],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[357-9]"],"0$1",1],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["2[48]"],"0$1",1],["(\\d{3})(\\d{4})(\\d{3})","$1 $2 $3",["2"],"0$1",1]],"0"],VU:["678","00","[57-9]\\d{6}|(?:[238]\\d|48)\\d{3}",[5,7],[["(\\d{3})(\\d{4})","$1 $2",["[57-9]"]]]],WF:["681","00","(?:40|72|8\\d{4})\\d{4}|[89]\\d{5}",[6,9],[["(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3",["[47-9]"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"]]]],WS:["685","0","(?:[2-6]|8\\d{5})\\d{4}|[78]\\d{6}|[68]\\d{5}",[5,6,7,10],[["(\\d{5})","$1",["[2-5]|6[1-9]"]],["(\\d{3})(\\d{3,7})","$1 $2",["[68]"]],["(\\d{2})(\\d{5})","$1 $2",["7"]]]],XK:["383","00","2\\d{7,8}|3\\d{7,11}|(?:4\\d\\d|[89]00)\\d{5}",[8,9,10,11,12],[["(\\d{3})(\\d{5})","$1 $2",["[89]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[2-4]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["2|39"],"0$1"],["(\\d{2})(\\d{7,10})","$1 $2",["3"],"0$1"]],"0"],YE:["967","00","(?:1|7\\d)\\d{7}|[1-7]\\d{6}",[7,8,9],[["(\\d)(\\d{3})(\\d{3,4})","$1 $2 $3",["[1-6]|7(?:[24-6]|8[0-7])"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["7"],"0$1"]],"0"],YT:["262","00","7093\\d{5}|(?:80|9\\d)\\d{7}|(?:26|63)9\\d{6}",[9],0,"0",0,0,0,0,0,[["269(?:0[0-467]|15|5[0-4]|6\\d|[78]0)\\d{4}"],["(?:639(?:0[0-79]|1[019]|[267]\\d|3[09]|40|5[05-9]|9[04-79])|7093[5-7])\\d{4}"],["80\\d{7}"],0,0,0,0,0,["9(?:(?:39|47)8[01]|769\\d)\\d{4}"]]],ZA:["27","00","[1-79]\\d{8}|8\\d{4,9}",[5,6,7,8,9,10],[["(\\d{2})(\\d{3,4})","$1 $2",["8[1-4]"],"0$1"],["(\\d{2})(\\d{3})(\\d{2,3})","$1 $2 $3",["8[1-4]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["860"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[1-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["8"],"0$1"]],"0"],ZM:["260","00","800\\d{6}|(?:21|[579]\\d|63)\\d{7}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[28]"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["[579]"],"0$1"]],"0"],ZW:["263","00","2(?:[0-57-9]\\d{6,8}|6[0-24-9]\\d{6,7})|[38]\\d{9}|[35-8]\\d{8}|[3-6]\\d{7}|[1-689]\\d{6}|[1-3569]\\d{5}|[1356]\\d{4}",[5,6,7,8,9,10],[["(\\d{3})(\\d{3,5})","$1 $2",["2(?:0[45]|2[278]|[49]8)|3(?:[09]8|17)|6(?:[29]8|37|75)|[23][78]|(?:33|5[15]|6[68])[78]"],"0$1"],["(\\d)(\\d{3})(\\d{2,4})","$1 $2 $3",["[49]"],"0$1"],["(\\d{3})(\\d{4})","$1 $2",["80"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["24|8[13-59]|(?:2[05-79]|39|5[45]|6[15-8])2","2(?:02[014]|4|[56]20|[79]2)|392|5(?:42|525)|6(?:[16-8]21|52[013])|8[13-59]"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["7"],"0$1"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["2(?:1[39]|2[0157]|[378]|[56][14])|3(?:12|29)","2(?:1[39]|2[0157]|[378]|[56][14])|3(?:123|29)"],"0$1"],["(\\d{4})(\\d{6})","$1 $2",["8"],"0$1"],["(\\d{2})(\\d{3,5})","$1 $2",["1|2(?:0[0-36-9]|12|29|[56])|3(?:1[0-689]|[24-6])|5(?:[0236-9]|1[2-4])|6(?:[013-59]|7[0-46-9])|(?:33|55|6[68])[0-69]|(?:29|3[09]|62)[0-79]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["29[013-9]|39|54"],"0$1"],["(\\d{4})(\\d{3,5})","$1 $2",["(?:25|54)8","258|5483"],"0$1"]],"0"]},nonGeographic:{800:["800",0,"(?:00|[1-9]\\d)\\d{6}",[8],[["(\\d{4})(\\d{4})","$1 $2",["\\d"]]],0,0,0,0,0,0,[0,0,["(?:00|[1-9]\\d)\\d{6}"]]],808:["808",0,"[1-9]\\d{7}",[8],[["(\\d{4})(\\d{4})","$1 $2",["[1-9]"]]],0,0,0,0,0,0,[0,0,0,0,0,0,0,0,0,["[1-9]\\d{7}"]]],870:["870",0,"7\\d{11}|[235-7]\\d{8}",[9,12],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[235-7]"]]],0,0,0,0,0,0,[0,["(?:[356]|774[45])\\d{8}|7[6-8]\\d{7}"],0,0,0,0,0,0,["2\\d{8}",[9]]]],878:["878",0,"10\\d{10}",[12],[["(\\d{2})(\\d{5})(\\d{5})","$1 $2 $3",["1"]]],0,0,0,0,0,0,[0,0,0,0,0,0,0,0,["10\\d{10}"]]],881:["881",0,"6\\d{9}|[0-36-9]\\d{8}",[9,10],[["(\\d)(\\d{3})(\\d{5})","$1 $2 $3",["[0-37-9]"]],["(\\d)(\\d{3})(\\d{5,6})","$1 $2 $3",["6"]]],0,0,0,0,0,0,[0,["6\\d{9}|[0-36-9]\\d{8}"]]],882:["882",0,"[13]\\d{6}(?:\\d{2,5})?|[19]\\d{7}|(?:[25]\\d\\d|4)\\d{7}(?:\\d{2})?",[7,8,9,10,11,12],[["(\\d{2})(\\d{5})","$1 $2",["16|342"]],["(\\d{2})(\\d{6})","$1 $2",["49"]],["(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3",["1[36]|9"]],["(\\d{2})(\\d{4})(\\d{3})","$1 $2 $3",["3[23]"]],["(\\d{2})(\\d{3,4})(\\d{4})","$1 $2 $3",["16"]],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["10|23|3(?:[15]|4[57])|4|51"]],["(\\d{3})(\\d{4})(\\d{4})","$1 $2 $3",["34"]],["(\\d{2})(\\d{4,5})(\\d{5})","$1 $2 $3",["[1-35]"]]],0,0,0,0,0,0,[0,["342\\d{4}|(?:337|49)\\d{6}|(?:3(?:2|47|7\\d{3})|50\\d{3})\\d{7}",[7,8,9,10,12]],0,0,0,["348[57]\\d{7}",[11]],0,0,["1(?:3(?:0[0347]|[13][0139]|2[035]|4[013568]|6[0459]|7[06]|8[15-8]|9[0689])\\d{4}|6\\d{5,10})|(?:345\\d|9[89])\\d{6}|(?:10|2(?:3|85\\d)|3(?:[15]|[69]\\d\\d)|4[15-8]|51)\\d{8}"]]],883:["883",0,"(?:[1-4]\\d|51)\\d{6,10}",[8,9,10,11,12],[["(\\d{3})(\\d{3})(\\d{2,8})","$1 $2 $3",["[14]|2[24-689]|3[02-689]|51[24-9]"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["510"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["21"]],["(\\d{4})(\\d{4})(\\d{4})","$1 $2 $3",["51[13]"]],["(\\d{3})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["[235]"]]],0,0,0,0,0,0,[0,0,0,0,0,0,0,0,["(?:2(?:00\\d\\d|10)|(?:370[1-9]|51\\d0)\\d)\\d{7}|51(?:00\\d{5}|[24-9]0\\d{4,7})|(?:1[0-79]|2[24-689]|3[02-689]|4[0-4])0\\d{5,9}"]]],888:["888",0,"\\d{11}",[11],[["(\\d{3})(\\d{3})(\\d{5})","$1 $2 $3"]],0,0,0,0,0,0,[0,0,0,0,0,0,["\\d{11}"]]],979:["979",0,"[1359]\\d{8}",[9],[["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["[1359]"]]],0,0,0,0,0,0,[0,0,0,["[1359]\\d{8}"]]]}};function m5(t,e){var n=Array.prototype.slice.call(e);return n.push(g5),t.apply(this,n)}function Fg(t,e){t=t.split("-"),e=e.split("-");for(var n=t[0].split("."),r=e[0].split("."),i=0;i<3;i++){var s=Number(n[i]),a=Number(r[i]);if(s>a)return 1;if(a>s)return-1;if(!isNaN(s)&&isNaN(a))return 1;if(isNaN(s)&&!isNaN(a))return-1}return t[1]&&e[1]?t[1]>e[1]?1:t[1]<e[1]?-1:0:!t[1]&&e[1]?1:t[1]&&!e[1]?-1:0}var _5={}.constructor;function Kr(t){return t!=null&&t.constructor===_5}function ci(t){"@babel/helpers - typeof";return ci=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ci(t)}function el(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function y5(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,w5(r.key),r)}}function tl(t,e,n){return e&&y5(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function w5(t){var e=b5(t,"string");return ci(e)=="symbol"?e:e+""}function b5(t,e){if(ci(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(ci(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}var v5="1.2.0",$5="1.7.35",Hg=" ext. ",k5=/^\d+$/,Je=(function(){function t(e){el(this,t),C1(e),this.metadata=e,N1.call(this,e)}return tl(t,[{key:"getCountries",value:function(){return Object.keys(this.metadata.countries).filter(function(n){return n!=="001"})}},{key:"getCountryMetadata",value:function(n){return this.metadata.countries[n]}},{key:"nonGeographic",value:function(){if(!(this.v1||this.v2||this.v3))return this.metadata.nonGeographic||this.metadata.nonGeographical}},{key:"hasCountry",value:function(n){return this.getCountryMetadata(n)!==void 0}},{key:"hasCallingCode",value:function(n){if(this.getCountryCodesForCallingCode(n))return!0;if(this.nonGeographic()){if(this.nonGeographic()[n])return!0}else{var r=this.countryCallingCodes()[n];if(r&&r.length===1&&r[0]==="001")return!0}}},{key:"isNonGeographicCallingCode",value:function(n){return this.nonGeographic()?!!this.nonGeographic()[n]:!this.getCountryCodesForCallingCode(n)}},{key:"country",value:function(n){return this.selectNumberingPlan(n)}},{key:"selectNumberingPlan",value:function(n,r){if(n&&k5.test(n)&&(r=n,n=null),n&&n!=="001"){if(!this.hasCountry(n))throw new Error("Unknown country: ".concat(n));this.numberingPlan=new Vg(this.getCountryMetadata(n),this)}else if(r){if(!this.hasCallingCode(r))throw new Error("Unknown calling code: ".concat(r));this.numberingPlan=new Vg(this.getNumberingPlanMetadata(r),this)}else this.numberingPlan=void 0;return this}},{key:"getCountryCodesForCallingCode",value:function(n){var r=this.countryCallingCodes()[n];if(r)return r.length===1&&r[0].length===3?void 0:r}},{key:"getCountryCodeForCallingCode",value:function(n){var r=this.getCountryCodesForCallingCode(n);if(r)return r[0]}},{key:"getNumberingPlanMetadata",value:function(n){var r=this.getCountryCodeForCallingCode(n);if(r)return this.getCountryMetadata(r);if(this.nonGeographic()){var i=this.nonGeographic()[n];if(i)return i}else{var s=this.countryCallingCodes()[n];if(s&&s.length===1&&s[0]==="001")return this.metadata.countries["001"]}}},{key:"countryCallingCode",value:function(){return this.numberingPlan.callingCode()}},{key:"IDDPrefix",value:function(){return this.numberingPlan.IDDPrefix()}},{key:"defaultIDDPrefix",value:function(){return this.numberingPlan.defaultIDDPrefix()}},{key:"nationalNumberPattern",value:function(){return this.numberingPlan.nationalNumberPattern()}},{key:"possibleLengths",value:function(){return this.numberingPlan.possibleLengths()}},{key:"formats",value:function(){return this.numberingPlan.formats()}},{key:"nationalPrefixForParsing",value:function(){return this.numberingPlan.nationalPrefixForParsing()}},{key:"nationalPrefixTransformRule",value:function(){return this.numberingPlan.nationalPrefixTransformRule()}},{key:"leadingDigits",value:function(){return this.numberingPlan.leadingDigits()}},{key:"hasTypes",value:function(){return this.numberingPlan.hasTypes()}},{key:"type",value:function(n){return this.numberingPlan.type(n)}},{key:"ext",value:function(){return this.numberingPlan.ext()}},{key:"countryCallingCodes",value:function(){return this.v1?this.metadata.country_phone_code_to_countries:this.metadata.country_calling_codes}},{key:"chooseCountryByCountryCallingCode",value:function(n){return this.selectNumberingPlan(n)}},{key:"hasSelectedNumberingPlan",value:function(){return this.numberingPlan!==void 0}}])})(),Vg=(function(){function t(e,n){el(this,t),this.globalMetadataObject=n,this.metadata=e,N1.call(this,n.metadata)}return tl(t,[{key:"callingCode",value:function(){return this.metadata[0]}},{key:"getDefaultCountryMetadataForRegion",value:function(){return this.globalMetadataObject.getNumberingPlanMetadata(this.callingCode())}},{key:"IDDPrefix",value:function(){if(!(this.v1||this.v2))return this.metadata[1]}},{key:"defaultIDDPrefix",value:function(){if(!(this.v1||this.v2))return this.metadata[12]}},{key:"nationalNumberPattern",value:function(){return this.v1||this.v2?this.metadata[1]:this.metadata[2]}},{key:"possibleLengths",value:function(){if(!this.v1)return this.metadata[this.v2?2:3]}},{key:"_getFormats",value:function(n){return n[this.v1?2:this.v2?3:4]}},{key:"formats",value:function(){var n=this,r=this._getFormats(this.metadata)||this._getFormats(this.getDefaultCountryMetadataForRegion())||[];return r.map(function(i){return new x5(i,n)})}},{key:"nationalPrefix",value:function(){return this.metadata[this.v1?3:this.v2?4:5]}},{key:"_getNationalPrefixFormattingRule",value:function(n){return n[this.v1?4:this.v2?5:6]}},{key:"nationalPrefixFormattingRule",value:function(){return this._getNationalPrefixFormattingRule(this.metadata)||this._getNationalPrefixFormattingRule(this.getDefaultCountryMetadataForRegion())}},{key:"_nationalPrefixForParsing",value:function(){return this.metadata[this.v1?5:this.v2?6:7]}},{key:"nationalPrefixForParsing",value:function(){return this._nationalPrefixForParsing()||this.nationalPrefix()}},{key:"nationalPrefixTransformRule",value:function(){return this.metadata[this.v1?6:this.v2?7:8]}},{key:"_getNationalPrefixIsOptionalWhenFormatting",value:function(){return!!this.metadata[this.v1?7:this.v2?8:9]}},{key:"nationalPrefixIsOptionalWhenFormattingInNationalFormat",value:function(){return this._getNationalPrefixIsOptionalWhenFormatting(this.metadata)||this._getNationalPrefixIsOptionalWhenFormatting(this.getDefaultCountryMetadataForRegion())}},{key:"leadingDigits",value:function(){return this.metadata[this.v1?8:this.v2?9:10]}},{key:"types",value:function(){return this.metadata[this.v1?9:this.v2?10:11]}},{key:"hasTypes",value:function(){return this.types()&&this.types().length===0?!1:!!this.types()}},{key:"type",value:function(n){if(this.hasTypes()&&Kg(this.types(),n))return new z5(Kg(this.types(),n),this)}},{key:"ext",value:function(){return this.v1||this.v2?Hg:this.metadata[13]||Hg}}])})(),x5=(function(){function t(e,n){el(this,t),this._format=e,this.metadata=n}return tl(t,[{key:"pattern",value:function(){return this._format[0]}},{key:"format",value:function(){return this._format[1]}},{key:"leadingDigitsPatterns",value:function(){return this._format[2]||[]}},{key:"nationalPrefixFormattingRule",value:function(){return this._format[3]||this.metadata.nationalPrefixFormattingRule()}},{key:"nationalPrefixIsOptionalWhenFormattingInNationalFormat",value:function(){return!!this._format[4]||this.metadata.nationalPrefixIsOptionalWhenFormattingInNationalFormat()}},{key:"nationalPrefixIsMandatoryWhenFormattingInNationalFormat",value:function(){return this.usesNationalPrefix()&&!this.nationalPrefixIsOptionalWhenFormattingInNationalFormat()}},{key:"usesNationalPrefix",value:function(){return!!(this.nationalPrefixFormattingRule()&&!S5.test(this.nationalPrefixFormattingRule()))}},{key:"internationalFormat",value:function(){return this._format[5]||this.format()}}])})(),S5=/^\(?\$1\)?$/,z5=(function(){function t(e,n){el(this,t),this.type=e,this.metadata=n}return tl(t,[{key:"pattern",value:function(){return this.metadata.v1?this.type:this.type[0]}},{key:"possibleLengths",value:function(){if(!this.metadata.v1)return this.type[1]||this.metadata.possibleLengths()}}])})();function Kg(t,e){switch(e){case"FIXED_LINE":return t[0];case"MOBILE":return t[1];case"TOLL_FREE":return t[2];case"PREMIUM_RATE":return t[3];case"PERSONAL_NUMBER":return t[4];case"VOICEMAIL":return t[5];case"UAN":return t[6];case"PAGER":return t[7];case"VOIP":return t[8];case"SHARED_COST":return t[9]}}function C1(t){if(!t)throw new Error("[libphonenumber-js] `metadata` argument not passed. Check your arguments.");if(!Kr(t)||!Kr(t.countries))throw new Error("[libphonenumber-js] `metadata` argument was passed but it's not a valid metadata. Must be an object having `.countries` child object property. Got ".concat(Kr(t)?"an object of shape: { "+Object.keys(t).join(", ")+" }":"a "+A5(t)+": "+t,"."))}var A5=function(e){return ci(e)};function Rp(t,e){if(e=new Je(e),e.hasCountry(t))return e.selectNumberingPlan(t).countryCallingCode();throw new Error("Unknown country: ".concat(t))}function E5(t,e){return e.countries.hasOwnProperty(t)}function N1(t){var e=t.version;typeof e=="number"?(this.v1=e===1,this.v2=e===2,this.v3=e===3,this.v4=e===4):e?Fg(e,v5)===-1?this.v2=!0:Fg(e,$5)===-1?this.v3=!0:this.v4=!0:this.v1=!0}function Bp(t,e,n){return C5(t,e,void 0,n)}function C5(t,e,n,r){e&&(r=new Je(r.metadata),r.selectNumberingPlan(e));var i=r.type(n),s=i&&i.possibleLengths()||r.possibleLengths();if(!s)return"IS_POSSIBLE";var a=t.length,c=s[0];return c===a?"IS_POSSIBLE":c>a?"TOO_SHORT":s[s.length-1]<a?"TOO_LONG":s.indexOf(a,1)>=0?"IS_POSSIBLE":"INVALID_LENGTH"}function N5(t,e,n){if(e===void 0&&(e={}),n=new Je(n),e.v2){if(!t.countryCallingCode)throw new Error("Invalid phone number object passed");n.selectNumberingPlan(t.countryCallingCode)}else{if(!t.phone)return!1;if(t.country){if(!n.hasCountry(t.country))throw new Error("Unknown country: ".concat(t.country));n.selectNumberingPlan(t.country)}else{if(!t.countryCallingCode)throw new Error("Invalid phone number object passed");n.selectNumberingPlan(t.countryCallingCode)}}if(n.possibleLengths())return I1(t.phone||t.nationalNumber,t.country,n);if(t.countryCallingCode&&n.isNonGeographicCallingCode(t.countryCallingCode))return!0;throw new Error('Missing "possibleLengths" in metadata. Perhaps the metadata has been generated before v1.0.18.')}function I1(t,e,n){return Bp(t,e,n)==="IS_POSSIBLE"}function _n(t,e){return t=t||"",new RegExp("^(?:"+e+")$").test(t)}function I5(t,e){var n=typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=j5(t))||e){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
81
+ `,r}async function j$(t){const e=await t.publicKey.export(),n=await crypto.subtle.exportKey("jwk",e),r=JSON.stringify(n,Object.keys(n).sort()),s=new TextEncoder().encode(r);return Fl(await Ym(s))}const P$=1e3*60*60*24,O$=new o.OpenAPIHono().openapi(o.createRoute({tags:["keys"],method:"get",path:"/signing",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(Ul)}},description:"List of keys"}}}),async t=>{const{signingKeys:e}=await t.env.data.keys.list({q:"type:jwt_signing"}),n=e.filter(r=>"cert"in r).map(r=>r);return t.json(n)}).openapi(o.createRoute({tags:["keys"],method:"get",path:"/signing/{kid}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({kid:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ul}},description:"The requested key"}}}),async t=>{const{kid:e}=t.req.valid("param"),{signingKeys:n}=await t.env.data.keys.list({q:"type:jwt_signing"}),r=n.find(i=>i.kid===e);if(!r)throw new v(404,{message:"Key not found"});return t.json(r)}).openapi(o.createRoute({tags:["keys"],method:"post",path:"/signing/rotate",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Status"}}}),async t=>{const{signingKeys:e}=await t.env.data.keys.list({q:"type:jwt_signing"});for await(const r of e)await t.env.data.keys.update(r.kid,{revoked_at:new Date(Date.now()+P$).toISOString()});const n=await Da({name:`CN=${t.env.ORGANIZATION_NAME}`});return await t.env.data.keys.create({...n,type:"jwt_signing"}),t.text("OK",{status:201})}).openapi(o.createRoute({tags:["keys"],method:"put",path:"/signing/{kid}/revoke",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({kid:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Status"}}}),async t=>{const{kid:e}=t.req.valid("param");if(!await t.env.data.keys.update(e,{revoked_at:new Date().toISOString()}))throw new v(404,{message:"Key not found"});const r=await Da({name:`CN=${t.env.ORGANIZATION_NAME}`});return await t.env.data.keys.create({...r,type:"jwt_signing"}),t.text("OK")}),T$=new o.OpenAPIHono().openapi(o.createRoute({tags:["users"],method:"get",path:"/",request:{query:o.z.object({email:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:o.z.array(Su)}},description:"List of users"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{email:n}=t.req.valid("query"),i=(await Ru(t.env.data.users,e,n)).filter(s=>!s.linked_to);return t.json(i)}),R$=it.extend({clients:o.z.array(Jn)}),jg=o.z.object({enabled_connections:o.z.array(o.z.object({connection_id:o.z.string(),connection:ht.optional()}))}),B$=o.z.array(o.z.string()),L$=new o.OpenAPIHono().openapi(o.createRoute({tags:["clients"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([R$,o.z.array(Jn)])}},description:"List of clients"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i,sort:s,q:a}=t.req.valid("query"),l=(await t.env.data.clients.list(e,{page:n,per_page:r,include_totals:i,sort:Ke(s),q:a})).clients;return i?t.json({clients:l,start:0,limit:10,length:l.length}):t.json(l)}).openapi(o.createRoute({tags:["clients"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Jn}},description:"A client"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.clients.get(e,n);if(!r)throw new v(404);return t.json(r)}).openapi(o.createRoute({tags:["clients"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.clients.remove(e,n))throw new v(404,{message:"Client not found"});return t.text("OK")}).openapi(o.createRoute({tags:["clients"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(Hs.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Jn}},description:"The updated client"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),i=t.req.valid("json");await t.env.data.clients.update(e,n,i);const s=await t.env.data.clients.get(e,n);if(!s)throw new v(404,{message:"Client not found"});return t.json(s)}).openapi(o.createRoute({tags:["clients"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Hs.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:o.z.object(Jn.shape)}},description:"A client"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r={...n,client_secret:n.client_secret||pe()},i=await t.env.data.clients.create(e,r);return t.json(i,{status:201})}).openapi(o.createRoute({tags:["clients"],method:"get",path:"/{id}/connections",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:jg}},description:"List of connections enabled for this client"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.clients.get(e,n);if(!r)throw new v(404,{message:"Client not found"});const i=r.connections&&r.connections.length>0;let s;if(i)s=await Promise.all(r.connections.map(async a=>{const c=await t.env.data.connections.get(e,a);return{connection_id:a,connection:c||void 0}}));else{const{connections:a}=await t.env.data.connections.list(e,{});s=a.filter(c=>c.id).map(c=>({connection_id:c.id,connection:c}))}return t.json({enabled_connections:s})}).openapi(o.createRoute({tags:["clients"],method:"patch",path:"/{id}/connections",request:{body:{content:{"application/json":{schema:B$}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:jg}},description:"Updated list of connections for this client"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.clients.get(e,n))throw new v(404,{message:"Client not found"});const s=[];for(const c of r)await t.env.data.connections.get(e,c)&&s.push(c);await t.env.data.clients.update(e,n,{connections:s});const a=await Promise.all(s.map(async c=>{const l=await t.env.data.connections.get(e,c);return{connection_id:c,connection:l||void 0}}));return t.json({enabled_connections:a})});o.z.object({start:o.z.number(),limit:o.z.number(),length:o.z.number()});Va.extend({email:o.z.string(),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());const U$=it.extend({tenants:o.z.array(Sn)}),D$=new o.OpenAPIHono().openapi(o.createRoute({tags:["tenants","settings"],method:"get",path:"/settings",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Sn}},description:"Current tenant settings"}}}),async t=>{const e=await t.env.data.tenants.get(t.var.tenant_id);if(!e)throw new v(404,{message:"Tenant not found"});return t.json(e)}).openapi(o.createRoute({tags:["tenants","settings"],method:"patch",path:"/settings",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(io.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Sn}},description:"Updated tenant settings"}}}),async t=>{const e=t.req.valid("json"),{id:n,...r}=e,i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new v(404,{message:"Tenant not found"});const s=Dl(i,r);await t.env.data.tenants.update(t.var.tenant_id,s);const a=await t.env.data.tenants.get(t.var.tenant_id);if(!a)throw new v(500,{message:"Failed to retrieve updated tenant"});return t.json(a)}).openapi(o.createRoute({tags:["tenants"],method:"get",path:"/",request:{query:Te},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:o.z.union([o.z.array(Sn),U$])}},description:"List of tenants"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),a=await t.env.data.tenants.list({page:e,per_page:n,include_totals:r,sort:Ke(i),q:s});return r?t.json(a):t.json(a.tenants)}).openapi(o.createRoute({tags:["tenants"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:Sn}},description:"A tenant"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.tenants.get(e);if(!n)throw new v(404);return t.json(n)}).openapi(o.createRoute({tags:["tenants"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param");return await t.env.data.tenants.remove(e),t.text("OK")}).openapi(o.createRoute({tags:["tenants"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(io.shape).partial()}}},params:o.z.object({id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param"),n=t.req.valid("json");return await t.env.data.tenants.update(e,n),t.text("OK")}).openapi(o.createRoute({tags:["tenants"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(io.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"tenant/json":{schema:Sn}},description:"An tenant"}}}),async t=>{const e=t.req.valid("json"),n=await t.env.data.tenants.create(e);return t.json(n,{status:201})}),M$=it.extend({logs:o.z.array(Ws)}),q$=new o.OpenAPIHono().openapi(o.createRoute({tags:["logs"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Ws),M$])}},description:"List of log rows"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),a=await t.env.data.logs.list(t.var.tenant_id,{page:e,per_page:n,include_totals:r,sort:Ke(i),q:s});return r?t.json(a):t.json(a.logs)}).openapi(o.createRoute({tags:["logs"],method:"get",path:"/{id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ws}},description:"A log entry"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.logs.get(t.var.tenant_id,e);if(!n)throw new v(404);return t.json(n)}),F$=17,H$={organization:"org_",connection:"con_",action:"act_",hook:"h_",rule:"rul_",resource_server:"api_",guardian_factor:"gfa_",invite:"inv_"};function Jc(t){const r=Jm("0123456789abcdefghijklmnopqrstuvwxyz",F$)();return`${H$[t]}${r}`}function V$(){return Jc("organization")}function K$(){return Jc("connection")}function G$(){return Jc("hook")}function W$(){return Jc("invite")}const J$=it.extend({hooks:o.z.array(Lr)}),X$=new o.OpenAPIHono().openapi(o.createRoute({tags:["hooks"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Lr),J$])}},description:"List of hooks"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),a=await t.env.data.hooks.list(t.var.tenant_id,{page:e,per_page:n,include_totals:r,sort:Ke(i),q:s});return r?t.json(a):t.json(a.hooks)}).openapi(o.createRoute({tags:["hooks"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:ks}}}},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Lr}},description:"The created hook"}}}),async t=>{const e=t.req.valid("json"),n={...e,hook_id:e.hook_id||G$()},r=await t.env.data.hooks.create(t.var.tenant_id,n);return t.json(r,{status:201})}).openapi(o.createRoute({tags:["hooks"],method:"patch",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({hook_id:o.z.string()}),body:{content:{"application/json":{schema:o.z.union([ks.options[0].omit({hook_id:!0}).partial(),ks.options[1].omit({hook_id:!0}).partial()])}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Lr}},description:"The updated hook"},404:{description:"Hook not found"}}}),async t=>{const{hook_id:e}=t.req.valid("param"),n=t.req.valid("json");await t.env.data.hooks.update(t.var.tenant_id,e,n);const r=await t.env.data.hooks.get(t.var.tenant_id,e);if(!r)throw new v(404,{message:"Hook not found"});return t.json(r)}).openapi(o.createRoute({tags:["hooks"],method:"get",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({hook_id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Lr}},description:"A hook"},404:{description:"Hook not found"}}}),async t=>{const{hook_id:e}=t.req.valid("param"),n=await t.env.data.hooks.get(t.var.tenant_id,e);if(!n)throw new v(404,{message:"Hook not found"});return t.json(n)}).openapi(o.createRoute({tags:["hooks"],method:"delete",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({hook_id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{description:"A hook"}}}),async t=>{const{hook_id:e}=t.req.valid("param");if(!await t.env.data.hooks.remove(t.var.tenant_id,e))throw new v(404,{message:"Hook not found"});return t.text("OK")}),Z$=it.extend({connections:o.z.array(ht)}),Y$=o.z.object({enabled_clients:o.z.array(o.z.object({client_id:o.z.string(),name:o.z.string()}))}),Q$=o.z.array(o.z.object({client_id:o.z.string(),status:o.z.boolean()})),ek=new o.OpenAPIHono().openapi(o.createRoute({tags:["connections"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(ht),Z$])}},description:"List of connectionss"}}}),async t=>{const{page:e,per_page:n,include_totals:r=!1,sort:i,q:s}=t.req.valid("query"),a=await t.env.data.connections.list(t.var.tenant_id,{page:e,per_page:n,include_totals:r,sort:Ke(i),q:s});return r?t.json(a):t.json(a.connections)}).openapi(o.createRoute({tags:["connections"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:ht}},description:"A connection"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.connections.get(t.var.tenant_id,e);if(!n)throw new v(404);return t.json(n)}).openapi(o.createRoute({tags:["connections"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param");if(!await t.env.data.connections.remove(t.var.tenant_id,e))throw new v(404,{message:"Connection not found"});return t.text("OK")}).openapi(o.createRoute({tags:["connections"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(Ks.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:ht}},description:"The updated connection"}}}),async t=>{const{id:e}=t.req.valid("param"),n=t.req.valid("json");if(!await t.env.data.connections.update(t.var.tenant_id,e,n))throw new v(404,{message:"Connection not found"});const i=await t.env.data.connections.get(t.var.tenant_id,e);if(!i)throw new v(404,{message:"Connection not found"});return t.json(i)}).openapi(o.createRoute({tags:["connections"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Ks.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:ht}},description:"A connection"}}}),async t=>{const e=t.req.valid("json"),n={...e,id:e.id||K$()},r=await t.env.data.connections.create(t.var.tenant_id,n);return t.json(r,{status:201})}).openapi(o.createRoute({tags:["connections"],method:"get",path:"/{id}/clients",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Y$}},description:"List of clients enabled for this connection"}}}),async t=>{const{id:e}=t.req.valid("param");if(!await t.env.data.connections.get(t.var.tenant_id,e))throw new v(404,{message:"Connection not found"});const{clients:r}=await t.env.data.clients.list(t.var.tenant_id,{per_page:1e3}),i=r.filter(s=>s.connections?.includes(e)).map(s=>({client_id:s.client_id,name:s.name}));return t.json({enabled_clients:i})}).openapi(o.createRoute({tags:["connections"],method:"patch",path:"/{id}/clients",request:{body:{content:{"application/json":{schema:Q$}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Clients updated successfully"}}}),async t=>{const{id:e}=t.req.valid("param"),n=t.req.valid("json");if(!await t.env.data.connections.get(t.var.tenant_id,e))throw new v(404,{message:"Connection not found"});for(const i of n){const s=await t.env.data.clients.get(t.var.tenant_id,i.client_id);if(!s)continue;const a=s.connections||[];i.status?a.includes(e)||await t.env.data.clients.update(t.var.tenant_id,i.client_id,{connections:[...a,e]}):a.includes(e)&&await t.env.data.clients.update(t.var.tenant_id,i.client_id,{connections:a.filter(c=>c!==e)})}return t.text("OK")}),tk=new o.OpenAPIHono().openapi(o.createRoute({tags:["prompts"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ss}},description:"Branding settings"}}}),async t=>{const e=await t.env.data.promptSettings.get(t.var.tenant_id);return e?t.json(e):t.json(Ss.parse({}))}).openapi(o.createRoute({tags:["prompts"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Ss.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Prompts settings"}}}),async t=>{const e=t.req.valid("json"),n=await t.env.data.promptSettings.get(t.var.tenant_id);return Object.assign(n,e),await t.env.data.promptSettings.set(t.var.tenant_id,n),t.json(n)});let Pg=!1;function jp(t){t.use(async(e,n)=>(Pg||(t.openAPIRegistry.registerComponent("securitySchemes","Bearer",{type:"oauth2",scheme:"bearer",flows:{implicit:{authorizationUrl:`${e.env.AUTH_URL}/authorize`,scopes:{openid:"Basic user information",email:"User email",profile:"User profile information"}}}}),Pg=!0),await n()))}var nk=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return e(n)}catch{return n}})}},rk=decodeURIComponent,ik=/^[\w!#$%&'*.^`|~+-]+$/,ok=/^[ !#-:<-[\]-~]*$/,sk=(t,e)=>{if(t.indexOf(e)===-1)return{};const n=t.trim().split(";"),r={};for(let i of n){i=i.trim();const s=i.indexOf("=");if(s===-1)continue;const a=i.substring(0,s).trim();if(e!==a||!ik.test(a))continue;let c=i.substring(s+1).trim();if(c.startsWith('"')&&c.endsWith('"')&&(c=c.slice(1,-1)),ok.test(c)){r[a]=c.indexOf("%")!==-1?nk(c,rk):c;break}}return r},ak=(t,e,n={})=>{let r=`${t}=${e}`;if(t.startsWith("__Secure-")&&!n.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(t.startsWith("__Host-")){if(!n.secure)throw new Error("__Host- Cookie must have Secure attributes");if(n.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(n.domain)throw new Error("__Host- Cookie must not have Domain attributes")}if(n&&typeof n.maxAge=="number"&&n.maxAge>=0){if(n.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");r+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!=="host"&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+="; HttpOnly"),n.secure&&(r+="; Secure"),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(r+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw new Error("Partitioned Cookie must have Secure attributes");r+="; Partitioned"}return r},xl=(t,e,n)=>(e=encodeURIComponent(e),ak(t,e,n)),ck=(t,e,n)=>{const r=t.req.raw.headers.get("Cookie");{if(!r)return;let i=e;return sk(r,i)[i]}},lk=(t,e,n)=>{let r;return n?.prefix==="secure"?r=xl("__Secure-"+t,e,{path:"/",...n,secure:!0}):n?.prefix==="host"?r=xl("__Host-"+t,e,{...n,path:"/",secure:!0,domain:void 0}):r=xl(t,e,{path:"/",...n}),r},Og=(t,e,n,r)=>{const i=lk(e,n,r);t.header("Set-Cookie",i,{append:!0})},v1=t=>$1(t.replace(/_|-/g,e=>({_:"/","-":"+"})[e]??e)),$1=t=>{const e=atob(t),n=new Uint8Array(new ArrayBuffer(e.length)),r=e.length/2;for(let i=0,s=e.length-1;i<=r;i++,s--)n[i]=e.charCodeAt(i),n[s]=e.charCodeAt(s);return n},k1=(t=>(t.HS256="HS256",t.HS384="HS384",t.HS512="HS512",t.RS256="RS256",t.RS384="RS384",t.RS512="RS512",t.PS256="PS256",t.PS384="PS384",t.PS512="PS512",t.ES256="ES256",t.ES384="ES384",t.ES512="ES512",t.EdDSA="EdDSA",t))(k1||{}),dk=class extends Error{constructor(t){super(`${t} is not an implemented algorithm`),this.name="JwtAlgorithmNotImplemented"}},x1=class extends Error{constructor(t){super(`invalid JWT token: ${t}`),this.name="JwtTokenInvalid"}},uk=class extends Error{constructor(t){super(`token (${t}) is being used before it's valid`),this.name="JwtTokenNotBefore"}},pk=class extends Error{constructor(t){super(`token (${t}) expired`),this.name="JwtTokenExpired"}},fk=class extends Error{constructor(t,e){super(`Invalid "iat" claim, must be a valid number lower than "${t}" (iat: "${e}")`),this.name="JwtTokenIssuedAt"}},Sl=class extends Error{constructor(t,e){super(`expected issuer "${t}", got ${e?`"${e}"`:"none"} `),this.name="JwtTokenIssuer"}},hk=class extends Error{constructor(t){super(`jwt header is invalid: ${JSON.stringify(t)}`),this.name="JwtHeaderInvalid"}},gk=class extends Error{constructor(t){super(`token(${t}) signature mismatched`),this.name="JwtTokenSignatureMismatched"}},mk=class extends Error{constructor(t){super(`required "aud" in jwt payload: ${JSON.stringify(t)}`),this.name="JwtPayloadRequiresAud"}},_k=class extends Error{constructor(t,e){super(`expected audience "${Array.isArray(t)?t.join(", "):t}", got "${e}"`),this.name="JwtTokenAudience"}},Ma=(t=>(t.Encrypt="encrypt",t.Decrypt="decrypt",t.Sign="sign",t.Verify="verify",t.DeriveKey="deriveKey",t.DeriveBits="deriveBits",t.WrapKey="wrapKey",t.UnwrapKey="unwrapKey",t))(Ma||{}),S1=new TextEncoder,yk=new TextDecoder;async function wk(t,e,n,r){const i=vk(e),s=await bk(t,i);return await crypto.subtle.verify(i,s,n,r)}function Tg(t){return $1(t.replace(/-+(BEGIN|END).*/g,"").replace(/\s/g,""))}async function bk(t,e){if(!crypto.subtle||!crypto.subtle.importKey)throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.");if($k(t)){if(t.type==="public"||t.type==="secret")return t;t=await Rg(t)}if(typeof t=="string"&&t.includes("PRIVATE")){const r=await crypto.subtle.importKey("pkcs8",Tg(t),e,!0,[Ma.Sign]);t=await Rg(r)}const n=[Ma.Verify];return typeof t=="object"?await crypto.subtle.importKey("jwk",t,e,!1,n):t.includes("PUBLIC")?await crypto.subtle.importKey("spki",Tg(t),e,!1,n):await crypto.subtle.importKey("raw",S1.encode(t),e,!1,n)}async function Rg(t){if(t.type!=="private")throw new Error(`unexpected key type: ${t.type}`);if(!t.extractable)throw new Error("unexpected private key is unextractable");const e=await crypto.subtle.exportKey("jwk",t),{kty:n}=e,{alg:r,e:i,n:s}=e,{crv:a,x:c,y:l}=e;return{kty:n,alg:r,e:i,n:s,crv:a,x:c,y:l,key_ops:[Ma.Verify]}}function vk(t){switch(t){case"HS256":return{name:"HMAC",hash:{name:"SHA-256"}};case"HS384":return{name:"HMAC",hash:{name:"SHA-384"}};case"HS512":return{name:"HMAC",hash:{name:"SHA-512"}};case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"RS384":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case"RS512":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case"PS256":return{name:"RSA-PSS",hash:{name:"SHA-256"},saltLength:32};case"PS384":return{name:"RSA-PSS",hash:{name:"SHA-384"},saltLength:48};case"PS512":return{name:"RSA-PSS",hash:{name:"SHA-512"},saltLength:64};case"ES256":return{name:"ECDSA",hash:{name:"SHA-256"},namedCurve:"P-256"};case"ES384":return{name:"ECDSA",hash:{name:"SHA-384"},namedCurve:"P-384"};case"ES512":return{name:"ECDSA",hash:{name:"SHA-512"},namedCurve:"P-521"};case"EdDSA":return{name:"Ed25519",namedCurve:"Ed25519"};default:throw new dk(t)}}function $k(t){return Xm()==="node"&&crypto.webcrypto?t instanceof crypto.webcrypto.CryptoKey:t instanceof CryptoKey}var Bg=t=>JSON.parse(yk.decode(v1(t)));function kk(t){if(typeof t=="object"&&t!==null){const e=t;return"alg"in e&&Object.values(k1).includes(e.alg)&&(!("typ"in e)||e.typ==="JWT")}return!1}var xk=async(t,e,n)=>{const{alg:r="HS256",iss:i,nbf:s=!0,exp:a=!0,iat:c=!0,aud:l}=typeof n=="string"?{alg:n}:n||{},d=t.split(".");if(d.length!==3)throw new x1(t);const{header:u,payload:f}=z1(t);if(!kk(u))throw new hk(u);const g=Date.now()/1e3|0;if(s&&f.nbf&&f.nbf>g)throw new uk(t);if(a&&f.exp&&f.exp<=g)throw new pk(t);if(c&&f.iat&&g<f.iat)throw new fk(g,f.iat);if(i){if(!f.iss)throw new Sl(i,null);if(typeof i=="string"&&f.iss!==i)throw new Sl(i,f.iss);if(i instanceof RegExp&&!i.test(f.iss))throw new Sl(i,f.iss)}if(l){if(!f.aud)throw new mk(f);if(!(Array.isArray(f.aud)?f.aud:[f.aud]).some(N=>l instanceof RegExp?l.test(N):typeof l=="string"?N===l:Array.isArray(l)&&l.includes(N)))throw new _k(l,f.aud)}const _=t.substring(0,t.lastIndexOf("."));if(!await wk(e,r,v1(d[2]),S1.encode(_)))throw new gk(t);return f},z1=t=>{try{const[e,n]=t.split("."),r=Bg(e),i=Bg(n);return{header:r,payload:i}}catch{throw new x1(t)}},A1={verify:xk,decode:z1},Sk=A1.verify,zk=A1.decode;async function pu(t){const{signingKeys:e}=await t.keys.list({q:"type:jwt_signing"});return await Promise.all(e.map(async r=>{const s=await new Wc(r.cert).publicKey.export(),a=await crypto.subtle.exportKey("jwk",s);return Nu.parse({...a,kid:r.kid})}))}o.z.object({alg:o.z.literal("RS256"),kty:o.z.literal("RSA"),use:o.z.literal("sig"),n:o.z.string(),e:o.z.string(),kid:o.z.string(),x5t:o.z.string(),x5c:o.z.array(o.z.string())});async function Ak(t){if(t.JWKS_URL&&t.JWKS_SERVICE){const e=await t.JWKS_SERVICE.fetch(t.JWKS_URL);return e.ok?(await e.json()).keys:(console.warn(`JWKS fetch failed with status ${e.status}, falling back to database`),await pu(t.data))}return await pu(t.data)}async function Ek(t,e){try{const{header:n}=zk(e),i=(await Ak(t.env)).find(c=>c.kid===n.kid);if(!i)throw new B(401,{message:"No matching kid found"});const s=await crypto.subtle.importKey("jwk",i,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return await Sk(e,s,"RS256")}catch(n){throw n instanceof v?n:new B(403,{message:"Invalid JWT signature"})}}function Ck(t){return t.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,"{$1}")}function Nk(t,e){return e.startsWith(t)?e:t+e}function Pp(t){return async(e,n)=>{const r=e.req.matchedRoutes.find(c=>c.method.toUpperCase()===e.req.method&&c.path!=="/*");if(!r)return await n();const i=Ck(r.path),s="basePath"in r&&typeof r.basePath=="string"?r.basePath:"",a=t.openAPIRegistry.definitions.find(c=>"route"in c&&Nk(s,c.route.path)===i&&c.route.method.toUpperCase()===e.req.method.toUpperCase());if(a&&"route"in a){const c=a.route.security?.[0]?.Bearer;if(!c?.length)return await n();const l=e.req.header("authorization")||"",[d,u]=l.split(" ");if(d?.toLowerCase()!=="bearer"||!u)throw new B(401,{message:"Missing bearer token"});try{const f=await Ek(e,u);e.set("user_id",f.sub),e.set("user",f),!e.var.tenant_id&&f.tenant_id&&e.set("tenant_id",f.tenant_id);const g=f.permissions||[],_=f.scope?.split(" ")||[];if(c.length&&!(c.some(w=>g.includes(w))||c.some(w=>_.includes(w))))throw new B(403,{message:"Unauthorized"})}catch(f){throw f instanceof v?f:new B(403,{message:"Invalid token"})}}return await n()}}const Ik=new o.OpenAPIHono().openapi(o.createRoute({tags:["emails"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:zs}},description:"Email provider"}}}),async t=>{const e=await t.env.data.emailProviders.get(t.var.tenant_id);if(!e)throw new v(404,{message:"Email provider not found"});return t.json(e)}).openapi(o.createRoute({tags:["emails"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(zs.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const e=t.req.valid("json");return await t.env.data.emailProviders.create(t.var.tenant_id,e),t.text("OK",{status:201})}).openapi(o.createRoute({tags:["emails"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(zs.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const e=t.req.valid("json");return await t.env.data.emailProviders.update(t.var.tenant_id,e),t.text("OK")}),jk=new o.OpenAPIHono().openapi(o.createRoute({tags:["sessions"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ja}},description:"A session"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.sessions.get(t.var.tenant_id,e);if(!n)throw new v(404);return t.json(n)}).openapi(o.createRoute({tags:["sessions"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param");if(!await t.env.data.sessions.remove(t.var.tenant_id,e))throw new v(404,{message:"Session not found"});return t.text("OK")}).openapi(o.createRoute({tags:["sessions"],method:"post",path:"/{id}/revoke",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{202:{description:"Sesssion deletion status"}}}),async t=>{const{id:e}=t.req.valid("param");if(!await t.env.data.sessions.update(t.var.tenant_id,e,{revoked_at:new Date().toDateString()}))throw new v(404,{message:"Session not found"});return t.text("Session deletion request accepted.",{status:202})}),Pk=new o.OpenAPIHono().openapi(o.createRoute({tags:["refresh_tokens"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:ju}},description:"A session"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.refreshTokens.get(t.var.tenant_id,e);if(!n)throw new v(404);return t.json(n)}).openapi(o.createRoute({tags:["refresh_tokens"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param");if(!await t.env.data.refreshTokens.remove(t.var.tenant_id,e))throw new v(404,{message:"Session not found"});return t.text("OK")}),Ok=new o.OpenAPIHono().openapi(o.createRoute({tags:["custom-domains"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(xn)}},description:"List of custom domains"}}}),async t=>{const e=await t.env.data.customDomains.list(t.var.tenant_id);return t.json(e)}).openapi(o.createRoute({tags:["custom-domains"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:xn}},description:"A customDomain"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.customDomains.get(t.var.tenant_id,e);if(!n)throw new v(404);return t.json(n)}).openapi(o.createRoute({tags:["custom-domains"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param");if(!await t.env.data.customDomains.remove(t.var.tenant_id,e))throw new v(404,{message:"Custom domain not found"});return t.text("OK")}).openapi(o.createRoute({tags:["custom-domains"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(xn.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:xn}},description:"The updated custom domain"}}}),async t=>{const{id:e}=t.req.valid("param"),n=t.req.valid("json");if(!await t.env.data.customDomains.update(t.var.tenant_id,e,n))throw new v(404);const i=await t.env.data.customDomains.get(t.var.tenant_id,e);if(!i)throw new v(404);return t.json(i)}).openapi(o.createRoute({tags:["custom-domains"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Eu.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:xn}},description:"The created custom domain"}}}),async t=>{const e=t.req.valid("json"),n=await t.env.data.customDomains.create(t.var.tenant_id,e);return t.json(n,{status:201})}).openapi(o.createRoute({tags:["custom-domains"],method:"post",path:"/{id}/verify",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:xn}},description:"The custom domain"}}}),async()=>{throw new v(501,{message:"Not implemented"})});function Xc(t,e){const n={};for(const[r,i]of Object.entries(e)){if(i==null)continue;const s={};for(const[a,c]of Object.entries(i))typeof c=="function"?s[a]=async(...l)=>{const d=performance.now();try{const u=await c(...l),g=performance.now()-d,_=t.res.headers.get("Server-Timing")||"",w=_?`${_}, ${r}-${a};dur=${g.toFixed(2)}`:`${r}-${a};dur=${g.toFixed(2)}`;return t.res.headers.set("Server-Timing",w),u}catch(u){const g=performance.now()-d,_=t.res.headers.get("Server-Timing")||"",w=_?`${_}, ${r}-${a}-error;dur=${g.toFixed(2)}`:`${r}-${a}-error;dur=${g.toFixed(2)}`;throw t.res.headers.set("Server-Timing",w),u}}:s[a]=c;n[r]=s}return n}async function Zc(t,e){const n=t.req.header("x-forwarded-host");if(n){const i=await t.env.data.customDomains.getByDomain(n);if(i)return t.set("tenant_id",i.tenant_id),t.set("custom_domain",n),t.set("host",n),await e()}const r=t.req.header("host");if(r){t.set("host",r);const i=r.split(".");if(i.length>1&&typeof i[0]=="string"){const s=i[0];await t.env.data.tenants.get(s)&&t.set("tenant_id",s)}}else t.set("host",new URL(ic(t.env)).host);if(!t.var.tenant_id){const i=t.req.header("tenant-id");i&&t.set("tenant_id",i)}return await e()}const Tk=o.z.object({name:o.z.string(),version:o.z.string(),env:o.z.object({node:o.z.string().optional()}).optional()});function Rk(t){if(t)try{let e=t;try{e=atob(t)}catch{}try{const n=JSON.parse(e);return Tk.parse(n)}catch{}}catch{return}}const Yc=async(t,e)=>{const n=t.req.query("auth0Client")?.slice(0,255),i=(t.req.header("x-forwarded-host")&&t.req.header("x-forwarded-for")?t.req.header("x-forwarded-for")?.split(",")[0]?.trim():t.req.header("cf-connecting-ip")||t.req.header("x-real-ip"))?.slice(0,45),s=t.req.header("user-agent")?.slice(0,512),a=t.req.header("cf-ipcountry")?.slice(0,2),c=n?Rk(n):void 0;c&&t.set("auth0_client",c),i&&t.set("ip",i),s&&t.set("useragent",s),a&&t.set("countryCode",a),await e()};function Bk(t,e,n,r){try{const i=`${t}:${e}:${JSON.stringify(n)}`;return r?`${r}:${i}`:i}catch{const s=`${t}:${e}:${Date.now()}-${Math.random()}`;return r?`${r}:${s}`:s}}function Qc(t,e){const{cache:n,defaultTtl:r,customTtls:i={},excludeMethods:s=[],cacheEntities:a=[],keyPrefix:c}=e,l=new Set(s),d=a.length===0,u=new Set(a),f={};for(const[g,_]of Object.entries(t)){if(_==null)continue;const w=d||u.has(g),k={};for(const[z,N]of Object.entries(_))if(typeof N=="function"){if(!w){k[z]=N;continue}const I=`${g}:${z}`;if(l.has(I)){k[z]=N;continue}const S=i[I]??r,E=["create","update","remove","delete","set","used"].includes(z);k[z]=async(...P)=>{if(E)return await N.apply(_,P);const G=Bk(g,z,P,c),Z=await n.get(G);if(Z!==null)if(Z&&typeof Z=="object"&&"isCachedNull"in Z){const M=Z;return M.isCachedNull?null:M.value}else return Z;const W=await N.apply(_,P);if(S>=0)if(W!==null)await n.set(G,W,S);else{const M={value:null,isCachedNull:!0};await n.set(G,M,S)}return W}}else k[z]=N;f[g]=k}return f}class Lk{constructor(e={}){this.config=e;const n=e.cleanupIntervalMs;n&&n>0&&(this.cleanupTimer=setInterval(()=>{this.cleanupExpired()},n))}cache=new Map;accessOrder=new Map;accessCounter=0;cleanupTimer;async get(e){const n=this.cache.get(e);return n?n.expiresAt&&n.expiresAt<new Date?(this.cache.delete(e),this.accessOrder.delete(e),null):(this.accessOrder.set(e,++this.accessCounter),n.value):null}async set(e,n,r){let i;const s=r??this.config.defaultTtlSeconds,a=s!==void 0,c=a?Math.max(0,s):0;a&&(i=new Date(Date.now()+(c>0?c*1e3:-1))),this.config.maxEntries&&this.cache.size>=this.config.maxEntries&&!this.cache.has(e)&&this.evictLeastRecentlyUsed();const l={value:n,expiresAt:i};this.cache.set(e,l),this.accessOrder.set(e,++this.accessCounter)}async delete(e){const n=this.cache.has(e);return this.cache.delete(e),this.accessOrder.delete(e),n}async clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}getStats(){return{size:this.cache.size,maxEntries:this.config.maxEntries,defaultTtlSeconds:this.config.defaultTtlSeconds}}cleanupExpired(){const e=new Date,n=[];for(const[r,i]of this.cache.entries())i.expiresAt&&i.expiresAt<e&&n.push(r);for(const r of n)this.cache.delete(r),this.accessOrder.delete(r)}evictLeastRecentlyUsed(){let e=null,n=1/0;for(const[r,i]of this.accessOrder.entries())i<n&&(n=i,e=r);e&&(this.cache.delete(e),this.accessOrder.delete(e))}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0)}}function ds(t={}){return new Lk(t)}const Uk=it.extend({forms:o.z.array(Br)}),Dk=new o.OpenAPIHono().openapi(o.createRoute({tags:["forms"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Br),Uk])}},description:"List of forms"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i=!1,sort:s,q:a}=t.req.valid("query"),c=await t.env.data.forms.list(e,{page:n,per_page:r,include_totals:i,sort:Ke(s),q:a});return i?t.json(c):t.json(c.forms)}).openapi(o.createRoute({tags:["forms"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Br}},description:"A form"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.forms.get(e,n);if(!r)throw new v(404);return t.json(r)}).openapi(o.createRoute({tags:["forms"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.forms.remove(e,n))throw new v(404,{message:"Form not found"});return t.text("OK")}).openapi(o.createRoute({tags:["forms"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(Gs.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Br}},description:"The updated form"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.forms.update(e,n,r))throw new v(404,{message:"Form not found"});const s=await t.env.data.forms.get(e,n);if(!s)throw new v(404,{message:"Form not found"});return t.json(s)}).openapi(o.createRoute({tags:["forms"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Gs.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Br}},description:"A form"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.forms.create(e,n);return t.json(r,{status:201})}),Mk=it.extend({roles:o.z.array(Yn)}),qk=new o.OpenAPIHono().openapi(o.createRoute({tags:["roles"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Yn),Mk])}},description:"List of roles"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),a=await t.env.data.roles.list(t.var.tenant_id,{page:e,per_page:n,include_totals:r,sort:Ke(i),q:s});return r?t.json(a):t.json(a.roles)}).openapi(o.createRoute({tags:["roles"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Yn}},description:"A role"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.roles.get(t.var.tenant_id,e);if(!n)throw new v(404);return t.json(n)}).openapi(o.createRoute({tags:["roles"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:Xs}}}},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Yn}},description:"Role created"}}}),async t=>{const e=t.req.valid("json"),n=await t.env.data.roles.create(t.var.tenant_id,e);return t.json(n,{status:201})}).openapi(o.createRoute({tags:["roles"],method:"patch",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:Xs.partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Yn}},description:"Updated role"}}}),async t=>{const{id:e}=t.req.valid("param"),n=t.req.valid("json");if(!await t.env.data.roles.update(t.var.tenant_id,e,n))throw new v(404);const i=await t.env.data.roles.get(t.var.tenant_id,e);return t.json(i)}).openapi(o.createRoute({tags:["roles"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param");if(!await t.env.data.roles.remove(t.var.tenant_id,e))throw new v(404);return t.text("OK")}).openapi(o.createRoute({tags:["roles"],method:"get",path:"/{id}/permissions",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),query:Te},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Im}},description:"Role permissions"}}}),async t=>{const{id:e}=t.req.valid("param"),{page:n,per_page:r,sort:i,q:s}=t.req.valid("query");if(!await t.env.data.roles.get(t.var.tenant_id,e))throw new v(404,{message:"Role not found"});const c=await t.env.data.rolePermissions.list(t.var.tenant_id,e,{page:n,per_page:r,include_totals:!1,sort:Ke(i),q:s});return t.json(c)}).openapi(o.createRoute({tags:["roles"],method:"post",path:"/{id}/permissions",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),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:["auth:write"]}],responses:{201:{description:"Permissions assigned to role"}}}),async t=>{const{id:e}=t.req.valid("param"),{permissions:n}=t.req.valid("json");if(!await t.env.data.roles.get(t.var.tenant_id,e))throw new v(404,{message:"Role not found"});if(!await t.env.data.rolePermissions.assign(t.var.tenant_id,e,n.map(s=>({role_id:e,resource_server_identifier:s.resource_server_identifier,permission_name:s.permission_name}))))throw new v(500,{message:"Failed to assign permissions to role"});return t.json({message:"Permissions assigned successfully"},{status:201})}).openapi(o.createRoute({tags:["roles"],method:"delete",path:"/{id}/permissions",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),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:["auth:write"]}],responses:{200:{description:"Permissions removed from role"}}}),async t=>{const{id:e}=t.req.valid("param"),{permissions:n}=t.req.valid("json");if(!await t.env.data.roles.get(t.var.tenant_id,e))throw new v(404,{message:"Role not found"});if(!await t.env.data.rolePermissions.remove(t.var.tenant_id,e,n))throw new v(500,{message:"Failed to remove permissions from role"});return t.json({message:"Permissions removed successfully"})}),Fk=it.extend({resource_servers:o.z.array(Zn)}),Hk=new o.OpenAPIHono().openapi(o.createRoute({tags:["resource-servers"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Zn),Fk])}},description:"List of resource servers"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i=!1,sort:s,q:a}=t.req.valid("query"),c=await t.env.data.resourceServers.list(e,{page:n,per_page:r,include_totals:i,sort:Ke(s),q:a});return i?t.json(c):t.json(c.resource_servers)}).openapi(o.createRoute({tags:["resource-servers"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Zn}},description:"A resource server"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.resourceServers.get(e,n);if(!r)throw new v(404);return t.json(r)}).openapi(o.createRoute({tags:["resource-servers"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.resourceServers.remove(e,n))throw new v(404,{message:"Resource server not found"});return t.text("OK")}).openapi(o.createRoute({tags:["resource-servers"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(Js.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Zn}},description:"The updated resource server"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.resourceServers.update(e,n,r))throw new v(404,{message:"Resource server not found"});const s=await t.env.data.resourceServers.get(e,n);if(!s)throw new v(404,{message:"Resource server not found"});return t.json(s)}).openapi(o.createRoute({tags:["resource-servers"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Js.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Zn}},description:"A resource server"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.resourceServers.create(e,n);return t.json(r,{status:201})}),Vk=o.z.object({per_page:o.z.string().min(1).optional().default("50").transform(t=>parseInt(t,10)).openapi({description:"Number of results per page. Defaults to 50."}),page:o.z.string().min(0).optional().default("0").transform(t=>parseInt(t,10)).openapi({description:"Page index of the results to return. First page is 0."}),include_totals:o.z.string().optional().default("false").transform(t=>t==="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().min(1).optional().transform(t=>t?parseInt(t,10):void 0).openapi({description:"Number of results per page. Defaults to 50."}),audience:o.z.string().optional().openapi({description:"Optional filter on audience."}),client_id:o.z.string().optional().openapi({description:"Optional filter on client_id."}),allow_any_organization:o.z.string().optional().transform(t=>t==="true"?!0:t==="false"?!1:void 0).openapi({description:"Optional filter on allow_any_organization."}),subject_type:o.z.enum(["client","user"]).optional().openapi({description:"EA 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."})}),Kk=it.extend({client_grants:o.z.array(Xn)}),Gk=new o.OpenAPIHono().openapi(o.createRoute({tags:["client-grants"],method:"get",path:"/",request:{query:Vk,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Xn),Kk])}},description:"List of client grants"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i=!1,from:s,take:a,audience:c,client_id:l,allow_any_organization:d,subject_type:u}=t.req.valid("query"),f=[];l&&f.push(`client_id:"${l}"`),c&&f.push(`audience:"${c}"`),d!==void 0&&f.push(`allow_any_organization:${d}`),u&&f.push(`subject_type:"${u}"`),s&&f.push(`id:>${s}`);const g=f.length>0?f.join(" AND "):void 0,_=a??r,w=await t.env.data.clientGrants.list(e,{page:n,per_page:_,include_totals:i,q:g});return i?t.json(w):t.json(w.client_grants)}).openapi(o.createRoute({tags:["client-grants"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Xn}},description:"A client grant"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.clientGrants.get(e,n);if(!r)throw new v(404,{message:"Client grant not found"});return t.json(r)}).openapi(o.createRoute({tags:["client-grants"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.clientGrants.remove(e,n))throw new v(404,{message:"Client grant not found"});return t.text("OK")}).openapi(o.createRoute({tags:["client-grants"],method:"patch",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Vs.shape).partial()}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Xn}},description:"The updated client grant"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.clientGrants.get(e,n))throw new v(404,{message:"Client grant not found"});if(!await t.env.data.clientGrants.update(e,n,r))throw new v(500,{message:"Failed to update client grant"});const a=await t.env.data.clientGrants.get(e,n);if(!a)throw new v(404,{message:"Client grant not found"});return t.json(a)}).openapi(o.createRoute({tags:["client-grants"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(Vs.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Xn}},description:"A client grant"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.clientGrants.create(e,n);return t.json(r,{status:201})}),Wk=o.z.object({page:o.z.string().optional().default("0").transform(t=>parseInt(t,10)).openapi({description:"Page index of the results to return. First page is 0."}),per_page:o.z.string().optional().default("50").transform(t=>parseInt(t,10)).openapi({description:"Number of results per page. Defaults to 50."}),include_totals:o.z.string().optional().default("false").transform(t=>t==="true").openapi({description:"When true, return results inside an object that also contains the start and limit. When false (default), a direct array of results is returned."}),fields:o.z.string().optional().openapi({description:"Comma-separated list of fields to include or exclude (based on value provided for include_fields) in the result. Leave empty to retrieve all fields."}),include_fields:o.z.string().optional().default("true").transform(t=>t==="true").openapi({description:"Whether specified fields are to be included (true) or excluded (false). Defaults to true."}),sort:o.z.string().optional().default("created_at:-1").openapi({description:"Field to sort by. Use field:order where order is 1 for ascending and -1 for descending. Defaults to created_at:-1."})}),Jk=o.z.object({invitations:o.z.array(oo),start:o.z.number(),limit:o.z.number(),length:o.z.number()}),Xk=Cu.omit({organization_id:!0,invitation_url:!0}),Zk=it.extend({organizations:o.z.array(zn)}),Op=o.z.object({user_id:o.z.string().openapi({description:"ID of this user"}),email:o.z.string().email().optional().openapi({description:"Email address of this user",format:"email"}),roles:o.z.array(o.z.object({})).default([]).openapi({description:"Array of roles assigned to this user in the organization"})}),Yk=o.z.object({start:o.z.number().openapi({description:"Start index of the current page"}),limit:o.z.number().openapi({description:"Number of items per page"}),total:o.z.number().openapi({description:"Total number of members"}),members:o.z.array(Op).openapi({description:"Array of organization members"})}),Qk=o.z.object({next:o.z.string().optional().openapi({description:"Checkpoint ID to be used to retrieve the next set of results"}),members:o.z.array(Op).openapi({description:"Array of organization members"})}),e5=o.z.object({members:o.z.array(o.z.string()).openapi({description:"Array of user IDs to add to the organization"})}),t5=o.z.object({members:o.z.array(o.z.string()).openapi({description:"Array of user IDs to remove from the organization"})}),n5=new o.OpenAPIHono().openapi(o.createRoute({tags:["organizations"],method:"get",path:"/",request:{query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([Zk,o.z.array(zn)])}},description:"List of organizations"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i,sort:s,q:a}=t.req.valid("query"),c=await t.env.data.organizations.list(e,{page:n,per_page:r,include_totals:i,sort:Ke(s),q:a});return i?t.json(c):t.json(c.organizations)}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:zn}},description:"An organization"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.organizations.get(e,n);if(!r)throw new v(404,{message:"Organization not found"});return t.json(r)}).openapi(o.createRoute({tags:["organizations"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Organization deleted successfully"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.organizations.remove(e,n))throw new v(404,{message:"Organization not found"});return t.text("OK")}).openapi(o.createRoute({tags:["organizations"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:Ys.partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:zn}},description:"The updated organization"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.organizations.update(e,n,r))throw new v(404,{message:"Organization not found"});const s=await t.env.data.organizations.get(e,n);if(!s)throw new v(404,{message:"Organization not found"});return t.json(s)}).openapi(o.createRoute({tags:["organizations"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:Ys}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:zn}},description:"The created organization"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r={...n,id:n.id||V$()},i=await t.env.data.organizations.create(e,r);return t.json(i,{status:201})}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/members",request:{params:o.z.object({id:o.z.string()}),query:Te,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Op),Yk,Qk])}},description:"List of organization members"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),{page:r,per_page:i,include_totals:s,sort:a}=t.req.valid("query");if(!await t.env.data.organizations.get(e,n))throw new v(404,{message:"Organization not found"});const l=await t.env.data.userOrganizations.list(e,{page:r,per_page:i,include_totals:s,sort:Ke(a),q:`organization_id:${n}`}),d=[];for(const u of l.userOrganizations){const f=await t.env.data.users.get(e,u.user_id);f&&d.push({user_id:f.user_id,email:f.email||void 0,roles:[]})}return s?t.json({start:l.start,limit:l.limit,total:l.length,members:d}):t.json(d)}).openapi(o.createRoute({tags:["organizations"],method:"post",path:"/{id}/members",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:e5}}}},security:[{Bearer:["auth:write"]}],responses:{204:{description:"Members added successfully"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),{members:r}=t.req.valid("json");if(!await t.env.data.organizations.get(e,n))throw new v(404,{message:"Organization not found"});for(const s of r)(await t.env.data.userOrganizations.list(e,{q:`user_id:${s}`,per_page:1})).userOrganizations.some(l=>l.organization_id===n)||await t.env.data.userOrganizations.create(e,{user_id:s,organization_id:n});return new Response(null,{status:204})}).openapi(o.createRoute({tags:["organizations"],method:"delete",path:"/{id}/members",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:t5}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Members removed successfully"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),{members:r}=t.req.valid("json");for(const i of r){const a=(await t.env.data.userOrganizations.list(e,{q:`user_id:${i}`,per_page:100})).userOrganizations.find(c=>c.organization_id===n);a&&await t.env.data.userOrganizations.remove(e,a.id)}return t.json({message:"Members removed successfully"})}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/members/{user_id}/roles",request:{params:o.z.object({id:o.z.string(),user_id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),query:Te},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Zs}},description:"User roles in organization"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n,user_id:r}=t.req.valid("param");if(!await t.env.data.organizations.get(e,n))throw new v(404,{message:"Organization not found"});if(!await t.env.data.users.get(e,r))throw new v(404,{message:"User not found"});const a=await t.env.data.userRoles.list(e,r,void 0,n);return t.json(a)}).openapi(o.createRoute({tags:["organizations"],method:"post",path:"/{id}/members/{user_id}/roles",request:{params:o.z.object({id:o.z.string(),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()).openapi({description:"List of role IDs to associate with the user"})})}}}},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Roles assigned successfully"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n,user_id:r}=t.req.valid("param"),{roles:i}=t.req.valid("json");if(!await t.env.data.organizations.get(e,n))throw new v(404,{message:"Organization not found"});if(!await t.env.data.users.get(e,r))throw new v(404,{message:"User not found"});for(const c of i){if(!await t.env.data.roles.get(e,c))throw new v(400,{message:`Role ${c} not found`});if(!await t.env.data.userRoles.create(e,r,c,n))throw new v(500,{message:`Failed to assign role ${c} to user`})}return t.json({message:"Roles assigned successfully"},{status:201})}).openapi(o.createRoute({tags:["organizations"],method:"delete",path:"/{id}/members/{user_id}/roles",request:{params:o.z.object({id:o.z.string(),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()).openapi({description:"List of role IDs to remove from the user"})})}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Roles removed successfully"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n,user_id:r}=t.req.valid("param"),{roles:i}=t.req.valid("json");if(!await t.env.data.organizations.get(e,n))throw new v(404,{message:"Organization not found"});if(!await t.env.data.users.get(e,r))throw new v(404,{message:"User not found"});for(const c of i)if(!await t.env.data.userRoles.remove(e,r,c,n))throw new v(500,{message:`Failed to remove role ${c} from user`});return t.json({message:"Roles removed successfully"})}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/roles",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()}),query:Te},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Zs}},description:"List of roles available in organization"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),{page:r,per_page:i,sort:s,q:a}=t.req.valid("query");if(!await t.env.data.organizations.get(e,n))throw new v(404,{message:"Organization not found"});const l=await t.env.data.roles.list(e,{page:r,per_page:i,sort:Ke(s),q:a});return t.json(l.roles)}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/invitations",request:{params:o.z.object({id:o.z.string().openapi({description:"Organization ID",param:{name:"id",in:"path"}})}),query:Wk,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(oo),Jk])}},description:"List of organization invitations"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),{page:r,per_page:i,include_totals:s,fields:a,include_fields:c,sort:l}=t.req.valid("query");if(!await t.env.data.organizations.get(e,n))throw new v(404,{message:"Organization not found"});let f=(await t.env.data.invites.list(e,{page:r,per_page:i})).invites.filter(g=>g.organization_id===n);if(l){const g=Ke(l);if(g){const{sort_by:_,sort_order:w}=g;f.sort((k,z)=>{const N=k[_],I=z[_];if(N===void 0||I===void 0||N===I)return 0;const S=N<I?-1:1;return w==="asc"?S:-S})}}if(a){const g=a.split(",").map(_=>_.trim());f=f.map(_=>{const w={};for(const k of Object.keys(_))(c?g.includes(k):!g.includes(k))&&(w[k]=_[k]);return w})}return s?t.json({invitations:f,start:r*i,limit:i,length:f.length}):t.json(f)}).openapi(o.createRoute({tags:["organizations"],method:"get",path:"/{id}/invitations/{invitation_id}",request:{params:o.z.object({id:o.z.string().openapi({description:"Organization ID",param:{name:"id",in:"path"}}),invitation_id:o.z.string().openapi({description:"Invitation ID",param:{name:"invitation_id",in:"path"}})}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:oo}},description:"An invitation"},404:{description:"Invitation not found"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n,invitation_id:r}=t.req.valid("param"),i=await t.env.data.invites.get(e,r);if(!i||i.organization_id!==n)throw new v(404,{message:"Invitation not found"});return t.json(i)}).openapi(o.createRoute({tags:["organizations"],method:"post",path:"/{id}/invitations",request:{params:o.z.object({id:o.z.string().openapi({description:"Organization ID",param:{name:"id",in:"path"}})}),body:{content:{"application/json":{schema:Xk}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:oo}},description:"The created invitation"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.organizations.get(e,n))throw new v(404,{message:"Organization not found"});const a=`https://invite.placeholder/${W$()}`,c={...r,organization_id:n,invitation_url:a},l=await t.env.data.invites.create(e,c);return t.json(l,{status:201})}).openapi(o.createRoute({tags:["organizations"],method:"delete",path:"/{id}/invitations/{invitation_id}",request:{params:o.z.object({id:o.z.string().openapi({description:"Organization ID",param:{name:"id",in:"path"}}),invitation_id:o.z.string().openapi({description:"Invitation ID",param:{name:"invitation_id",in:"path"}})}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{204:{description:"Invitation deleted successfully"},404:{description:"Invitation not found"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n,invitation_id:r}=t.req.valid("param"),i=await t.env.data.invites.get(e,r);if(!i||i.organization_id!==n)throw new v(404,{message:"Invitation not found"});if(!await t.env.data.invites.remove(e,r))throw new v(404,{message:"Invitation not found"});return t.body(null,{status:204})});function r5(t){const e=new o.OpenAPIHono;e.use(M0({origin:r=>r&&t.allowedOrigins?.includes(r)?r:"",allowHeaders:["Tenant-Id","Content-Type","Content-Range","Auth0-Client","Authorization","Range","Upgrade-Insecure-Requests"],allowMethods:["POST","PUT","GET","DELETE","PATCH","OPTIONS"],exposeHeaders:["Content-Length","Content-Range"],maxAge:600,credentials:!0})),jp(e),e.use(async(r,i)=>{const s=qo(r,t.dataAdapter),a=ds({defaultTtlSeconds:0,maxEntries:100,cleanupIntervalMs:0}),c=Qc(s,{defaultTtl:0,cacheEntities:["tenants","connections","clients","legacyClients","branding","themes","promptSettings","forms"],cache:a});return r.env.data=Xc(r,c),i()}),e.use(Yc).use(Zc).use(Pp(e));const n=e.route("/branding",Ab).route("/custom-domains",Ok).route("/email/providers",Ik).route("/users",P3).route("/keys",O$).route("/users-by-email",T$).route("/clients",L$).route("/client-grants",Gk).route("/tenants",D$).route("/logs",q$).route("/hooks",X$).route("/connections",ek).route("/prompts",tk).route("/sessions",jk).route("/refresh_tokens",Pk).route("/forms",Dk).route("/roles",qk).route("/resource-servers",Hk).route("/organizations",n5);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Management API"},servers:[{url:"/api/v2",description:"API V2"}],security:[{oauth2:["openid","email","profile"]}]}),n}function i5(t,e){Object.keys(e).forEach(n=>{const r=e[n];r!=null&&r.length&&t.searchParams.set(n,r)})}function mn(t){if(t)return`${t.name}/${t.version}${t.env?.node?` (env: node/${t.env.node})`:""}`}async function Ai(t,e){const n=await t.data.legacyClients.get(e);if(!n)throw new B(403,{message:"Client not found"});let r=n;if(t.DEFAULT_CLIENT_ID||t.DEFAULT_TENANT_ID){const i=t.DEFAULT_CLIENT_ID?await t.data.legacyClients.get(t.DEFAULT_CLIENT_ID):void 0,s=await t.data.connections.list(n.tenant.id),a=t.DEFAULT_TENANT_ID?await t.data.connections.list(t.DEFAULT_TENANT_ID):{connections:[]},c=s.connections.map(l=>{const d=a.connections?.find(f=>f.name===l.name);if(!d?.options)return l;const u=ht.parse({...d||{},...l});return u.options=Dr.parse({...d.options||{},...l.options}),u}).filter(l=>l);r={...n,web_origins:[...i?.web_origins||[],...n.web_origins||[]],allowed_logout_urls:[...i?.allowed_logout_urls||[],...n.allowed_logout_urls||[]],callbacks:[...i?.callbacks||[],...n.callbacks||[]],connections:c,tenant:{...i?.tenant||{},...n.tenant}}}return{...r,web_origins:[...r.web_origins||[],`${De(t)}login`],allowed_logout_urls:[...r.allowed_logout_urls||[],t.ISSUER],callbacks:[...r.callbacks||[],`${De(t)}info`]}}async function Lg(t,e,n,r){if(!r.state)throw new B(400,{message:"State not found"});const i=e.connections.find(l=>l.name===n);if(!i)throw t.set("client_id",e.client_id),await ie(t,e.tenant.id,{type:te.FAILED_LOGIN,description:"Connection not found"}),new B(403,{message:"Connection Not Found"});let s=await t.env.data.loginSessions.get(e.tenant.id,r.state);if(!s){const l=t.get("ip"),d=t.get("useragent"),u=t.get("auth0_client");s=await t.env.data.loginSessions.create(e.tenant.id,{expires_at:new Date(Date.now()+or*1e3).toISOString(),authParams:r,csrf_token:pe(),ip:l,useragent:d,auth0Client:mn(u)})}const c=await j_(t,i.strategy).getRedirect(t,i);return await t.env.data.codes.create(e.tenant.id,{login_id:s.id,code_id:c.code,code_type:"oauth2_state",connection_id:i.id,code_verifier:c.codeVerifier,expires_at:new Date(Date.now()+av*1e3).toISOString()}),new Response(null,{status:302,headers:{location:c.redirectUrl}})}async function Ug(t,{code:e,state:n}){const{env:r}=t,i=await r.data.codes.get(t.var.tenant_id||"",n,"oauth2_state");if(!i||!i.connection_id)throw new B(403,{message:"State not found"});const s=await r.data.loginSessions.get(t.var.tenant_id||"",i.login_id);if(!s)throw new B(403,{message:"Session not found"});if(s.authorization_url){const w=new URL(s.authorization_url).hostname,k=t.var.host||"";if(w!==k&&w){const z=new URL(`https://${w}/callback`);return z.searchParams.set("state",n),z.searchParams.set("code",e),new Response("Redirecting",{status:307,headers:{location:z.toString()}})}}const a=await Ai(r,s.authParams.client_id);t.set("client_id",a.client_id),t.set("tenant_id",a.tenant.id);const c=a.connections.find(w=>w.id===i.connection_id);if(!c)throw await ie(t,a.tenant.id,{type:te.FAILED_LOGIN,description:"Connection not found"}),new B(403,{message:"Connection not found"});if(t.set("connection",c.name),!s.authParams.redirect_uri)throw await ie(t,a.tenant.id,{type:te.FAILED_LOGIN,description:"Redirect URI not defined"}),new B(403,{message:"Redirect URI not defined"});const d=await j_(t,c.strategy).validateAuthorizationCodeAndGetUser(t,c,e,i.code_verifier),{sub:u,...f}=d;t.set("user_id",u);const g=d.email?.toLocaleLowerCase()||`${c.name}.${u}@${new URL(t.env.ISSUER).hostname}`;t.set("username",g);const _=await nc(t,{client:a,username:g,provider:c.strategy,connection:c.name,userId:u,profileData:f,isSocial:!0,ip:t.var.ip});return Gt(t,{client:a,authParams:s.authParams,loginSession:s,user:_,authStrategy:{strategy:c.strategy,strategy_type:"social"}})}function Dg(t){return t===Ct.WEB_MESSAGE}async function $s(t,e,n,r,i,s){const a=await t.env.data.codes.get(t.var.tenant_id||"",e,"oauth2_state");if(!a)throw new v(400,{message:"State not found"});const c=await t.env.data.loginSessions.get(t.var.tenant_id,a.login_id);if(!c)throw new v(400,{message:"Login not found"});const{redirect_uri:l}=c.authParams;if(!l)throw new v(400,{message:"Redirect uri not found"});ie(t,t.var.tenant_id,{type:te.FAILED_LOGIN,description:`Failed connection login: ${i} ${n}, ${r}`});const d=new URL(l);return i5(d,{error:n,error_description:r,error_reason:s,error_code:i,state:c.authParams.state}),t.redirect(`${De(t.env)}login/identifier?state=${c.id}&error=${n}`)}const o5=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string(),code:o.z.string().optional(),scope:o.z.string().optional(),hd:o.z.string().optional(),error:o.z.string().optional(),error_description:o.z.string().optional(),error_code:o.z.string().optional(),error_reason:o.z.string().optional()})},responses:{302:{description:"Redirect to the client's redirect uri"},400:{description:"Bad Request",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}},500:{description:"Internal Server Error",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async t=>{const{state:e,code:n,error:r,error_description:i,error_code:s,error_reason:a}=t.req.valid("query");if(r)return $s(t,e,r,i,s,a);if(!n)throw new v(400,{message:"Code is required"});try{const c=await Ug(t,{code:n,state:e});if(!(c instanceof Response))throw new v(500,{message:"Internal server error"});return c}catch(c){if(c instanceof B&&c.status===400){const l=await t.env.data.codes.get(t.var.tenant_id||"",e,"oauth2_state");if(l){const d=await t.env.data.loginSessions.get(t.var.tenant_id,l.login_id);if(d&&Dg(d.authParams.response_mode)){let u="access_denied";try{u=JSON.parse(c.message).message||u}catch{u=c.message||u}return $s(t,e,"access_denied",u)}}}throw c}}).openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({state:o.z.string(),code:o.z.string().optional(),scope:o.z.string().optional(),hd:o.z.string().optional(),error:o.z.string().optional(),error_description:o.z.string().optional(),error_code:o.z.string().optional(),error_reason:o.z.string().optional()})}}}},responses:{302:{description:"Redirect to the client's redirect uri"},400:{description:"Bad Request",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}},500:{description:"Internal Server Error",content:{"application/json":{schema:o.z.object({message:o.z.string()})}}}}}),async t=>{const{state:e,code:n,error:r,error_description:i,error_code:s,error_reason:a}=t.req.valid("form");if(r)return $s(t,e,r,i,s,a);if(!n)throw new v(400,{message:"Code is required"});try{const c=await Ug(t,{code:n,state:e});if(!(c instanceof Response))throw new v(500,{message:"Internal server error"});return c}catch(c){if(c instanceof B&&c.status===400){const l=await t.env.data.codes.get(t.var.tenant_id||"",e,"oauth2_state");if(l){const d=await t.env.data.loginSessions.get(t.var.tenant_id,l.login_id);if(d&&Dg(d.authParams.response_mode)){let u="access_denied";try{u=JSON.parse(c.message).message||u}catch{u=c.message||u}return $s(t,e,"access_denied",u)}}}throw c}});function Tp(t,e=[],n={}){try{const r=new URL(t);return e.some(i=>{try{return s5(r,new URL(i),n)}catch{return!1}})}catch{return!1}}function s5(t,e,n={}){if(t.protocol!==e.protocol)return!1;if(n.allowPathWildcards&&e.pathname.includes("*")){const r=e.pathname.replace(/\*/g,".*").replace(/\//g,"\\/");if(!new RegExp(`^${r}$`).test(t.pathname))return!1}else if(t.pathname!==e.pathname)return!1;if(n.allowSubDomainWildcards&&e.hostname.startsWith("*.")&&e.hostname.split(".").length>2&&["http:","https:"].includes(e.protocol)){const r=e.hostname.split(".").slice(1).join(".");return t.hostname===r||t.hostname.endsWith("."+r)}return t.hostname===e.hostname}const a5=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{query:o.z.object({client_id:o.z.string(),returnTo:o.z.string().optional()}),header:o.z.object({cookie:o.z.string().optional()})},responses:{302:{description:"Log the user out"}}}),async t=>{const{client_id:e,returnTo:n}=t.req.valid("query"),r=await t.env.data.legacyClients.get(e);if(!r)return t.text("OK");const i=await t.env.data.legacyClients.get("DEFAULT_CLIENT");t.set("client_id",e),t.set("tenant_id",r.tenant.id);const s=n||t.req.header("referer");if(!s)return t.text("OK");if(!Tp(s,[...r.allowed_logout_urls||[],...i?.allowed_logout_urls||[]],{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new v(400,{message:"Invalid redirect uri"});const a=t.req.header("cookie");if(a){const c=Wr(r.tenant.id,a);if(c){const l=await t.env.data.sessions.get(r.tenant.id,c);if(l){const d=await t.env.data.users.get(r.tenant.id,l.user_id);d&&(t.set("user_id",d.user_id),t.set("connection",d.connection));const u=await t.env.data.refreshTokens.list(r.tenant.id,{q:`session_id=${c}`,page:0,per_page:100,include_totals:!1});await Promise.all(u.refresh_tokens.map(f=>t.env.data.refreshTokens.remove(r.tenant.id,f.id))),await t.env.data.sessions.update(r.tenant.id,c,{revoked_at:new Date().toISOString()})}}}return ie(t,r.tenant.id,{type:te.SUCCESS_LOGOUT,description:"User successfully logged out"}),new Response("Redirecting",{status:302,headers:{"set-cookie":r_(r.tenant.id,t.req.header("host")),location:s}})}),Mg=o.z.object({sub:o.z.string(),email:o.z.string().optional(),family_name:o.z.string().optional(),given_name:o.z.string().optional(),email_verified:o.z.boolean()}),c5=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:Mg}},description:"Userinfo"}}}),async t=>{if(!t.var.user)throw new v(404,{message:"User not found"});const e=await t.env.data.users.get(t.var.user.tenant_id,t.var.user.sub);if(!e)throw new v(404,{message:"User not found"});return t.json(Mg.parse({...e,sub:e.user_id}))}),l5=new o.OpenAPIHono().openapi(o.createRoute({tags:["well known"],method:"get",path:"/jwks.json",request:{},responses:{200:{content:{"application/json":{schema:fm}},description:"List of tenants"}}}),async t=>{const e=await pu(t.env.data);return t.json({keys:e},{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${ms}, stale-while-revalidate=${ms*2}, stale-if-error=86400`}})}).openapi(o.createRoute({tags:["well known"],method:"get",path:"/openid-configuration",request:{},responses:{200:{content:{"application/json":{schema:Ll}},description:"List of tenants"}}}),async t=>{const e=Ll.parse({issuer:ic(t.env),authorization_endpoint:`${me(t.env)}authorize`,token_endpoint:`${me(t.env)}oauth/token`,device_authorization_endpoint:`${me(t.env)}oauth/device/code`,userinfo_endpoint:`${me(t.env)}userinfo`,mfa_challenge_endpoint:`${me(t.env)}mfa/challenge`,jwks_uri:`${me(t.env)}.well-known/jwks.json`,registration_endpoint:`${me(t.env)}oidc/register`,revocation_endpoint:`${me(t.env)}oauth/revoke`,scopes_supported:["openid","profile","offline_access","name","given_name","family_name","nickname","email","email_verified","picture","created_at","identities","phone","address"],response_types_supported:["code","token","id_token","code token","code id_token","token id_token","code token id_token"],code_challenge_methods_supported:["S256","plain"],response_modes_supported:["query","fragment","form_post"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256"],token_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post"],claims_supported:["aud","auth_time","created_at","email","email_verified","exp","family_name","given_name","iat","identities","iss","name","nickname","phone_number","picture","sub"],request_uri_parameter_supported:!1,request_parameter_supported:!1,token_endpoint_auth_signing_alg_values_supported:["RS256","RS384","PS256"]});return t.json(e,{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${ms}, stale-while-revalidate=${ms*2}, stale-if-error=86400`}})});function ho(t,e){if(!t||!e||t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}const E1=o.z.object({grant_type:o.z.literal("client_credentials"),scope:o.z.string().optional(),client_secret:o.z.string(),client_id:o.z.string(),audience:o.z.string().optional()});async function d5(t,e){const n=await t.env.data.legacyClients.get(e.client_id);if(!n)throw new B(403,{message:"Invalid client credentials"});if(n.client_secret&&!ho(n.client_secret,e.client_secret))throw new B(403,{message:"Invalid client credentials"});const r={client_id:n.client_id,scope:e.scope,audience:e.audience||n.tenant.default_audience};return{client:n,authParams:r}}const u5=o.z.object({grant_type:o.z.literal("authorization_code"),client_id:o.z.string(),code:o.z.string(),redirect_uri:o.z.string().optional(),client_secret:o.z.string().optional(),code_verifier:o.z.string().optional(),organization:o.z.string().optional()}).refine(t=>"client_secret"in t&&!("code_verifier"in t)||!("client_secret"in t)&&"code_verifier"in t,{message:"Must provide either client_secret (standard flow) or code_verifier/code_verifier_mode (PKCE flow), but not both"});async function p5(t,e){const n=await t.env.data.legacyClients.get(e.client_id);if(!n)throw new B(403,{message:"Client not found"});const r=await t.env.data.codes.get(n.tenant.id,e.code,"authorization_code");if(!r||!r.user_id)throw ie(t,n.tenant.id,{type:te.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid client credentials"}),new B(403,{message:"Invalid client credentials"});if(new Date(r.expires_at)<new Date)throw ie(t,n.tenant.id,{type:te.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Code expired",userId:r.user_id}),new B(403,{message:"Code expired"});if(r.used_at)throw ie(t,n.tenant.id,{type:te.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid authorization code",userId:r.user_id}),new B(403,{error:"invalid_grant",error_description:"Invalid authorization code"});const i=await t.env.data.loginSessions.get(n.tenant.id,r.login_id);if(!i)throw new B(403,{message:"Invalid login"});if(e.organization&&i.authParams.organization&&e.organization!==i.authParams.organization)throw new B(400,{error:"invalid_request",error_description:"Organization parameter does not match login session organization"});if("client_secret"in e){const l=await t.env.data.legacyClients.get("DEFAULT_CLIENT");if(!ho(n.client_secret,e.client_secret)&&!ho(l?.client_secret,e.client_secret))throw ie(t,n.tenant.id,{type:te.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid client credentials",userId:r.user_id}),new B(403,{message:"Invalid client credentials"})}else if(r.code_challenge&&r.code_challenge_method&&e.code_verifier){const l=await iv(e.code_verifier,r.code_challenge_method);if(!ho(l,r.code_challenge))throw ie(t,n.tenant.id,{type:te.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid client credentials",userId:r.user_id}),new B(403,{message:"Invalid client credentials"})}if(r.redirect_uri&&r.redirect_uri!==e.redirect_uri)throw ie(t,n.tenant.id,{type:te.FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN,description:"Invalid redirect uri",userId:r.user_id}),new B(403,{message:"Invalid redirect uri"});const s=await t.env.data.users.get(n.tenant.id,r.user_id);if(!s)throw new B(403,{message:"User not found"});await t.env.data.codes.used(n.tenant.id,e.code);let a;i.session_id&&i.authParams.scope?.split(" ").includes("offline_access")&&(a=await d_(t,{user:s,client:n,session_id:i.session_id,scope:i.authParams.scope,audience:i.authParams.audience}));let c;if(i.authParams.organization){const l=await t.env.data.organizations.get(n.tenant.id,i.authParams.organization);l?c={id:l.id,name:l.name}:c={id:i.authParams.organization,name:"Unknown"}}return{user:s,client:n,loginSession:i,session_id:i.session_id,refresh_token:a?.id,organization:c,authParams:{...i.authParams,state:r.state,nonce:r.nonce,response_mode:Ct.WEB_MESSAGE,client_id:n.client_id,scope:i.authParams.scope,audience:i.authParams.audience}}}function qg(t,e){const n=t.var.log;n?t.set("log",`${n}
82
+ ${e}`):t.set("log",e)}const f5=o.z.object({grant_type:o.z.literal("refresh_token"),client_id:o.z.string(),redirect_uri:o.z.string().optional(),refresh_token:o.z.string(),client_secret:o.z.string().optional()});async function h5(t,e){const n=await t.env.data.legacyClients.get(e.client_id);if(!n)throw new B(403,{message:"Client not found"});if(e.client_secret&&n.client_secret&&!ho(n.client_secret,e.client_secret))throw new B(403,{error:"invalid_client",error_description:"Client authentication failed"});const r=await t.env.data.refreshTokens.get(n.tenant.id,e.refresh_token);if(r){if(r.expires_at&&new Date(r.expires_at)<new Date||r.idle_expires_at&&new Date(r.idle_expires_at)<new Date)throw qg(t,`Refresh token has expired: ${e.refresh_token}`),new B(400,{error:"invalid_grant",error_description:"Refresh token has expired"})}else throw qg(t,`Invalid refresh token: ${e.refresh_token}`),new B(400,{error:"invalid_grant",error_description:"Invalid refresh token"});const i=await t.env.data.users.get(n.tenant.id,r.user_id);if(!i)throw new B(403,{message:"User not found"});t.set("user_id",i.user_id);const s=r.resource_servers[0];if(r.idle_expires_at){const a=new Date(Date.now()+2592e6);await t.env.data.refreshTokens.update(n.tenant.id,r.id,{idle_expires_at:a.toISOString(),last_exchanged_at:new Date().toISOString(),device:{...r.device,last_ip:t.req.header["x-real-ip"]||"",last_user_agent:t.req.header["user-agent"]||""}})}return{user:i,client:n,refresh_token:r.id,session_id:r.session_id,authParams:{client_id:n.client_id,audience:s?.audience,scope:s?.scopes,response_mode:Ct.WEB_MESSAGE}}}const g5={version:4,country_calling_codes:{1:["US","AG","AI","AS","BB","BM","BS","CA","DM","DO","GD","GU","JM","KN","KY","LC","MP","MS","PR","SX","TC","TT","VC","VG","VI"],7:["RU","KZ"],20:["EG"],27:["ZA"],30:["GR"],31:["NL"],32:["BE"],33:["FR"],34:["ES"],36:["HU"],39:["IT","VA"],40:["RO"],41:["CH"],43:["AT"],44:["GB","GG","IM","JE"],45:["DK"],46:["SE"],47:["NO","SJ"],48:["PL"],49:["DE"],51:["PE"],52:["MX"],53:["CU"],54:["AR"],55:["BR"],56:["CL"],57:["CO"],58:["VE"],60:["MY"],61:["AU","CC","CX"],62:["ID"],63:["PH"],64:["NZ"],65:["SG"],66:["TH"],81:["JP"],82:["KR"],84:["VN"],86:["CN"],90:["TR"],91:["IN"],92:["PK"],93:["AF"],94:["LK"],95:["MM"],98:["IR"],211:["SS"],212:["MA","EH"],213:["DZ"],216:["TN"],218:["LY"],220:["GM"],221:["SN"],222:["MR"],223:["ML"],224:["GN"],225:["CI"],226:["BF"],227:["NE"],228:["TG"],229:["BJ"],230:["MU"],231:["LR"],232:["SL"],233:["GH"],234:["NG"],235:["TD"],236:["CF"],237:["CM"],238:["CV"],239:["ST"],240:["GQ"],241:["GA"],242:["CG"],243:["CD"],244:["AO"],245:["GW"],246:["IO"],247:["AC"],248:["SC"],249:["SD"],250:["RW"],251:["ET"],252:["SO"],253:["DJ"],254:["KE"],255:["TZ"],256:["UG"],257:["BI"],258:["MZ"],260:["ZM"],261:["MG"],262:["RE","YT"],263:["ZW"],264:["NA"],265:["MW"],266:["LS"],267:["BW"],268:["SZ"],269:["KM"],290:["SH","TA"],291:["ER"],297:["AW"],298:["FO"],299:["GL"],350:["GI"],351:["PT"],352:["LU"],353:["IE"],354:["IS"],355:["AL"],356:["MT"],357:["CY"],358:["FI","AX"],359:["BG"],370:["LT"],371:["LV"],372:["EE"],373:["MD"],374:["AM"],375:["BY"],376:["AD"],377:["MC"],378:["SM"],380:["UA"],381:["RS"],382:["ME"],383:["XK"],385:["HR"],386:["SI"],387:["BA"],389:["MK"],420:["CZ"],421:["SK"],423:["LI"],500:["FK"],501:["BZ"],502:["GT"],503:["SV"],504:["HN"],505:["NI"],506:["CR"],507:["PA"],508:["PM"],509:["HT"],590:["GP","BL","MF"],591:["BO"],592:["GY"],593:["EC"],594:["GF"],595:["PY"],596:["MQ"],597:["SR"],598:["UY"],599:["CW","BQ"],670:["TL"],672:["NF"],673:["BN"],674:["NR"],675:["PG"],676:["TO"],677:["SB"],678:["VU"],679:["FJ"],680:["PW"],681:["WF"],682:["CK"],683:["NU"],685:["WS"],686:["KI"],687:["NC"],688:["TV"],689:["PF"],690:["TK"],691:["FM"],692:["MH"],850:["KP"],852:["HK"],853:["MO"],855:["KH"],856:["LA"],880:["BD"],886:["TW"],960:["MV"],961:["LB"],962:["JO"],963:["SY"],964:["IQ"],965:["KW"],966:["SA"],967:["YE"],968:["OM"],970:["PS"],971:["AE"],972:["IL"],973:["BH"],974:["QA"],975:["BT"],976:["MN"],977:["NP"],992:["TJ"],993:["TM"],994:["AZ"],995:["GE"],996:["KG"],998:["UZ"]},countries:{AC:["247","00","(?:[01589]\\d|[46])\\d{4}",[5,6]],AD:["376","00","(?:1|6\\d)\\d{7}|[135-9]\\d{5}",[6,8,9],[["(\\d{3})(\\d{3})","$1 $2",["[135-9]"]],["(\\d{4})(\\d{4})","$1 $2",["1"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["6"]]]],AE:["971","00","(?:[4-7]\\d|9[0-689])\\d{7}|800\\d{2,9}|[2-4679]\\d{7}",[5,6,7,8,9,10,11,12],[["(\\d{3})(\\d{2,9})","$1 $2",["60|8"]],["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["[236]|[479][2-8]"],"0$1"],["(\\d{3})(\\d)(\\d{5})","$1 $2 $3",["[479]"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["5"],"0$1"]],"0"],AF:["93","00","[2-7]\\d{8}",[9],[["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[2-7]"],"0$1"]],"0"],AG:["1","011","(?:268|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([457]\\d{6})$|1","268$1",0,"268"],AI:["1","011","(?:264|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2457]\\d{6})$|1","264$1",0,"264"],AL:["355","00","(?:700\\d\\d|900)\\d{3}|8\\d{5,7}|(?:[2-5]|6\\d)\\d{7}",[6,7,8,9],[["(\\d{3})(\\d{3,4})","$1 $2",["80|9"],"0$1"],["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["4[2-6]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[2358][2-5]|4"],"0$1"],["(\\d{3})(\\d{5})","$1 $2",["[23578]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["6"],"0$1"]],"0"],AM:["374","00","(?:[1-489]\\d|55|60|77)\\d{6}",[8],[["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["[89]0"],"0 $1"],["(\\d{3})(\\d{5})","$1 $2",["2|3[12]"],"(0$1)"],["(\\d{2})(\\d{6})","$1 $2",["1|47"],"(0$1)"],["(\\d{2})(\\d{6})","$1 $2",["[3-9]"],"0$1"]],"0"],AO:["244","00","[29]\\d{8}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[29]"]]]],AR:["54","00","(?:11|[89]\\d\\d)\\d{8}|[2368]\\d{9}",[10,11],[["(\\d{4})(\\d{2})(\\d{4})","$1 $2-$3",["2(?:2[024-9]|3[0-59]|47|6[245]|9[02-8])|3(?:3[28]|4[03-9]|5[2-46-8]|7[1-578]|8[2-9])","2(?:[23]02|6(?:[25]|4[6-8])|9(?:[02356]|4[02568]|72|8[23]))|3(?:3[28]|4(?:[04679]|3[5-8]|5[4-68]|8[2379])|5(?:[2467]|3[237]|8[2-5])|7[1-578]|8(?:[2469]|3[2578]|5[4-8]|7[36-8]|8[5-8]))|2(?:2[24-9]|3[1-59]|47)","2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3[78]|5(?:4[46]|8)|8[2379])|5(?:[2467]|3[237]|8[23])|7[1-578]|8(?:[2469]|3[278]|5[56][46]|86[3-6]))|2(?:2[24-9]|3[1-59]|47)|38(?:[58][78]|7[378])|3(?:4[35][56]|58[45]|8(?:[38]5|54|76))[4-6]","2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3(?:5(?:4[0-25689]|[56])|[78])|58|8[2379])|5(?:[2467]|3[237]|8(?:[23]|4(?:[45]|60)|5(?:4[0-39]|5|64)))|7[1-578]|8(?:[2469]|3[278]|54(?:4|5[13-7]|6[89])|86[3-6]))|2(?:2[24-9]|3[1-59]|47)|38(?:[58][78]|7[378])|3(?:454|85[56])[46]|3(?:4(?:36|5[56])|8(?:[38]5|76))[4-6]"],"0$1",1],["(\\d{2})(\\d{4})(\\d{4})","$1 $2-$3",["1"],"0$1",1],["(\\d{3})(\\d{3})(\\d{4})","$1-$2-$3",["[68]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2-$3",["[23]"],"0$1",1],["(\\d)(\\d{4})(\\d{2})(\\d{4})","$2 15-$3-$4",["9(?:2[2-469]|3[3-578])","9(?:2(?:2[024-9]|3[0-59]|47|6[245]|9[02-8])|3(?:3[28]|4[03-9]|5[2-46-8]|7[1-578]|8[2-9]))","9(?:2(?:[23]02|6(?:[25]|4[6-8])|9(?:[02356]|4[02568]|72|8[23]))|3(?:3[28]|4(?:[04679]|3[5-8]|5[4-68]|8[2379])|5(?:[2467]|3[237]|8[2-5])|7[1-578]|8(?:[2469]|3[2578]|5[4-8]|7[36-8]|8[5-8])))|92(?:2[24-9]|3[1-59]|47)","9(?:2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3[78]|5(?:4[46]|8)|8[2379])|5(?:[2467]|3[237]|8[23])|7[1-578]|8(?:[2469]|3[278]|5(?:[56][46]|[78])|7[378]|8(?:6[3-6]|[78]))))|92(?:2[24-9]|3[1-59]|47)|93(?:4[35][56]|58[45]|8(?:[38]5|54|76))[4-6]","9(?:2(?:[23]02|6(?:[25]|4(?:64|[78]))|9(?:[02356]|4(?:[0268]|5[2-6])|72|8[23]))|3(?:3[28]|4(?:[04679]|3(?:5(?:4[0-25689]|[56])|[78])|5(?:4[46]|8)|8[2379])|5(?:[2467]|3[237]|8(?:[23]|4(?:[45]|60)|5(?:4[0-39]|5|64)))|7[1-578]|8(?:[2469]|3[278]|5(?:4(?:4|5[13-7]|6[89])|[56][46]|[78])|7[378]|8(?:6[3-6]|[78]))))|92(?:2[24-9]|3[1-59]|47)|93(?:4(?:36|5[56])|8(?:[38]5|76))[4-6]"],"0$1",0,"$1 $2 $3-$4"],["(\\d)(\\d{2})(\\d{4})(\\d{4})","$2 15-$3-$4",["91"],"0$1",0,"$1 $2 $3-$4"],["(\\d{3})(\\d{3})(\\d{5})","$1-$2-$3",["8"],"0$1"],["(\\d)(\\d{3})(\\d{3})(\\d{4})","$2 15-$3-$4",["9"],"0$1",0,"$1 $2 $3-$4"]],"0",0,"0?(?:(11|2(?:2(?:02?|[13]|2[13-79]|4[1-6]|5[2457]|6[124-8]|7[1-4]|8[13-6]|9[1267])|3(?:02?|1[467]|2[03-6]|3[13-8]|[49][2-6]|5[2-8]|[67])|4(?:7[3-578]|9)|6(?:[0136]|2[24-6]|4[6-8]?|5[15-8])|80|9(?:0[1-3]|[19]|2\\d|3[1-6]|4[02568]?|5[2-4]|6[2-46]|72?|8[23]?))|3(?:3(?:2[79]|6|8[2578])|4(?:0[0-24-9]|[12]|3[5-8]?|4[24-7]|5[4-68]?|6[02-9]|7[126]|8[2379]?|9[1-36-8])|5(?:1|2[1245]|3[237]?|4[1-46-9]|6[2-4]|7[1-6]|8[2-5]?)|6[24]|7(?:[069]|1[1568]|2[15]|3[145]|4[13]|5[14-8]|7[2-57]|8[126])|8(?:[01]|2[15-7]|3[2578]?|4[13-6]|5[4-8]?|6[1-357-9]|7[36-8]?|8[5-8]?|9[124])))15)?","9$1"],AS:["1","011","(?:[58]\\d\\d|684|900)\\d{7}",[10],0,"1",0,"([267]\\d{6})$|1","684$1",0,"684"],AT:["43","00","1\\d{3,12}|2\\d{6,12}|43(?:(?:0\\d|5[02-9])\\d{3,9}|2\\d{4,5}|[3467]\\d{4}|8\\d{4,6}|9\\d{4,7})|5\\d{4,12}|8\\d{7,12}|9\\d{8,12}|(?:[367]\\d|4[0-24-9])\\d{4,11}",[4,5,6,7,8,9,10,11,12,13],[["(\\d)(\\d{3,12})","$1 $2",["1(?:11|[2-9])"],"0$1"],["(\\d{3})(\\d{2})","$1 $2",["517"],"0$1"],["(\\d{2})(\\d{3,5})","$1 $2",["5[079]"],"0$1"],["(\\d{3})(\\d{3,10})","$1 $2",["(?:31|4)6|51|6(?:48|5[0-3579]|[6-9])|7(?:20|32|8)|[89]","(?:31|4)6|51|6(?:485|5[0-3579]|[6-9])|7(?:20|32|8)|[89]"],"0$1"],["(\\d{4})(\\d{3,9})","$1 $2",["[2-467]|5[2-6]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["5"],"0$1"],["(\\d{2})(\\d{4})(\\d{4,7})","$1 $2 $3",["5"],"0$1"]],"0"],AU:["61","001[14-689]|14(?:1[14]|34|4[17]|[56]6|7[47]|88)0011","1(?:[0-79]\\d{7}(?:\\d(?:\\d{2})?)?|8[0-24-9]\\d{7})|[2-478]\\d{8}|1\\d{4,7}",[5,6,7,8,9,10,12],[["(\\d{2})(\\d{3,4})","$1 $2",["16"],"0$1"],["(\\d{2})(\\d{3})(\\d{2,4})","$1 $2 $3",["16"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["14|4"],"0$1"],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["[2378]"],"(0$1)"],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1(?:30|[89])"]]],"0",0,"(183[12])|0",0,0,0,[["(?:(?:241|349)0\\d\\d|8(?:51(?:0(?:0[03-9]|[12479]\\d|3[2-9]|5[0-8]|6[1-9]|8[0-7])|1(?:[0235689]\\d|1[0-69]|4[0-589]|7[0-47-9])|2(?:0[0-79]|[18][13579]|2[14-9]|3[0-46-9]|[4-6]\\d|7[89]|9[0-4])|[34]\\d\\d)|91(?:(?:[0-58]\\d|6[0135-9])\\d|7(?:0[0-24-9]|[1-9]\\d)|9(?:[0-46-9]\\d|5[0-79]))))\\d{3}|(?:2(?:[0-26-9]\\d|3[0-8]|4[02-9]|5[0135-9])|3(?:[0-3589]\\d|4[0-578]|6[1-9]|7[0-35-9])|7(?:[013-57-9]\\d|2[0-8])|8(?:55|6[0-8]|[78]\\d|9[02-9]))\\d{6}",[9]],["4(?:79[01]|83[0-36-9]|95[0-3])\\d{5}|4(?:[0-36]\\d|4[047-9]|[58][0-24-9]|7[02-8]|9[0-47-9])\\d{6}",[9]],["180(?:0\\d{3}|2)\\d{3}",[7,10]],["190[0-26]\\d{6}",[10]],0,0,0,["163\\d{2,6}",[5,6,7,8,9]],["14(?:5(?:1[0458]|[23][458])|71\\d)\\d{4}",[9]],["13(?:00\\d{6}(?:\\d{2})?|45[0-4]\\d{3})|13\\d{4}",[6,8,10,12]]],"0011"],AW:["297","00","(?:[25-79]\\d\\d|800)\\d{4}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[25-9]"]]]],AX:["358","00|99(?:[01469]|5(?:[14]1|3[23]|5[59]|77|88|9[09]))","2\\d{4,9}|35\\d{4,5}|(?:60\\d\\d|800)\\d{4,6}|7\\d{5,11}|(?:[14]\\d|3[0-46-9]|50)\\d{4,8}",[5,6,7,8,9,10,11,12],0,"0",0,0,0,0,"18",0,"00"],AZ:["994","00","365\\d{6}|(?:[124579]\\d|60|88)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["90"],"0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["1[28]|2|365|46","1[28]|2|365[45]|46","1[28]|2|365(?:4|5[02])|46"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[13-9]"],"0$1"]],"0"],BA:["387","00","6\\d{8}|(?:[35689]\\d|49|70)\\d{6}",[8,9],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["6[1-3]|[7-9]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2-$3",["[3-5]|6[56]"],"0$1"],["(\\d{2})(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3 $4",["6"],"0$1"]],"0"],BB:["1","011","(?:246|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","246$1",0,"246"],BD:["880","00","[1-469]\\d{9}|8[0-79]\\d{7,8}|[2-79]\\d{8}|[2-9]\\d{7}|[3-9]\\d{6}|[57-9]\\d{5}",[6,7,8,9,10],[["(\\d{2})(\\d{4,6})","$1-$2",["31[5-8]|[459]1"],"0$1"],["(\\d{3})(\\d{3,7})","$1-$2",["3(?:[67]|8[013-9])|4(?:6[168]|7|[89][18])|5(?:6[128]|9)|6(?:[15]|28|4[14])|7[2-589]|8(?:0[014-9]|[12])|9[358]|(?:3[2-5]|4[235]|5[2-578]|6[0389]|76|8[3-7]|9[24])1|(?:44|66)[01346-9]"],"0$1"],["(\\d{4})(\\d{3,6})","$1-$2",["[13-9]|2[23]"],"0$1"],["(\\d)(\\d{7,8})","$1-$2",["2"],"0$1"]],"0"],BE:["32","00","4\\d{8}|[1-9]\\d{7}",[8,9],[["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["(?:80|9)0"],"0$1"],["(\\d)(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[239]|4[23]"],"0$1"],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[15-8]"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["4"],"0$1"]],"0"],BF:["226","00","(?:[025-7]\\d|44)\\d{6}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[024-7]"]]]],BG:["359","00","00800\\d{7}|[2-7]\\d{6,7}|[89]\\d{6,8}|2\\d{5}",[6,7,8,9,12],[["(\\d)(\\d)(\\d{2})(\\d{2})","$1 $2 $3 $4",["2"],"0$1"],["(\\d{3})(\\d{4})","$1 $2",["43[1-6]|70[1-9]"],"0$1"],["(\\d)(\\d{3})(\\d{3,4})","$1 $2 $3",["2"],"0$1"],["(\\d{2})(\\d{3})(\\d{2,3})","$1 $2 $3",["[356]|4[124-7]|7[1-9]|8[1-6]|9[1-7]"],"0$1"],["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["(?:70|8)0"],"0$1"],["(\\d{3})(\\d{3})(\\d{2})","$1 $2 $3",["43[1-7]|7"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[48]|9[08]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["9"],"0$1"]],"0"],BH:["973","00","[136-9]\\d{7}",[8],[["(\\d{4})(\\d{4})","$1 $2",["[13679]|8[02-4679]"]]]],BI:["257","00","(?:[267]\\d|31)\\d{6}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2367]"]]]],BJ:["229","00","(?:01\\d|8)\\d{7}",[8,10],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4 $5",["0"]]]],BL:["590","00","(?:590\\d|7090)\\d{5}|(?:69|80|9\\d)\\d{7}",[9],0,"0",0,0,0,0,0,[["590(?:2[7-9]|3[3-7]|5[12]|87)\\d{4}"],["(?:69(?:0\\d\\d|1(?:2[2-9]|3[0-5])|4(?:0[89]|1[2-6]|9\\d)|6(?:1[016-9]|5[0-4]|[67]\\d))|7090[0-4])\\d{4}"],["80[0-5]\\d{6}"],0,0,0,0,0,["9(?:(?:39[5-7]|76[018])\\d|475[0-6])\\d{4}"]]],BM:["1","011","(?:441|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","441$1",0,"441"],BN:["673","00","[2-578]\\d{6}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[2-578]"]]]],BO:["591","00(?:1\\d)?","8001\\d{5}|(?:[2-467]\\d|50)\\d{6}",[8,9],[["(\\d)(\\d{7})","$1 $2",["[235]|4[46]"]],["(\\d{8})","$1",["[67]"]],["(\\d{3})(\\d{2})(\\d{4})","$1 $2 $3",["8"]]],"0",0,"0(1\\d)?"],BQ:["599","00","(?:[34]1|7\\d)\\d{5}",[7],0,0,0,0,0,0,"[347]"],BR:["55","00(?:1[245]|2[1-35]|31|4[13]|[56]5|99)","[1-467]\\d{9,10}|55[0-46-9]\\d{8}|[34]\\d{7}|55\\d{7,8}|(?:5[0-46-9]|[89]\\d)\\d{7,9}",[8,9,10,11],[["(\\d{4})(\\d{4})","$1-$2",["300|4(?:0[02]|37|86)","300|4(?:0(?:0|20)|370|864)"]],["(\\d{3})(\\d{2,3})(\\d{4})","$1 $2 $3",["(?:[358]|90)0"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1 $2-$3",["(?:[14689][1-9]|2[12478]|3[1-578]|5[13-5]|7[13-579])[2-57]"],"($1)"],["(\\d{2})(\\d{5})(\\d{4})","$1 $2-$3",["[16][1-9]|[2-57-9]"],"($1)"]],"0",0,"(?:0|90)(?:(1[245]|2[1-35]|31|4[13]|[56]5|99)(\\d{10,11}))?","$2"],BS:["1","011","(?:242|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([3-8]\\d{6})$|1","242$1",0,"242"],BT:["975","00","[178]\\d{7}|[2-8]\\d{6}",[7,8],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["[2-6]|7[246]|8[2-4]"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["1[67]|[78]"]]]],BW:["267","00","(?:0800|(?:[37]|800)\\d)\\d{6}|(?:[2-6]\\d|90)\\d{5}",[7,8,10],[["(\\d{2})(\\d{5})","$1 $2",["90"]],["(\\d{3})(\\d{4})","$1 $2",["[24-6]|3[15-9]"]],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[37]"]],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["0"]],["(\\d{3})(\\d{4})(\\d{3})","$1 $2 $3",["8"]]]],BY:["375","810","(?:[12]\\d|33|44|902)\\d{7}|8(?:0[0-79]\\d{5,7}|[1-7]\\d{9})|8(?:1[0-489]|[5-79]\\d)\\d{7}|8[1-79]\\d{6,7}|8[0-79]\\d{5}|8\\d{5}",[6,7,8,9,10,11],[["(\\d{3})(\\d{3})","$1 $2",["800"],"8 $1"],["(\\d{3})(\\d{2})(\\d{2,4})","$1 $2 $3",["800"],"8 $1"],["(\\d{4})(\\d{2})(\\d{3})","$1 $2-$3",["1(?:5[169]|6[3-5]|7[179])|2(?:1[35]|2[34]|3[3-5])","1(?:5[169]|6(?:3[1-3]|4|5[125])|7(?:1[3-9]|7[0-24-6]|9[2-7]))|2(?:1[35]|2[34]|3[3-5])"],"8 0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2-$3-$4",["1(?:[56]|7[467])|2[1-3]"],"8 0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2-$3-$4",["[1-4]"],"8 0$1"],["(\\d{3})(\\d{3,4})(\\d{4})","$1 $2 $3",["[89]"],"8 $1"]],"8",0,"0|80?",0,0,0,0,"8~10"],BZ:["501","00","(?:0800\\d|[2-8])\\d{6}",[7,11],[["(\\d{3})(\\d{4})","$1-$2",["[2-8]"]],["(\\d)(\\d{3})(\\d{4})(\\d{3})","$1-$2-$3-$4",["0"]]]],CA:["1","011","[2-9]\\d{9}|3\\d{6}",[7,10],0,"1",0,0,0,0,0,[["(?:2(?:04|[23]6|[48]9|5[07]|63)|3(?:06|43|54|6[578]|82)|4(?:03|1[68]|[26]8|3[178]|50|74)|5(?:06|1[49]|48|79|8[147])|6(?:04|[18]3|39|47|72)|7(?:0[59]|42|53|78|8[02])|8(?:[06]7|19|25|7[39])|9(?:0[25]|42))[2-9]\\d{6}",[10]],["",[10]],["8(?:00|33|44|55|66|77|88)[2-9]\\d{6}",[10]],["900[2-9]\\d{6}",[10]],["52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|(?:5(?:2[125-9]|33|44|66|77|88)|6(?:22|33))[2-9]\\d{6}",[10]],0,["310\\d{4}",[7]],0,["600[2-9]\\d{6}",[10]]]],CC:["61","001[14-689]|14(?:1[14]|34|4[17]|[56]6|7[47]|88)0011","1(?:[0-79]\\d{8}(?:\\d{2})?|8[0-24-9]\\d{7})|[148]\\d{8}|1\\d{5,7}",[6,7,8,9,10,12],0,"0",0,"([59]\\d{7})$|0","8$1",0,0,[["8(?:51(?:0(?:02|31|60|89)|1(?:18|76)|223)|91(?:0(?:1[0-2]|29)|1(?:[28]2|50|79)|2(?:10|64)|3(?:[06]8|22)|4[29]8|62\\d|70[23]|959))\\d{3}",[9]],["4(?:79[01]|83[0-36-9]|95[0-3])\\d{5}|4(?:[0-36]\\d|4[047-9]|[58][0-24-9]|7[02-8]|9[0-47-9])\\d{6}",[9]],["180(?:0\\d{3}|2)\\d{3}",[7,10]],["190[0-26]\\d{6}",[10]],0,0,0,0,["14(?:5(?:1[0458]|[23][458])|71\\d)\\d{4}",[9]],["13(?:00\\d{6}(?:\\d{2})?|45[0-4]\\d{3})|13\\d{4}",[6,8,10,12]]],"0011"],CD:["243","00","(?:(?:[189]|5\\d)\\d|2)\\d{7}|[1-68]\\d{6}",[7,8,9,10],[["(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3",["88"],"0$1"],["(\\d{2})(\\d{5})","$1 $2",["[1-6]"],"0$1"],["(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3",["2"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["1"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[89]"],"0$1"],["(\\d{2})(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3 $4",["5"],"0$1"]],"0"],CF:["236","00","(?:[27]\\d{3}|8776)\\d{4}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[278]"]]]],CG:["242","00","222\\d{6}|(?:0\\d|80)\\d{7}",[9],[["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["8"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[02]"]]]],CH:["41","00","8\\d{11}|[2-9]\\d{8}",[9,12],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["8[047]|90"],"0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2-79]|81"],"0$1"],["(\\d{3})(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4 $5",["8"],"0$1"]],"0"],CI:["225","00","[02]\\d{9}",[10],[["(\\d{2})(\\d{2})(\\d)(\\d{5})","$1 $2 $3 $4",["2"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3 $4",["0"]]]],CK:["682","00","[2-578]\\d{4}",[5],[["(\\d{2})(\\d{3})","$1 $2",["[2-578]"]]]],CL:["56","(?:0|1(?:1[0-69]|2[02-5]|5[13-58]|69|7[0167]|8[018]))0","12300\\d{6}|6\\d{9,10}|[2-9]\\d{8}",[9,10,11],[["(\\d{5})(\\d{4})","$1 $2",["219","2196"],"($1)"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["60|809"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["44"]],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["2[1-36]"],"($1)"],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["9(?:10|[2-9])"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["3[2-5]|[47]|5[1-3578]|6[13-57]|8(?:0[1-8]|[1-9])"],"($1)"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["60|8"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["1"]],["(\\d{3})(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3 $4",["60"]]]],CM:["237","00","[26]\\d{8}|88\\d{6,7}",[8,9],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["88"]],["(\\d)(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4 $5",["[26]|88"]]]],CN:["86","00|1(?:[12]\\d|79)\\d\\d00","(?:(?:1[03-689]|2\\d)\\d\\d|6)\\d{8}|1\\d{10}|[126]\\d{6}(?:\\d(?:\\d{2})?)?|86\\d{5,6}|(?:[3-579]\\d|8[0-57-9])\\d{5,9}",[7,8,9,10,11,12],[["(\\d{2})(\\d{5,6})","$1 $2",["(?:10|2[0-57-9])[19]|3(?:[157]|35|49|9[1-68])|4(?:1[124-9]|2[179]|6[47-9]|7|8[23])|5(?:[1357]|2[37]|4[36]|6[1-46]|80)|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:07|1[236-8]|2[5-7]|[37]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3|4[13]|5[1-5]|7[0-79]|9[0-35-9])|(?:4[35]|59|85)[1-9]","(?:10|2[0-57-9])(?:1[02]|9[56])|8078|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))1","10(?:1(?:0|23)|9[56])|2[0-57-9](?:1(?:00|23)|9[56])|80781|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))12","10(?:1(?:0|23)|9[56])|2[0-57-9](?:1(?:00|23)|9[56])|807812|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))123","10(?:1(?:0|23)|9[56])|2[0-57-9](?:1(?:00|23)|9[56])|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:1[124-9]|2[179]|[35][1-9]|6[47-9]|7\\d|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:078|1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|3\\d|4[13]|5[1-5]|7[0-79]|9[0-35-9]))123"],"0$1"],["(\\d{3})(\\d{5,6})","$1 $2",["3(?:[157]|35|49|9[1-68])|4(?:[17]|2[179]|6[47-9]|8[23])|5(?:[1357]|2[37]|4[36]|6[1-46]|80)|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]|4[13]|5[1-5])|(?:4[35]|59|85)[1-9]","(?:3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[1-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))[19]","85[23](?:10|95)|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[14-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))(?:10|9[56])","85[23](?:100|95)|(?:3(?:[157]\\d|35|49|9[1-68])|4(?:[17]\\d|2[179]|[35][1-9]|6[47-9]|8[23])|5(?:[1357]\\d|2[37]|4[36]|6[1-46]|80|9[1-9])|6(?:3[1-5]|6[0238]|9[12])|7(?:01|[1579]\\d|2[248]|3[014-9]|4[3-6]|6[023689])|8(?:1[236-8]|2[5-7]|[37]\\d|5[14-9]|8[36-8]|9[1-8])|9(?:0[1-3689]|1[1-79]|[379]\\d|4[13]|5[1-5]))(?:100|9[56])"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["(?:4|80)0"]],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["10|2(?:[02-57-9]|1[1-9])","10|2(?:[02-57-9]|1[1-9])","10[0-79]|2(?:[02-57-9]|1[1-79])|(?:10|21)8(?:0[1-9]|[1-9])"],"0$1",1],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["3(?:[3-59]|7[02-68])|4(?:[26-8]|3[3-9]|5[2-9])|5(?:3[03-9]|[468]|7[028]|9[2-46-9])|6|7(?:[0-247]|3[04-9]|5[0-4689]|6[2368])|8(?:[1-358]|9[1-7])|9(?:[013479]|5[1-5])|(?:[34]1|55|79|87)[02-9]"],"0$1",1],["(\\d{3})(\\d{7,8})","$1 $2",["9"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["80"],"0$1",1],["(\\d{3})(\\d{4})(\\d{4})","$1 $2 $3",["[3-578]"],"0$1",1],["(\\d{3})(\\d{4})(\\d{4})","$1 $2 $3",["1[3-9]"]],["(\\d{2})(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3 $4",["[12]"],"0$1",1]],"0",0,"(1(?:[12]\\d|79)\\d\\d)|0",0,0,0,0,"00"],CO:["57","00(?:4(?:[14]4|56)|[579])","(?:46|60\\d\\d)\\d{6}|(?:1\\d|[39])\\d{9}",[8,10,11],[["(\\d{4})(\\d{4})","$1 $2",["46"]],["(\\d{3})(\\d{7})","$1 $2",["6|90"],"($1)"],["(\\d{3})(\\d{7})","$1 $2",["3[0-357]|9[14]"]],["(\\d)(\\d{3})(\\d{7})","$1-$2-$3",["1"],"0$1",0,"$1 $2 $3"]],"0",0,"0([3579]|4(?:[14]4|56))?"],CR:["506","00","(?:8\\d|90)\\d{8}|(?:[24-8]\\d{3}|3005)\\d{4}",[8,10],[["(\\d{4})(\\d{4})","$1 $2",["[2-7]|8[3-9]"]],["(\\d{3})(\\d{3})(\\d{4})","$1-$2-$3",["[89]"]]],0,0,"(19(?:0[0-2468]|1[09]|20|66|77|99))"],CU:["53","119","(?:[2-7]|8\\d\\d)\\d{7}|[2-47]\\d{6}|[34]\\d{5}",[6,7,8,10],[["(\\d{2})(\\d{4,6})","$1 $2",["2[1-4]|[34]"],"(0$1)"],["(\\d)(\\d{6,7})","$1 $2",["7"],"(0$1)"],["(\\d)(\\d{7})","$1 $2",["[56]"],"0$1"],["(\\d{3})(\\d{7})","$1 $2",["8"],"0$1"]],"0"],CV:["238","0","(?:[2-59]\\d\\d|800)\\d{4}",[7],[["(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3",["[2-589]"]]]],CW:["599","00","(?:[34]1|60|(?:7|9\\d)\\d)\\d{5}",[7,8],[["(\\d{3})(\\d{4})","$1 $2",["[3467]"]],["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["9[4-8]"]]],0,0,0,0,0,"[69]"],CX:["61","001[14-689]|14(?:1[14]|34|4[17]|[56]6|7[47]|88)0011","1(?:[0-79]\\d{8}(?:\\d{2})?|8[0-24-9]\\d{7})|[148]\\d{8}|1\\d{5,7}",[6,7,8,9,10,12],0,"0",0,"([59]\\d{7})$|0","8$1",0,0,[["8(?:51(?:0(?:01|30|59|88)|1(?:17|46|75)|2(?:22|35))|91(?:00[6-9]|1(?:[28]1|49|78)|2(?:09|63)|3(?:12|26|75)|4(?:56|97)|64\\d|7(?:0[01]|1[0-2])|958))\\d{3}",[9]],["4(?:79[01]|83[0-36-9]|95[0-3])\\d{5}|4(?:[0-36]\\d|4[047-9]|[58][0-24-9]|7[02-8]|9[0-47-9])\\d{6}",[9]],["180(?:0\\d{3}|2)\\d{3}",[7,10]],["190[0-26]\\d{6}",[10]],0,0,0,0,["14(?:5(?:1[0458]|[23][458])|71\\d)\\d{4}",[9]],["13(?:00\\d{6}(?:\\d{2})?|45[0-4]\\d{3})|13\\d{4}",[6,8,10,12]]],"0011"],CY:["357","00","(?:[279]\\d|[58]0)\\d{6}",[8],[["(\\d{2})(\\d{6})","$1 $2",["[257-9]"]]]],CZ:["420","00","(?:[2-578]\\d|60)\\d{7}|9\\d{8,11}",[9,10,11,12],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[2-8]|9[015-7]"]],["(\\d{2})(\\d{3})(\\d{3})(\\d{2})","$1 $2 $3 $4",["96"]],["(\\d{2})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["9"]],["(\\d{3})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["9"]]]],DE:["49","00","[2579]\\d{5,14}|49(?:[34]0|69|8\\d)\\d\\d?|49(?:37|49|60|7[089]|9\\d)\\d{1,3}|49(?:2[024-9]|3[2-689]|7[1-7])\\d{1,8}|(?:1|[368]\\d|4[0-8])\\d{3,13}|49(?:[015]\\d|2[13]|31|[46][1-8])\\d{1,9}",[4,5,6,7,8,9,10,11,12,13,14,15],[["(\\d{2})(\\d{3,13})","$1 $2",["3[02]|40|[68]9"],"0$1"],["(\\d{3})(\\d{3,12})","$1 $2",["2(?:0[1-389]|1[124]|2[18]|3[14])|3(?:[35-9][15]|4[015])|906|(?:2[4-9]|4[2-9]|[579][1-9]|[68][1-8])1","2(?:0[1-389]|12[0-8])|3(?:[35-9][15]|4[015])|906|2(?:[13][14]|2[18])|(?:2[4-9]|4[2-9]|[579][1-9]|[68][1-8])1"],"0$1"],["(\\d{4})(\\d{2,11})","$1 $2",["[24-6]|3(?:[3569][02-46-9]|4[2-4679]|7[2-467]|8[2-46-8])|70[2-8]|8(?:0[2-9]|[1-8])|90[7-9]|[79][1-9]","[24-6]|3(?:3(?:0[1-467]|2[127-9]|3[124578]|7[1257-9]|8[1256]|9[145])|4(?:2[135]|4[13578]|9[1346])|5(?:0[14]|2[1-3589]|6[1-4]|7[13468]|8[13568])|6(?:2[1-489]|3[124-6]|6[13]|7[12579]|8[1-356]|9[135])|7(?:2[1-7]|4[145]|6[1-5]|7[1-4])|8(?:21|3[1468]|6|7[1467]|8[136])|9(?:0[12479]|2[1358]|4[134679]|6[1-9]|7[136]|8[147]|9[1468]))|70[2-8]|8(?:0[2-9]|[1-8])|90[7-9]|[79][1-9]|3[68]4[1347]|3(?:47|60)[1356]|3(?:3[46]|46|5[49])[1246]|3[4579]3[1357]"],"0$1"],["(\\d{3})(\\d{4})","$1 $2",["138"],"0$1"],["(\\d{5})(\\d{2,10})","$1 $2",["3"],"0$1"],["(\\d{3})(\\d{5,11})","$1 $2",["181"],"0$1"],["(\\d{3})(\\d)(\\d{4,10})","$1 $2 $3",["1(?:3|80)|9"],"0$1"],["(\\d{3})(\\d{7,8})","$1 $2",["1[67]"],"0$1"],["(\\d{3})(\\d{7,12})","$1 $2",["8"],"0$1"],["(\\d{5})(\\d{6})","$1 $2",["185","1850","18500"],"0$1"],["(\\d{3})(\\d{4})(\\d{4})","$1 $2 $3",["7"],"0$1"],["(\\d{4})(\\d{7})","$1 $2",["18[68]"],"0$1"],["(\\d{4})(\\d{7})","$1 $2",["15[1279]"],"0$1"],["(\\d{5})(\\d{6})","$1 $2",["15[03568]","15(?:[0568]|3[13])"],"0$1"],["(\\d{3})(\\d{8})","$1 $2",["18"],"0$1"],["(\\d{3})(\\d{2})(\\d{7,8})","$1 $2 $3",["1(?:6[023]|7)"],"0$1"],["(\\d{4})(\\d{2})(\\d{7})","$1 $2 $3",["15[279]"],"0$1"],["(\\d{3})(\\d{2})(\\d{8})","$1 $2 $3",["15"],"0$1"]],"0"],DJ:["253","00","(?:2\\d|77)\\d{6}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[27]"]]]],DK:["45","00","[2-9]\\d{7}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2-9]"]]]],DM:["1","011","(?:[58]\\d\\d|767|900)\\d{7}",[10],0,"1",0,"([2-7]\\d{6})$|1","767$1",0,"767"],DO:["1","011","(?:[58]\\d\\d|900)\\d{7}",[10],0,"1",0,0,0,0,"8001|8[024]9"],DZ:["213","00","(?:[1-4]|[5-79]\\d|80)\\d{7}",[8,9],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[1-4]"],"0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["9"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-8]"],"0$1"]],"0"],EC:["593","00","1\\d{9,10}|(?:[2-7]|9\\d)\\d{7}",[8,9,10,11],[["(\\d)(\\d{3})(\\d{4})","$1 $2-$3",["[2-7]"],"(0$1)",0,"$1-$2-$3"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["9"],"0$1"],["(\\d{4})(\\d{3})(\\d{3,4})","$1 $2 $3",["1"]]],"0"],EE:["372","00","8\\d{9}|[4578]\\d{7}|(?:[3-8]\\d|90)\\d{5}",[7,8,10],[["(\\d{3})(\\d{4})","$1 $2",["[369]|4[3-8]|5(?:[0-2]|5[0-478]|6[45])|7[1-9]|88","[369]|4[3-8]|5(?:[02]|1(?:[0-8]|95)|5[0-478]|6(?:4[0-4]|5[1-589]))|7[1-9]|88"]],["(\\d{4})(\\d{3,4})","$1 $2",["[45]|8(?:00|[1-49])","[45]|8(?:00[1-9]|[1-49])"]],["(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3",["7"]],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["8"]]]],EG:["20","00","[189]\\d{8,9}|[24-6]\\d{8}|[135]\\d{7}",[8,9,10],[["(\\d)(\\d{7,8})","$1 $2",["[23]"],"0$1"],["(\\d{2})(\\d{6,7})","$1 $2",["1[35]|[4-6]|8[2468]|9[235-7]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[89]"],"0$1"],["(\\d{2})(\\d{8})","$1 $2",["1"],"0$1"]],"0"],EH:["212","00","[5-8]\\d{8}",[9],0,"0",0,0,0,0,"528[89]"],ER:["291","00","[178]\\d{6}",[7],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["[178]"],"0$1"]],"0"],ES:["34","00","[5-9]\\d{8}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[89]00"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-9]"]]]],ET:["251","00","(?:11|[2-579]\\d)\\d{7}",[9],[["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[1-579]"],"0$1"]],"0"],FI:["358","00|99(?:[01469]|5(?:[14]1|3[23]|5[59]|77|88|9[09]))","[1-35689]\\d{4}|7\\d{10,11}|(?:[124-7]\\d|3[0-46-9])\\d{8}|[1-9]\\d{5,8}",[5,6,7,8,9,10,11,12],[["(\\d{5})","$1",["20[2-59]"],"0$1"],["(\\d{3})(\\d{3,7})","$1 $2",["(?:[1-3]0|[68])0|70[07-9]"],"0$1"],["(\\d{2})(\\d{4,8})","$1 $2",["[14]|2[09]|50|7[135]"],"0$1"],["(\\d{2})(\\d{6,10})","$1 $2",["7"],"0$1"],["(\\d)(\\d{4,9})","$1 $2",["(?:19|[2568])[1-8]|3(?:0[1-9]|[1-9])|9"],"0$1"]],"0",0,0,0,0,"1[03-79]|[2-9]",0,"00"],FJ:["679","0(?:0|52)","45\\d{5}|(?:0800\\d|[235-9])\\d{6}",[7,11],[["(\\d{3})(\\d{4})","$1 $2",["[235-9]|45"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["0"]]],0,0,0,0,0,0,0,"00"],FK:["500","00","[2-7]\\d{4}",[5]],FM:["691","00","(?:[39]\\d\\d|820)\\d{4}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[389]"]]]],FO:["298","00","[2-9]\\d{5}",[6],[["(\\d{6})","$1",["[2-9]"]]],0,0,"(10(?:01|[12]0|88))"],FR:["33","00","[1-9]\\d{8}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"],"0 $1"],["(\\d)(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4 $5",["[1-79]"],"0$1"]],"0"],GA:["241","00","(?:[067]\\d|11)\\d{6}|[2-7]\\d{6}",[7,8],[["(\\d)(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2-7]"],"0$1"],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["0"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["11|[67]"],"0$1"]],0,0,"0(11\\d{6}|60\\d{6}|61\\d{6}|6[256]\\d{6}|7[467]\\d{6})","$1"],GB:["44","00","[1-357-9]\\d{9}|[18]\\d{8}|8\\d{6}",[7,9,10],[["(\\d{3})(\\d{4})","$1 $2",["800","8001","80011","800111","8001111"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3",["845","8454","84546","845464"],"0$1"],["(\\d{3})(\\d{6})","$1 $2",["800"],"0$1"],["(\\d{5})(\\d{4,5})","$1 $2",["1(?:38|5[23]|69|76|94)","1(?:(?:38|69)7|5(?:24|39)|768|946)","1(?:3873|5(?:242|39[4-6])|(?:697|768)[347]|9467)"],"0$1"],["(\\d{4})(\\d{5,6})","$1 $2",["1(?:[2-69][02-9]|[78])"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["[25]|7(?:0|6[02-9])","[25]|7(?:0|6(?:[03-9]|2[356]))"],"0$1"],["(\\d{4})(\\d{6})","$1 $2",["7"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[1389]"],"0$1"]],"0",0,"0|180020",0,0,0,[["(?:1(?:1(?:3(?:[0-58]\\d\\d|73[0-5])|4(?:(?:[0-5]\\d|70)\\d|69[7-9])|(?:(?:5[0-26-9]|[78][0-49])\\d|6(?:[0-4]\\d|5[01]))\\d)|(?:2(?:(?:0[024-9]|2[3-9]|3[3-79]|4[1-689]|[58][02-9]|6[0-47-9]|7[013-9]|9\\d)\\d|1(?:[0-7]\\d|8[0-3]))|(?:3(?:0\\d|1[0-8]|[25][02-9]|3[02-579]|[468][0-46-9]|7[1-35-79]|9[2-578])|4(?:0[03-9]|[137]\\d|[28][02-57-9]|4[02-69]|5[0-8]|[69][0-79])|5(?:0[1-35-9]|[16]\\d|2[024-9]|3[015689]|4[02-9]|5[03-9]|7[0-35-9]|8[0-468]|9[0-57-9])|6(?:0[034689]|1\\d|2[0-35689]|[38][013-9]|4[1-467]|5[0-69]|6[13-9]|7[0-8]|9[0-24578])|7(?:0[0246-9]|2\\d|3[0236-8]|4[03-9]|5[0-46-9]|6[013-9]|7[0-35-9]|8[024-9]|9[02-9])|8(?:0[35-9]|2[1-57-9]|3[02-578]|4[0-578]|5[124-9]|6[2-69]|7\\d|8[02-9]|9[02569])|9(?:0[02-589]|[18]\\d|2[02-689]|3[1-57-9]|4[2-9]|5[0-579]|6[2-47-9]|7[0-24578]|9[2-57]))\\d)\\d)|2(?:0[013478]|3[0189]|4[017]|8[0-46-9]|9[0-2])\\d{3})\\d{4}|1(?:2(?:0(?:46[1-4]|87[2-9])|545[1-79]|76(?:2\\d|3[1-8]|6[1-6])|9(?:7(?:2[0-4]|3[2-5])|8(?:2[2-8]|7[0-47-9]|8[3-5])))|3(?:6(?:38[2-5]|47[23])|8(?:47[04-9]|64[0157-9]))|4(?:044[1-7]|20(?:2[23]|8\\d)|6(?:0(?:30|5[2-57]|6[1-8]|7[2-8])|140)|8(?:052|87[1-3]))|5(?:2(?:4(?:3[2-79]|6\\d)|76\\d)|6(?:26[06-9]|686))|6(?:06(?:4\\d|7[4-79])|295[5-7]|35[34]\\d|47(?:24|61)|59(?:5[08]|6[67]|74)|9(?:55[0-4]|77[23]))|7(?:26(?:6[13-9]|7[0-7])|(?:442|688)\\d|50(?:2[0-3]|[3-68]2|76))|8(?:27[56]\\d|37(?:5[2-5]|8[239])|843[2-58])|9(?:0(?:0(?:6[1-8]|85)|52\\d)|3583|4(?:66[1-8]|9(?:2[01]|81))|63(?:23|3[1-4])|9561))\\d{3}",[9,10]],["7(?:457[0-57-9]|700[01]|911[028])\\d{5}|7(?:[1-3]\\d\\d|4(?:[0-46-9]\\d|5[0-689])|5(?:0[0-8]|[13-9]\\d|2[0-35-9])|7(?:0[1-9]|[1-7]\\d|8[02-9]|9[0-689])|8(?:[014-9]\\d|[23][0-8])|9(?:[024-9]\\d|1[02-9]|3[0-689]))\\d{6}",[10]],["80[08]\\d{7}|800\\d{6}|8001111"],["(?:8(?:4[2-5]|7[0-3])|9(?:[01]\\d|8[2-49]))\\d{7}|845464\\d",[7,10]],["70\\d{8}",[10]],0,["(?:3[0347]|55)\\d{8}",[10]],["76(?:464|652)\\d{5}|76(?:0[0-28]|2[356]|34|4[01347]|5[49]|6[0-369]|77|8[14]|9[139])\\d{6}",[10]],["56\\d{8}",[10]]],0," x"],GD:["1","011","(?:473|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","473$1",0,"473"],GE:["995","00","(?:[3-57]\\d\\d|800)\\d{6}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["70"],"0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["32"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[57]"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[348]"],"0$1"]],"0"],GF:["594","00","(?:[56]94\\d|7093)\\d{5}|(?:80|9\\d)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-7]|9[47]"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[89]"],"0$1"]],"0"],GG:["44","00","(?:1481|[357-9]\\d{3})\\d{6}|8\\d{6}(?:\\d{2})?",[7,9,10],0,"0",0,"([25-9]\\d{5})$|0|180020","1481$1",0,0,[["1481[25-9]\\d{5}",[10]],["7(?:(?:781|839)\\d|911[17])\\d{5}",[10]],["80[08]\\d{7}|800\\d{6}|8001111"],["(?:8(?:4[2-5]|7[0-3])|9(?:[01]\\d|8[0-3]))\\d{7}|845464\\d",[7,10]],["70\\d{8}",[10]],0,["(?:3[0347]|55)\\d{8}",[10]],["76(?:464|652)\\d{5}|76(?:0[0-28]|2[356]|34|4[01347]|5[49]|6[0-369]|77|8[14]|9[139])\\d{6}",[10]],["56\\d{8}",[10]]]],GH:["233","00","(?:[235]\\d{3}|800)\\d{5}",[8,9],[["(\\d{3})(\\d{5})","$1 $2",["8"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[235]"],"0$1"]],"0"],GI:["350","00","(?:[25]\\d|60)\\d{6}",[8],[["(\\d{3})(\\d{5})","$1 $2",["2"]]]],GL:["299","00","(?:19|[2-689]\\d|70)\\d{4}",[6],[["(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3",["19|[2-9]"]]]],GM:["220","00","[2-9]\\d{6}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[2-9]"]]]],GN:["224","00","722\\d{6}|(?:3|6\\d)\\d{7}",[8,9],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["3"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[67]"]]]],GP:["590","00","(?:590\\d|7090)\\d{5}|(?:69|80|9\\d)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-79]"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"],"0$1"]],"0",0,0,0,0,0,[["590(?:0[1-68]|[14][0-24-9]|2[0-68]|3[1-9]|5[3-579]|[68][0-689]|7[08]|9\\d)\\d{4}"],["(?:69(?:0\\d\\d|1(?:2[2-9]|3[0-5])|4(?:0[89]|1[2-6]|9\\d)|6(?:1[016-9]|5[0-4]|[67]\\d))|7090[0-4])\\d{4}"],["80[0-5]\\d{6}"],0,0,0,0,0,["9(?:(?:39[5-7]|76[018])\\d|475[0-6])\\d{4}"]]],GQ:["240","00","222\\d{6}|(?:3\\d|55|[89]0)\\d{7}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[235]"]],["(\\d{3})(\\d{6})","$1 $2",["[89]"]]]],GR:["30","00","5005000\\d{3}|8\\d{9,11}|(?:[269]\\d|70)\\d{8}",[10,11,12],[["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["21|7"]],["(\\d{4})(\\d{6})","$1 $2",["2(?:2|3[2-57-9]|4[2-469]|5[2-59]|6[2-9]|7[2-69]|8[2-49])|5"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[2689]"]],["(\\d{3})(\\d{3,4})(\\d{5})","$1 $2 $3",["8"]]]],GT:["502","00","80\\d{6}|(?:1\\d{3}|[2-7])\\d{7}",[8,11],[["(\\d{4})(\\d{4})","$1 $2",["[2-8]"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["1"]]]],GU:["1","011","(?:[58]\\d\\d|671|900)\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","671$1",0,"671"],GW:["245","00","[49]\\d{8}|4\\d{6}",[7,9],[["(\\d{3})(\\d{4})","$1 $2",["40"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[49]"]]]],GY:["592","001","(?:[2-8]\\d{3}|9008)\\d{3}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[2-9]"]]]],HK:["852","00(?:30|5[09]|[126-9]?)","8[0-46-9]\\d{6,7}|9\\d{4,7}|(?:[2-7]|9\\d{3})\\d{7}",[5,6,7,8,9,11],[["(\\d{3})(\\d{2,5})","$1 $2",["900","9003"]],["(\\d{4})(\\d{4})","$1 $2",["[2-7]|8[1-4]|9(?:0[1-9]|[1-8])"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["8"]],["(\\d{3})(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3 $4",["9"]]],0,0,0,0,0,0,0,"00"],HN:["504","00","8\\d{10}|[237-9]\\d{7}",[8,11],[["(\\d{4})(\\d{4})","$1-$2",["[237-9]"]]]],HR:["385","00","[2-69]\\d{8}|80\\d{5,7}|[1-79]\\d{7}|6\\d{6}",[7,8,9],[["(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3",["6[01]"],"0$1"],["(\\d{3})(\\d{2})(\\d{2,3})","$1 $2 $3",["8"],"0$1"],["(\\d)(\\d{4})(\\d{3})","$1 $2 $3",["1"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["6|7[245]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["9"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[2-57]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["8"],"0$1"]],"0"],HT:["509","00","[2-589]\\d{7}",[8],[["(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3",["[2-589]"]]]],HU:["36","00","[235-7]\\d{8}|[1-9]\\d{7}",[8,9],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["1"],"(06 $1)"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[27][2-9]|3[2-7]|4[24-9]|5[2-79]|6|8[2-57-9]|9[2-69]"],"(06 $1)"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[2-9]"],"06 $1"]],"06"],ID:["62","00[89]","00[1-9]\\d{9,14}|(?:[1-36]|8\\d{5})\\d{6}|00\\d{9}|[1-9]\\d{8,10}|[2-9]\\d{7}",[7,8,9,10,11,12,13,14,15,16,17],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["15"]],["(\\d{2})(\\d{5,9})","$1 $2",["2[124]|[36]1"],"(0$1)"],["(\\d{3})(\\d{5,7})","$1 $2",["800"],"0$1"],["(\\d{3})(\\d{5,8})","$1 $2",["[2-79]"],"(0$1)"],["(\\d{3})(\\d{3,4})(\\d{3})","$1-$2-$3",["8[1-35-9]"],"0$1"],["(\\d{3})(\\d{6,8})","$1 $2",["1"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["804"],"0$1"],["(\\d{3})(\\d)(\\d{3})(\\d{3})","$1 $2 $3 $4",["80"],"0$1"],["(\\d{3})(\\d{4})(\\d{4,5})","$1-$2-$3",["8"],"0$1"]],"0"],IE:["353","00","(?:1\\d|[2569])\\d{6,8}|4\\d{6,9}|7\\d{8}|8\\d{8,9}",[7,8,9,10],[["(\\d{2})(\\d{5})","$1 $2",["2[24-9]|47|58|6[237-9]|9[35-9]"],"(0$1)"],["(\\d{3})(\\d{5})","$1 $2",["[45]0"],"(0$1)"],["(\\d)(\\d{3,4})(\\d{4})","$1 $2 $3",["1"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[2569]|4[1-69]|7[14]"],"(0$1)"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["70"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["81"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[78]"],"0$1"],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1"]],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["4"],"(0$1)"],["(\\d{2})(\\d)(\\d{3})(\\d{4})","$1 $2 $3 $4",["8"],"0$1"]],"0"],IL:["972","0(?:0|1[2-9])","1\\d{6}(?:\\d{3,5})?|[57]\\d{8}|[1-489]\\d{7}",[7,8,9,10,11,12],[["(\\d{4})(\\d{3})","$1-$2",["125"]],["(\\d{4})(\\d{2})(\\d{2})","$1-$2-$3",["121"]],["(\\d)(\\d{3})(\\d{4})","$1-$2-$3",["[2-489]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1-$2-$3",["[57]"],"0$1"],["(\\d{4})(\\d{3})(\\d{3})","$1-$2-$3",["12"]],["(\\d{4})(\\d{6})","$1-$2",["159"]],["(\\d)(\\d{3})(\\d{3})(\\d{3})","$1-$2-$3-$4",["1[7-9]"]],["(\\d{3})(\\d{1,2})(\\d{3})(\\d{4})","$1-$2 $3-$4",["15"]]],"0"],IM:["44","00","1624\\d{6}|(?:[3578]\\d|90)\\d{8}",[10],0,"0",0,"([25-8]\\d{5})$|0|180020","1624$1",0,"74576|(?:16|7[56])24"],IN:["91","00","(?:000800|[2-9]\\d\\d)\\d{7}|1\\d{7,12}",[8,9,10,11,12,13],[["(\\d{8})","$1",["5(?:0|2[23]|3[03]|[67]1|88)","5(?:0|2(?:21|3)|3(?:0|3[23])|616|717|888)","5(?:0|2(?:21|3)|3(?:0|3[23])|616|717|8888)"],0,1],["(\\d{4})(\\d{4,5})","$1 $2",["180","1800"],0,1],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["140"],0,1],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["11|2[02]|33|4[04]|79[1-7]|80[2-46]","11|2[02]|33|4[04]|79(?:[1-6]|7[19])|80(?:[2-4]|6[0-589])","11|2[02]|33|4[04]|79(?:[124-6]|3(?:[02-9]|1[0-24-9])|7(?:1|9[1-6]))|80(?:[2-4]|6[0-589])"],"0$1",1],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["1(?:2[0-249]|3[0-25]|4[145]|[68]|7[1257])|2(?:1[257]|3[013]|4[01]|5[0137]|6[0158]|78|8[1568])|3(?:26|4[1-3]|5[34]|6[01489]|7[02-46]|8[159])|4(?:1[36]|2[1-47]|5[12]|6[0-26-9]|7[0-24-9]|8[013-57]|9[014-7])|5(?:1[025]|22|[36][25]|4[28]|5[12]|[78]1)|6(?:12|[2-4]1|5[17]|6[13]|80)|7(?:12|3[134]|4[47]|61|88)|8(?:16|2[014]|3[126]|6[136]|7[078]|8[34]|91)|(?:43|59|75)[15]|(?:1[59]|29|67|72)[14]","1(?:2[0-24]|3[0-25]|4[145]|[59][14]|6[1-9]|7[1257]|8[1-57-9])|2(?:1[257]|3[013]|4[01]|5[0137]|6[058]|78|8[1568]|9[14])|3(?:26|4[1-3]|5[34]|6[01489]|7[02-46]|8[159])|4(?:1[36]|2[1-47]|3[15]|5[12]|6[0-26-9]|7[0-24-9]|8[013-57]|9[014-7])|5(?:1[025]|22|[36][25]|4[28]|[578]1|9[15])|674|7(?:(?:2[14]|3[34]|5[15])[2-6]|61[346]|88[0-8])|8(?:70[2-6]|84[235-7]|91[3-7])|(?:1(?:29|60|8[06])|261|552|6(?:12|[2-47]1|5[17]|6[13]|80)|7(?:12|31|4[47])|8(?:16|2[014]|3[126]|6[136]|7[78]|83))[2-7]","1(?:2[0-24]|3[0-25]|4[145]|[59][14]|6[1-9]|7[1257]|8[1-57-9])|2(?:1[257]|3[013]|4[01]|5[0137]|6[058]|78|8[1568]|9[14])|3(?:26|4[1-3]|5[34]|6[01489]|7[02-46]|8[159])|4(?:1[36]|2[1-47]|3[15]|5[12]|6[0-26-9]|7[0-24-9]|8[013-57]|9[014-7])|5(?:1[025]|22|[36][25]|4[28]|[578]1|9[15])|6(?:12(?:[2-6]|7[0-8])|74[2-7])|7(?:(?:2[14]|5[15])[2-6]|3171|61[346]|88(?:[2-7]|82))|8(?:70[2-6]|84(?:[2356]|7[19])|91(?:[3-6]|7[19]))|73[134][2-6]|(?:74[47]|8(?:16|2[014]|3[126]|6[136]|7[78]|83))(?:[2-6]|7[19])|(?:1(?:29|60|8[06])|261|552|6(?:[2-4]1|5[17]|6[13]|7(?:1|4[0189])|80)|7(?:12|88[01]))[2-7]"],"0$1",1],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1(?:[2-479]|5[0235-9])|[2-5]|6(?:1[1358]|2[2457-9]|3[2-5]|4[235-7]|5[2-689]|6[24578]|7[235689]|8[1-6])|7(?:1[013-9]|28|3[129]|4[1-35689]|5[29]|6[02-5]|70)|807","1(?:[2-479]|5[0235-9])|[2-5]|6(?:1[1358]|2(?:[2457]|84|95)|3(?:[2-4]|55)|4[235-7]|5[2-689]|6[24578]|7[235689]|8[1-6])|7(?:1(?:[013-8]|9[6-9])|28[6-8]|3(?:17|2[0-49]|9[2-57])|4(?:1[2-4]|[29][0-7]|3[0-8]|[56]|8[0-24-7])|5(?:2[1-3]|9[0-6])|6(?:0[5689]|2[5-9]|3[02-8]|4|5[0-367])|70[13-7])|807[19]","1(?:[2-479]|5(?:[0236-9]|5[013-9]))|[2-5]|6(?:2(?:84|95)|355|8(?:28[235-7]|3))|73179|807(?:1|9[1-3])|(?:1552|6(?:(?:1[1358]|2[2457]|3[2-4]|4[235-7]|5[2-689]|6[24578]|7[235689])\\d|8(?:[14-6]\\d|2[0-79]))|7(?:1(?:[013-8]\\d|9[6-9])|28[6-8]|3(?:2[0-49]|9[2-57])|4(?:1[2-4]|[29][0-7]|3[0-8]|[56]\\d|8[0-24-7])|5(?:2[1-3]|9[0-6])|6(?:0[5689]|2[5-9]|3[02-8]|4\\d|5[0-367])|70[13-7]))[2-7]"],"0$1",1],["(\\d{5})(\\d{5})","$1 $2",["[6-9]"],"0$1",1],["(\\d{4})(\\d{2,4})(\\d{4})","$1 $2 $3",["1(?:6|8[06])","1(?:6|8[06]0)"],0,1],["(\\d{4})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["18"],0,1]],"0"],IO:["246","00","3\\d{6}",[7],[["(\\d{3})(\\d{4})","$1 $2",["3"]]]],IQ:["964","00","(?:1|7\\d\\d)\\d{7}|[2-6]\\d{7,8}",[8,9,10],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["1"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[2-6]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["7"],"0$1"]],"0"],IR:["98","00","[1-9]\\d{9}|(?:[1-8]\\d\\d|9)\\d{3,4}",[4,5,6,7,10],[["(\\d{4,5})","$1",["96"],"0$1"],["(\\d{2})(\\d{4,5})","$1 $2",["(?:1[137]|2[13-68]|3[1458]|4[145]|5[1468]|6[16]|7[1467]|8[13467])[12689]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["9"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["[1-8]"],"0$1"]],"0"],IS:["354","00|1(?:0(?:01|[12]0)|100)","(?:38\\d|[4-9])\\d{6}",[7,9],[["(\\d{3})(\\d{4})","$1 $2",["[4-9]"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["3"]]],0,0,0,0,0,0,0,"00"],IT:["39","00","0\\d{5,11}|1\\d{8,10}|3(?:[0-8]\\d{7,10}|9\\d{7,8})|(?:43|55|70)\\d{8}|8\\d{5}(?:\\d{2,4})?",[6,7,8,9,10,11,12],[["(\\d{2})(\\d{4,6})","$1 $2",["0[26]"]],["(\\d{3})(\\d{3,6})","$1 $2",["0[13-57-9][0159]|8(?:03|4[17]|9[2-5])","0[13-57-9][0159]|8(?:03|4[17]|9(?:2|3[04]|[45][0-4]))"]],["(\\d{4})(\\d{2,6})","$1 $2",["0(?:[13-579][2-46-8]|8[236-8])"]],["(\\d{4})(\\d{4})","$1 $2",["894"]],["(\\d{2})(\\d{3,4})(\\d{4})","$1 $2 $3",["0[26]|5"]],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["1(?:44|[679])|[378]|43"]],["(\\d{3})(\\d{3,4})(\\d{4})","$1 $2 $3",["0[13-57-9][0159]|14"]],["(\\d{2})(\\d{4})(\\d{5})","$1 $2 $3",["0[26]"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["0"]],["(\\d{3})(\\d{4})(\\d{4,5})","$1 $2 $3",["[03]"]]],0,0,0,0,0,0,[["0(?:669[0-79]\\d{1,6}|831\\d{2,8})|0(?:1(?:[0159]\\d|[27][1-5]|31|4[1-4]|6[1356]|8[2-57])|2\\d\\d|3(?:[0159]\\d|2[1-4]|3[12]|[48][1-6]|6[2-59]|7[1-7])|4(?:[0159]\\d|[23][1-9]|4[245]|6[1-5]|7[1-4]|81)|5(?:[0159]\\d|2[1-5]|3[2-6]|4[1-79]|6[4-6]|7[1-578]|8[3-8])|6(?:[0-57-9]\\d|6[0-8])|7(?:[0159]\\d|2[12]|3[1-7]|4[2-46]|6[13569]|7[13-6]|8[1-59])|8(?:[0159]\\d|2[3-578]|3[2356]|[6-8][1-5])|9(?:[0159]\\d|[238][1-5]|4[12]|6[1-8]|7[1-6]))\\d{2,7}"],["3[2-9]\\d{7,8}|(?:31|43)\\d{8}",[9,10]],["80(?:0\\d{3}|3)\\d{3}",[6,9]],["(?:0878\\d{3}|89(?:2\\d|3[04]|4(?:[0-4]|[5-9]\\d\\d)|5[0-4]))\\d\\d|(?:1(?:44|6[346])|89(?:38|5[5-9]|9))\\d{6}",[6,8,9,10]],["1(?:78\\d|99)\\d{6}",[9,10]],["3[2-8]\\d{9,10}",[11,12]],0,0,["55\\d{8}",[10]],["84(?:[08]\\d{3}|[17])\\d{3}",[6,9]]]],JE:["44","00","1534\\d{6}|(?:[3578]\\d|90)\\d{8}",[10],0,"0",0,"([0-24-8]\\d{5})$|0|180020","1534$1",0,0,[["1534[0-24-8]\\d{5}"],["7(?:(?:(?:50|82)9|937)\\d|7(?:00[378]|97\\d))\\d{5}"],["80(?:07(?:35|81)|8901)\\d{4}"],["(?:8(?:4(?:4(?:4(?:05|42|69)|703)|5(?:041|800))|7(?:0002|1206))|90(?:066[59]|1810|71(?:07|55)))\\d{4}"],["701511\\d{4}"],0,["(?:3(?:0(?:07(?:35|81)|8901)|3\\d{4}|4(?:4(?:4(?:05|42|69)|703)|5(?:041|800))|7(?:0002|1206))|55\\d{4})\\d{4}"],["76(?:464|652)\\d{5}|76(?:0[0-28]|2[356]|34|4[01347]|5[49]|6[0-369]|77|8[14]|9[139])\\d{6}"],["56\\d{8}"]]],JM:["1","011","(?:[58]\\d\\d|658|900)\\d{7}",[10],0,"1",0,0,0,0,"658|876"],JO:["962","00","(?:(?:[2689]|7\\d)\\d|32|427|53)\\d{6}",[8,9],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["[2356]|87"],"(0$1)"],["(\\d{3})(\\d{5,6})","$1 $2",["[89]"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["70"],"0$1"],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["[47]"],"0$1"]],"0"],JP:["81","010","00[1-9]\\d{6,14}|[25-9]\\d{9}|(?:00|[1-9]\\d\\d)\\d{6}",[8,9,10,11,12,13,14,15,16,17],[["(\\d{3})(\\d{3})(\\d{3})","$1-$2-$3",["(?:12|57|99)0"],"0$1"],["(\\d{4})(\\d)(\\d{4})","$1-$2-$3",["1(?:26|3[79]|4[56]|5[4-68]|6[3-5])|499|5(?:76|97)|746|8(?:3[89]|47|51)|9(?:80|9[16])","1(?:267|3(?:7[247]|9[278])|466|5(?:47|58|64)|6(?:3[245]|48|5[4-68]))|499[2468]|5(?:76|97)9|7468|8(?:3(?:8[7-9]|96)|477|51[2-9])|9(?:802|9(?:1[23]|69))|1(?:45|58)[67]","1(?:267|3(?:7[247]|9[278])|466|5(?:47|58|64)|6(?:3[245]|48|5[4-68]))|499[2468]|5(?:769|979[2-69])|7468|8(?:3(?:8[7-9]|96[2457-9])|477|51[2-9])|9(?:802|9(?:1[23]|69))|1(?:45|58)[67]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1-$2-$3",["60"],"0$1"],["(\\d)(\\d{4})(\\d{4})","$1-$2-$3",["3|4(?:2[09]|7[01])|6[1-9]","3|4(?:2(?:0|9[02-69])|7(?:0[019]|1))|6[1-9]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1-$2-$3",["1(?:1|5[45]|77|88|9[69])|2(?:2[1-37]|3[0-269]|4[59]|5|6[24]|7[1-358]|8[1369]|9[0-38])|4(?:[28][1-9]|3[0-57]|[45]|6[248]|7[2-579]|9[29])|5(?:2|3[0459]|4[0-369]|5[29]|8[02389]|9[0-389])|7(?:2[02-46-9]|34|[58]|6[0249]|7[57]|9[2-6])|8(?:2[124589]|3[26-9]|49|51|6|7[0-468]|8[68]|9[019])|9(?:[23][1-9]|4[15]|5[138]|6[1-3]|7[156]|8[189]|9[1-489])","1(?:1|5(?:4[018]|5[017])|77|88|9[69])|2(?:2(?:[127]|3[014-9])|3[0-269]|4[59]|5(?:[1-3]|5[0-69]|9[19])|62|7(?:[1-35]|8[0189])|8(?:[16]|3[0134]|9[0-5])|9(?:[028]|17))|4(?:2(?:[13-79]|8[014-6])|3[0-57]|[45]|6[248]|7[2-47]|8[1-9]|9[29])|5(?:2|3(?:[045]|9[0-8])|4[0-369]|5[29]|8[02389]|9[0-3])|7(?:2[02-46-9]|34|[58]|6[0249]|7[57]|9(?:[23]|4[0-59]|5[01569]|6[0167]))|8(?:2(?:[1258]|4[0-39]|9[0-2469])|3(?:[29]|60)|49|51|6(?:[0-24]|36|5[0-3589]|7[23]|9[01459])|7[0-468]|8[68])|9(?:[23][1-9]|4[15]|5[138]|6[1-3]|7[156]|8[189]|9(?:[1289]|3[34]|4[0178]))|(?:264|837)[016-9]|2(?:57|93)[015-9]|(?:25[0468]|422|838)[01]|(?:47[59]|59[89]|8(?:6[68]|9))[019]","1(?:1|5(?:4[018]|5[017])|77|88|9[69])|2(?:2[127]|3[0-269]|4[59]|5(?:[1-3]|5[0-69]|9(?:17|99))|6(?:2|4[016-9])|7(?:[1-35]|8[0189])|8(?:[16]|3[0134]|9[0-5])|9(?:[028]|17))|4(?:2(?:[13-79]|8[014-6])|3[0-57]|[45]|6[248]|7[2-47]|9[29])|5(?:2|3(?:[045]|9(?:[0-58]|6[4-9]|7[0-35689]))|4[0-369]|5[29]|8[02389]|9[0-3])|7(?:2[02-46-9]|34|[58]|6[0249]|7[57]|9(?:[23]|4[0-59]|5[01569]|6[0167]))|8(?:2(?:[1258]|4[0-39]|9[0169])|3(?:[29]|60|7(?:[017-9]|6[6-8]))|49|51|6(?:[0-24]|36[2-57-9]|5(?:[0-389]|5[23])|6(?:[01]|9[178])|7(?:2[2-468]|3[78])|9[0145])|7[0-468]|8[68])|9(?:4[15]|5[138]|7[156]|8[189]|9(?:[1289]|3(?:31|4[357])|4[0178]))|(?:8294|96)[1-3]|2(?:57|93)[015-9]|(?:223|8699)[014-9]|(?:25[0468]|422|838)[01]|(?:48|8292|9[23])[1-9]|(?:47[59]|59[89]|8(?:68|9))[019]"],"0$1"],["(\\d{3})(\\d{2})(\\d{4})","$1-$2-$3",["[14]|[289][2-9]|5[3-9]|7[2-4679]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1-$2-$3",["800"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1-$2-$3",["[25-9]"],"0$1"]],"0",0,"(000[2569]\\d{4,6})$|(?:(?:003768)0?)|0","$1"],KE:["254","000","(?:[17]\\d\\d|900)\\d{6}|(?:2|80)0\\d{6,7}|[4-6]\\d{6,8}",[7,8,9,10],[["(\\d{2})(\\d{5,7})","$1 $2",["[24-6]"],"0$1"],["(\\d{3})(\\d{6})","$1 $2",["[17]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["[89]"],"0$1"]],"0"],KG:["996","00","8\\d{9}|[235-9]\\d{8}",[9,10],[["(\\d{4})(\\d{5})","$1 $2",["3(?:1[346]|[24-79])"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[235-79]|88"],"0$1"],["(\\d{3})(\\d{3})(\\d)(\\d{2,3})","$1 $2 $3 $4",["8"],"0$1"]],"0"],KH:["855","00[14-9]","1\\d{9}|[1-9]\\d{7,8}",[8,9,10],[["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[1-9]"],"0$1"],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1"]]],"0"],KI:["686","00","(?:[37]\\d|6[0-79])\\d{6}|(?:[2-48]\\d|50)\\d{3}",[5,8],0,"0"],KM:["269","00","[3478]\\d{6}",[7],[["(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3",["[3478]"]]]],KN:["1","011","(?:[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-7]\\d{6})$|1","869$1",0,"869"],KP:["850","00|99","85\\d{6}|(?:19\\d|[2-7])\\d{7}",[8,10],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["8"],"0$1"],["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["[2-7]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["1"],"0$1"]],"0"],KR:["82","00(?:[125689]|3(?:[46]5|91)|7(?:00|27|3|55|6[126]))","00[1-9]\\d{8,11}|(?:[12]|5\\d{3})\\d{7}|[13-6]\\d{9}|(?:[1-6]\\d|80)\\d{7}|[3-6]\\d{4,5}|(?:00|7)0\\d{8}",[5,6,8,9,10,11,12,13,14],[["(\\d{2})(\\d{3,4})","$1-$2",["(?:3[1-3]|[46][1-4]|5[1-5])1"],"0$1"],["(\\d{4})(\\d{4})","$1-$2",["1"]],["(\\d)(\\d{3,4})(\\d{4})","$1-$2-$3",["2"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1-$2-$3",["[36]0|8"],"0$1"],["(\\d{2})(\\d{3,4})(\\d{4})","$1-$2-$3",["[1346]|5[1-5]"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1-$2-$3",["[57]"],"0$1"],["(\\d{2})(\\d{5})(\\d{4})","$1-$2-$3",["5"],"0$1"]],"0",0,"0(8(?:[1-46-8]|5\\d\\d))?"],KW:["965","00","18\\d{5}|(?:[2569]\\d|41)\\d{6}",[7,8],[["(\\d{4})(\\d{3,4})","$1 $2",["[169]|2(?:[235]|4[1-35-9])|52"]],["(\\d{3})(\\d{5})","$1 $2",["[245]"]]]],KY:["1","011","(?:345|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","345$1",0,"345"],KZ:["7","810","(?:33622|8\\d{8})\\d{5}|[78]\\d{9}",[10,14],0,"8",0,0,0,0,"33622|7",0,"8~10"],LA:["856","00","[23]\\d{9}|3\\d{8}|(?:[235-8]\\d|41)\\d{6}",[8,9,10],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["2[13]|3[14]|[4-8]"],"0$1"],["(\\d{2})(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3 $4",["3"],"0$1"],["(\\d{2})(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3 $4",["[23]"],"0$1"]],"0"],LB:["961","00","[27-9]\\d{7}|[13-9]\\d{6}",[7,8],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["[13-69]|7(?:[2-57]|62|8[0-6]|9[04-9])|8[02-9]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[27-9]"]]],"0"],LC:["1","011","(?:[58]\\d\\d|758|900)\\d{7}",[10],0,"1",0,"([2-8]\\d{6})$|1","758$1",0,"758"],LI:["423","00","[68]\\d{8}|(?:[2378]\\d|90)\\d{5}",[7,9],[["(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3",["[2379]|8(?:0[09]|7)","[2379]|8(?:0(?:02|9)|7)"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["8"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["69"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["6"]]],"0",0,"(1001)|0"],LK:["94","00","[1-9]\\d{8}",[9],[["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["7"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[1-689]"],"0$1"]],"0"],LR:["231","00","(?:[2457]\\d|33|88)\\d{7}|(?:2\\d|[4-6])\\d{6}",[7,8,9],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["4[67]|[56]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["2"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[2-578]"],"0$1"]],"0"],LS:["266","00","(?:[256]\\d\\d|800)\\d{5}",[8],[["(\\d{4})(\\d{4})","$1 $2",["[2568]"]]]],LT:["370","00","(?:[3469]\\d|52|[78]0)\\d{6}",[8],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["52[0-7]"],"(0-$1)",1],["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["[7-9]"],"0 $1",1],["(\\d{2})(\\d{6})","$1 $2",["37|4(?:[15]|6[1-8])"],"(0-$1)",1],["(\\d{3})(\\d{5})","$1 $2",["[3-6]"],"(0-$1)",1]],"0",0,"[08]"],LU:["352","00","35[013-9]\\d{4,8}|6\\d{8}|35\\d{2,4}|(?:[2457-9]\\d|3[0-46-9])\\d{2,9}",[4,5,6,7,8,9,10,11],[["(\\d{2})(\\d{3})","$1 $2",["2(?:0[2-689]|[2-9])|[3-57]|8(?:0[2-9]|[13-9])|9(?:0[89]|[2-579])"]],["(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3",["2(?:0[2-689]|[2-9])|[3-57]|8(?:0[2-9]|[13-9])|9(?:0[89]|[2-579])"]],["(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3",["20[2-689]"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{1,2})","$1 $2 $3 $4",["2(?:[0367]|4[3-8])"]],["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["80[01]|90[015]"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3 $4",["20"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["6"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{1,2})","$1 $2 $3 $4 $5",["2(?:[0367]|4[3-8])"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{1,5})","$1 $2 $3 $4",["[3-57]|8[13-9]|9(?:0[89]|[2-579])|(?:2|80)[2-9]"]]],0,0,"(15(?:0[06]|1[12]|[35]5|4[04]|6[26]|77|88|99)\\d)"],LV:["371","00","(?:[268]\\d|78|90)\\d{6}",[8],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[2679]|8[01]"]]]],LY:["218","00","[2-9]\\d{8}",[9],[["(\\d{2})(\\d{7})","$1-$2",["[2-9]"],"0$1"]],"0"],MA:["212","00","[5-8]\\d{8}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["5[45]"],"0$1"],["(\\d{4})(\\d{5})","$1-$2",["5(?:[19]|2[2-46-9]|3[3-9])|8(?:0[89]|92)"],"0$1"],["(\\d{2})(\\d{7})","$1-$2",["8"],"0$1"],["(\\d{3})(\\d{6})","$1-$2",["[5-7]"],"0$1"]],"0",0,0,0,0,0,[["5(?:(?:18|4[0679]|5[03])\\d|2(?:[0-25-79]\\d|3[1-578]|4[02-46-8]|8[0235-7])|3(?:[0-47]\\d|5[02-9]|6[02-8]|8[014-9]|9[3-9]))\\d{5}"],["(?:6(?:[0-79]\\d|8[0-247-9])|7(?:[016-8]\\d|2[0-8]|5[0-5]))\\d{6}"],["80[0-7]\\d{6}"],["89\\d{7}"],0,0,0,0,["(?:592(?:4[0-2]|93)|80[89]\\d\\d)\\d{4}"]]],MC:["377","00","(?:[3489]|[67]\\d)\\d{7}",[8,9],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["4"],"0$1"],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[389]"]],["(\\d)(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4 $5",["[67]"],"0$1"]],"0"],MD:["373","00","(?:[235-7]\\d|[89]0)\\d{6}",[8],[["(\\d{3})(\\d{5})","$1 $2",["[89]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["22|3"],"0$1"],["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["[25-7]"],"0$1"]],"0"],ME:["382","00","(?:20|[3-79]\\d)\\d{6}|80\\d{6,7}",[8,9],[["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[2-9]"],"0$1"]],"0"],MF:["590","00","(?:590\\d|7090)\\d{5}|(?:69|80|9\\d)\\d{7}",[9],0,"0",0,0,0,0,0,[["590(?:0[079]|[14]3|[27][79]|3[03-7]|5[0-268]|87)\\d{4}"],["(?:69(?:0\\d\\d|1(?:2[2-9]|3[0-5])|4(?:0[89]|1[2-6]|9\\d)|6(?:1[016-9]|5[0-4]|[67]\\d))|7090[0-4])\\d{4}"],["80[0-5]\\d{6}"],0,0,0,0,0,["9(?:(?:39[5-7]|76[018])\\d|475[0-6])\\d{4}"]]],MG:["261","00","[23]\\d{8}",[9],[["(\\d{2})(\\d{2})(\\d{3})(\\d{2})","$1 $2 $3 $4",["[23]"],"0$1"]],"0",0,"([24-9]\\d{6})$|0","20$1"],MH:["692","011","329\\d{4}|(?:[256]\\d|45)\\d{5}",[7],[["(\\d{3})(\\d{4})","$1-$2",["[2-6]"]]],"1"],MK:["389","00","[2-578]\\d{7}",[8],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["2|34[47]|4(?:[37]7|5[47]|64)"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[347]"],"0$1"],["(\\d{3})(\\d)(\\d{2})(\\d{2})","$1 $2 $3 $4",["[58]"],"0$1"]],"0"],ML:["223","00","[24-9]\\d{7}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[24-9]"]]]],MM:["95","00","1\\d{5,7}|95\\d{6}|(?:[4-7]|9[0-46-9])\\d{6,8}|(?:2|8\\d)\\d{5,8}",[6,7,8,9,10],[["(\\d)(\\d{2})(\\d{3})","$1 $2 $3",["16|2"],"0$1"],["(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3",["4(?:[2-46]|5[3-5])|5|6(?:[1-689]|7[235-7])|7(?:[0-4]|5[2-7])|8[1-5]|(?:60|86)[23]"],"0$1"],["(\\d)(\\d{3})(\\d{3,4})","$1 $2 $3",["[12]|452|678|86","[12]|452|6788|86"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[4-7]|8[1-35]"],"0$1"],["(\\d)(\\d{3})(\\d{4,6})","$1 $2 $3",["9(?:2[0-4]|[35-9]|4[137-9])"],"0$1"],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["2"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["8"],"0$1"],["(\\d)(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["92"],"0$1"],["(\\d)(\\d{5})(\\d{4})","$1 $2 $3",["9"],"0$1"]],"0"],MN:["976","001","[12]\\d{7,9}|[5-9]\\d{7}",[8,9,10],[["(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3",["[12]1"],"0$1"],["(\\d{4})(\\d{4})","$1 $2",["[5-9]"]],["(\\d{3})(\\d{5,6})","$1 $2",["[12]2[1-3]"],"0$1"],["(\\d{4})(\\d{5,6})","$1 $2",["[12](?:27|3[2-8]|4[2-68]|5[1-4689])","[12](?:27|3[2-8]|4[2-68]|5[1-4689])[0-3]"],"0$1"],["(\\d{5})(\\d{4,5})","$1 $2",["[12]"],"0$1"]],"0"],MO:["853","00","0800\\d{3}|(?:28|[68]\\d)\\d{6}",[7,8],[["(\\d{4})(\\d{3})","$1 $2",["0"]],["(\\d{4})(\\d{4})","$1 $2",["[268]"]]]],MP:["1","011","[58]\\d{9}|(?:67|90)0\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","670$1",0,"670"],MQ:["596","00","(?:596\\d|7091)\\d{5}|(?:69|[89]\\d)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-79]|8(?:0[6-9]|[36])"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"],"0$1"]],"0"],MR:["222","00","(?:[2-4]\\d\\d|800)\\d{5}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2-48]"]]]],MS:["1","011","(?:[58]\\d\\d|664|900)\\d{7}",[10],0,"1",0,"([34]\\d{6})$|1","664$1",0,"664"],MT:["356","00","3550\\d{4}|(?:[2579]\\d\\d|800)\\d{5}",[8],[["(\\d{4})(\\d{4})","$1 $2",["[2357-9]"]]]],MU:["230","0(?:0|[24-7]0|3[03])","(?:[57]|8\\d\\d)\\d{7}|[2-468]\\d{6}",[7,8,10],[["(\\d{3})(\\d{4})","$1 $2",["[2-46]|8[013]"]],["(\\d{4})(\\d{4})","$1 $2",["[57]"]],["(\\d{5})(\\d{5})","$1 $2",["8"]]],0,0,0,0,0,0,0,"020"],MV:["960","0(?:0|19)","(?:800|9[0-57-9]\\d)\\d{7}|[34679]\\d{6}",[7,10],[["(\\d{3})(\\d{4})","$1-$2",["[34679]"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[89]"]]],0,0,0,0,0,0,0,"00"],MW:["265","00","(?:[1289]\\d|31|77)\\d{7}|1\\d{6}",[7,9],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["1[2-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["2"],"0$1"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[137-9]"],"0$1"]],"0"],MX:["52","0[09]","[2-9]\\d{9}",[10],[["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["33|5[56]|81"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[2-9]"]]],0,0,0,0,0,0,0,"00"],MY:["60","00","1\\d{8,9}|(?:3\\d|[4-9])\\d{7}",[8,9,10],[["(\\d)(\\d{3})(\\d{4})","$1-$2 $3",["[4-79]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1-$2 $3",["1(?:[02469]|[378][1-9]|53)|8","1(?:[02469]|[37][1-9]|53|8(?:[1-46-9]|5[7-9]))|8"],"0$1"],["(\\d)(\\d{4})(\\d{4})","$1-$2 $3",["3"],"0$1"],["(\\d)(\\d{3})(\\d{2})(\\d{4})","$1-$2-$3-$4",["1(?:[367]|80)"]],["(\\d{3})(\\d{3})(\\d{4})","$1-$2 $3",["15"],"0$1"],["(\\d{2})(\\d{4})(\\d{4})","$1-$2 $3",["1"],"0$1"]],"0"],MZ:["258","00","(?:2|8\\d)\\d{7}",[8,9],[["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["2|8[2-79]"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["8"]]]],NA:["264","00","[68]\\d{7,8}",[8,9],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["88"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["6"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["87"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["8"],"0$1"]],"0"],NC:["687","00","(?:050|[2-57-9]\\d\\d)\\d{3}",[6],[["(\\d{2})(\\d{2})(\\d{2})","$1.$2.$3",["[02-57-9]"]]]],NE:["227","00","[027-9]\\d{7}",[8],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["08"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[089]|2[013]|7[0467]"]]]],NF:["672","00","[13]\\d{5}",[6],[["(\\d{2})(\\d{4})","$1 $2",["1[0-3]"]],["(\\d)(\\d{5})","$1 $2",["[13]"]]],0,0,"([0-258]\\d{4})$","3$1"],NG:["234","009","(?:20|9\\d)\\d{8}|[78]\\d{9,13}",[10,11,12,13,14],[["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["[7-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["20[129]"],"0$1"],["(\\d{4})(\\d{2})(\\d{4})","$1 $2 $3",["2"],"0$1"],["(\\d{3})(\\d{4})(\\d{4,5})","$1 $2 $3",["[78]"],"0$1"],["(\\d{3})(\\d{5})(\\d{5,6})","$1 $2 $3",["[78]"],"0$1"]],"0"],NI:["505","00","(?:1800|[25-8]\\d{3})\\d{4}",[8],[["(\\d{4})(\\d{4})","$1 $2",["[125-8]"]]]],NL:["31","00","(?:[124-7]\\d\\d|3(?:[02-9]\\d|1[0-8]))\\d{6}|8\\d{6,9}|9\\d{6,10}|1\\d{4,5}",[5,6,7,8,9,10,11],[["(\\d{3})(\\d{4,7})","$1 $2",["[89]0"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["66"],"0$1"],["(\\d)(\\d{8})","$1 $2",["6"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["1[16-8]|2[259]|3[124]|4[17-9]|5[124679]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[1-578]|91"],"0$1"],["(\\d{3})(\\d{3})(\\d{5})","$1 $2 $3",["9"],"0$1"]],"0"],NO:["47","00","(?:0|[2-9]\\d{3})\\d{4}",[5,8],[["(\\d{3})(\\d{2})(\\d{3})","$1 $2 $3",["8"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[2-79]"]]],0,0,0,0,0,"[02-689]|7[0-8]"],NP:["977","00","(?:1\\d|9)\\d{9}|[1-9]\\d{7}",[8,10,11],[["(\\d)(\\d{7})","$1-$2",["1[2-6]"],"0$1"],["(\\d{2})(\\d{6})","$1-$2",["1[01]|[2-8]|9(?:[1-59]|[67][2-6])"],"0$1"],["(\\d{3})(\\d{7})","$1-$2",["9"]]],"0"],NR:["674","00","(?:222|444|(?:55|8\\d)\\d|666|777|999)\\d{4}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[24-9]"]]]],NU:["683","00","(?:[4-7]|888\\d)\\d{3}",[4,7],[["(\\d{3})(\\d{4})","$1 $2",["8"]]]],NZ:["64","0(?:0|161)","[1289]\\d{9}|50\\d{5}(?:\\d{2,3})?|[27-9]\\d{7,8}|(?:[34]\\d|6[0-35-9])\\d{6}|8\\d{4,6}",[5,6,7,8,9,10],[["(\\d{2})(\\d{3,8})","$1 $2",["8[1-79]"],"0$1"],["(\\d{3})(\\d{2})(\\d{2,3})","$1 $2 $3",["50[036-8]|8|90","50(?:[0367]|88)|8|90"],"0$1"],["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["24|[346]|7[2-57-9]|9[2-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["2(?:10|74)|[589]"],"0$1"],["(\\d{2})(\\d{3,4})(\\d{4})","$1 $2 $3",["1|2[028]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,5})","$1 $2 $3",["2(?:[169]|7[0-35-9])|7"],"0$1"]],"0",0,0,0,0,0,0,"00"],OM:["968","00","(?:1505|[279]\\d{3}|500)\\d{4}|800\\d{5,6}",[7,8,9],[["(\\d{3})(\\d{4,6})","$1 $2",["[58]"]],["(\\d{2})(\\d{6})","$1 $2",["2"]],["(\\d{4})(\\d{4})","$1 $2",["[179]"]]]],PA:["507","00","(?:00800|8\\d{3})\\d{6}|[68]\\d{7}|[1-57-9]\\d{6}",[7,8,10,11],[["(\\d{3})(\\d{4})","$1-$2",["[1-57-9]"]],["(\\d{4})(\\d{4})","$1-$2",["[68]"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["8"]]]],PE:["51","00|19(?:1[124]|77|90)00","(?:[14-8]|9\\d)\\d{7}",[8,9],[["(\\d{3})(\\d{5})","$1 $2",["80"],"(0$1)"],["(\\d)(\\d{7})","$1 $2",["1"],"(0$1)"],["(\\d{2})(\\d{6})","$1 $2",["[4-8]"],"(0$1)"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["9"]]],"0",0,0,0,0,0,0,"00"," Anexo "],PF:["689","00","4\\d{5}(?:\\d{2})?|8\\d{7,8}",[6,8,9],[["(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3",["44"]],["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["4|8[7-9]"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"]]]],PG:["675","00|140[1-3]","(?:180|[78]\\d{3})\\d{4}|(?:[2-589]\\d|64)\\d{5}",[7,8],[["(\\d{3})(\\d{4})","$1 $2",["18|[2-69]|85"]],["(\\d{4})(\\d{4})","$1 $2",["[78]"]]],0,0,0,0,0,0,0,"00"],PH:["63","00","(?:[2-7]|9\\d)\\d{8}|2\\d{5}|(?:1800|8)\\d{7,9}",[6,8,9,10,11,12,13],[["(\\d)(\\d{5})","$1 $2",["2"],"(0$1)"],["(\\d{4})(\\d{4,6})","$1 $2",["3(?:23|39|46)|4(?:2[3-6]|[35]9|4[26]|76)|544|88[245]|(?:52|64|86)2","3(?:230|397|461)|4(?:2(?:35|[46]4|51)|396|4(?:22|63)|59[347]|76[15])|5(?:221|446)|642[23]|8(?:622|8(?:[24]2|5[13]))"],"(0$1)"],["(\\d{5})(\\d{4})","$1 $2",["346|4(?:27|9[35])|883","3469|4(?:279|9(?:30|56))|8834"],"(0$1)"],["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["2"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[3-7]|8[2-8]"],"(0$1)"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["[89]"],"0$1"],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["1"]],["(\\d{4})(\\d{1,2})(\\d{3})(\\d{4})","$1 $2 $3 $4",["1"]]],"0"],PK:["92","00","122\\d{6}|[24-8]\\d{10,11}|9(?:[013-9]\\d{8,10}|2(?:[01]\\d\\d|2(?:[06-8]\\d|1[01]))\\d{7})|(?:[2-8]\\d{3}|92(?:[0-7]\\d|8[1-9]))\\d{6}|[24-9]\\d{8}|[89]\\d{7}",[8,9,10,11,12],[["(\\d{3})(\\d{3})(\\d{2,7})","$1 $2 $3",["[89]0"],"0$1"],["(\\d{4})(\\d{5})","$1 $2",["1"]],["(\\d{3})(\\d{6,7})","$1 $2",["2(?:3[2358]|4[2-4]|9[2-8])|45[3479]|54[2-467]|60[468]|72[236]|8(?:2[2-689]|3[23578]|4[3478]|5[2356])|9(?:2[2-8]|3[27-9]|4[2-6]|6[3569]|9[25-8])","9(?:2[3-8]|98)|(?:2(?:3[2358]|4[2-4]|9[2-8])|45[3479]|54[2-467]|60[468]|72[236]|8(?:2[2-689]|3[23578]|4[3478]|5[2356])|9(?:22|3[27-9]|4[2-6]|6[3569]|9[25-7]))[2-9]"],"(0$1)"],["(\\d{2})(\\d{7,8})","$1 $2",["(?:2[125]|4[0-246-9]|5[1-35-7]|6[1-8]|7[14]|8[16]|91)[2-9]"],"(0$1)"],["(\\d{5})(\\d{5})","$1 $2",["58"],"(0$1)"],["(\\d{3})(\\d{7})","$1 $2",["3"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["2[125]|4[0-246-9]|5[1-35-7]|6[1-8]|7[14]|8[16]|91"],"(0$1)"],["(\\d{3})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["[24-9]"],"(0$1)"]],"0"],PL:["48","00","(?:6|8\\d\\d)\\d{7}|[1-9]\\d{6}(?:\\d{2})?|[26]\\d{5}",[6,7,8,9,10],[["(\\d{5})","$1",["19"]],["(\\d{3})(\\d{3})","$1 $2",["11|20|64"]],["(\\d{2})(\\d{2})(\\d{3})","$1 $2 $3",["(?:1[2-8]|2[2-69]|3[2-4]|4[1-468]|5[24-689]|6[1-3578]|7[14-7]|8[1-79]|9[145])1","(?:1[2-8]|2[2-69]|3[2-4]|4[1-468]|5[24-689]|6[1-3578]|7[14-7]|8[1-79]|9[145])19"]],["(\\d{3})(\\d{2})(\\d{2,3})","$1 $2 $3",["64"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["21|39|45|5[0137]|6[0469]|7[02389]|8(?:0[14]|8)"]],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["1[2-8]|[2-7]|8[1-79]|9[145]"]],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["8"]]]],PM:["508","00","[45]\\d{5}|(?:708|8\\d\\d)\\d{6}",[6,9],[["(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3",["[45]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["7"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"],"0$1"]],"0"],PR:["1","011","(?:[589]\\d\\d|787)\\d{7}",[10],0,"1",0,0,0,0,"787|939"],PS:["970","00","[2489]2\\d{6}|(?:1\\d|5)\\d{8}",[8,9,10],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["[2489]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["5"],"0$1"],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1"]]],"0"],PT:["351","00","1693\\d{5}|(?:[26-9]\\d|30)\\d{7}",[9],[["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["2[12]"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["16|[236-9]"]]]],PW:["680","01[12]","(?:[24-8]\\d\\d|345|900)\\d{4}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[2-9]"]]]],PY:["595","00","59\\d{4,6}|9\\d{5,10}|(?:[2-46-8]\\d|5[0-8])\\d{4,7}",[6,7,8,9,10,11],[["(\\d{3})(\\d{3,6})","$1 $2",["[2-9]0"],"0$1"],["(\\d{2})(\\d{5})","$1 $2",["[26]1|3[289]|4[1246-8]|7[1-3]|8[1-36]"],"(0$1)"],["(\\d{3})(\\d{4,5})","$1 $2",["2[279]|3[13-5]|4[359]|5|6(?:[34]|7[1-46-8])|7[46-8]|85"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["2[14-68]|3[26-9]|4[1246-8]|6(?:1|75)|7[1-35]|8[1-36]"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["87"]],["(\\d{3})(\\d{6})","$1 $2",["9(?:[5-79]|8[1-7])"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[2-8]"],"0$1"],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["9"]]],"0"],QA:["974","00","800\\d{4}|(?:2|800)\\d{6}|(?:0080|[3-7])\\d{7}",[7,8,9,11],[["(\\d{3})(\\d{4})","$1 $2",["2[136]|8"]],["(\\d{4})(\\d{4})","$1 $2",["[3-7]"]]]],RE:["262","00","709\\d{6}|(?:26|[689]\\d)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[26-9]"],"0$1"]],"0",0,0,0,0,0,[["26(?:2\\d\\d|3(?:0\\d|1[0-6]))\\d{4}"],["(?:69(?:2\\d\\d|3(?:[06][0-6]|1[0-3]|2[0-2]|3[0-39]|4\\d|5[0-5]|7[0-37]|8[0-8]|9[0-479]))|7092[0-3])\\d{4}"],["80\\d{7}"],["89[1-37-9]\\d{6}"],0,0,0,0,["9(?:399[0-3]|479[0-6]|76(?:2[278]|3[0-37]))\\d{4}"],["8(?:1[019]|2[0156]|84|90)\\d{6}"]]],RO:["40","00","(?:[236-8]\\d|90)\\d{7}|[23]\\d{5}",[6,9],[["(\\d{3})(\\d{3})","$1 $2",["2[3-6]","2[3-6]\\d9"],"0$1"],["(\\d{2})(\\d{4})","$1 $2",["219|31"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[23]1"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[236-9]"],"0$1"]],"0",0,0,0,0,0,0,0," int "],RS:["381","00","38[02-9]\\d{6,9}|6\\d{7,9}|90\\d{4,8}|38\\d{5,6}|(?:7\\d\\d|800)\\d{3,9}|(?:[12]\\d|3[0-79])\\d{5,10}",[6,7,8,9,10,11,12],[["(\\d{3})(\\d{3,9})","$1 $2",["(?:2[389]|39)0|[7-9]"],"0$1"],["(\\d{2})(\\d{5,10})","$1 $2",["[1-36]"],"0$1"]],"0"],RU:["7","810","8\\d{13}|[347-9]\\d{9}",[10,14],[["(\\d{4})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["7(?:1[0-8]|2[1-9])","7(?:1(?:[0-356]2|4[29]|7|8[27])|2(?:1[23]|[2-9]2))","7(?:1(?:[0-356]2|4[29]|7|8[27])|2(?:13[03-69]|62[013-9]))|72[1-57-9]2"],"8 ($1)",1],["(\\d{5})(\\d)(\\d{2})(\\d{2})","$1 $2 $3 $4",["7(?:1[0-68]|2[1-9])","7(?:1(?:[06][3-6]|[18]|2[35]|[3-5][3-5])|2(?:[13][3-5]|[24-689]|7[457]))","7(?:1(?:0(?:[356]|4[023])|[18]|2(?:3[013-9]|5)|3[45]|43[013-79]|5(?:3[1-8]|4[1-7]|5)|6(?:3[0-35-9]|[4-6]))|2(?:1(?:3[178]|[45])|[24-689]|3[35]|7[457]))|7(?:14|23)4[0-8]|71(?:33|45)[1-79]"],"8 ($1)",1],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["7"],"8 ($1)",1],["(\\d{3})(\\d{3})(\\d{2})(\\d{2})","$1 $2-$3-$4",["[349]|8(?:[02-7]|1[1-8])"],"8 ($1)",1],["(\\d{4})(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3 $4",["8"],"8 ($1)"]],"8",0,0,0,0,0,[["336(?:[013-9]\\d|2[013-9])\\d{5}|(?:3(?:0[12]|4[1-35-79]|5[1-3]|65|8[1-58]|9[0145])|4(?:01|1[1356]|2[13467]|7[1-5]|8[1-7]|9[1-689])|8(?:1[1-8]|2[01]|3[13-6]|4[0-8]|5[15-7]|6[0-35-79]|7[1-37-9]))\\d{7}",[10]],["9\\d{9}",[10]],["8(?:0[04]|108\\d{3})\\d{7}"],["80[39]\\d{7}",[10]],["808\\d{7}",[10]]],"8~10"],RW:["250","00","(?:06|[27]\\d\\d|[89]00)\\d{6}",[8,9],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["0"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["2"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[7-9]"],"0$1"]],"0"],SA:["966","00","(?:[15]\\d|800|92)\\d{7}",[9,10],[["(\\d{4})(\\d{5})","$1 $2",["9"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["1"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["5"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["8"]]],"0"],SB:["677","0[01]","[6-9]\\d{6}|[1-6]\\d{4}",[5,7],[["(\\d{2})(\\d{5})","$1 $2",["6[89]|7|8[4-9]|9(?:[1-8]|9[0-8])"]]]],SC:["248","010|0[0-2]","(?:[2489]\\d|64)\\d{5}",[7],[["(\\d)(\\d{3})(\\d{3})","$1 $2 $3",["[246]|9[57]"]]],0,0,0,0,0,0,0,"00"],SD:["249","00","[19]\\d{8}",[9],[["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[19]"],"0$1"]],"0"],SE:["46","00","(?:[26]\\d\\d|9)\\d{9}|[1-9]\\d{8}|[1-689]\\d{7}|[1-4689]\\d{6}|2\\d{5}",[6,7,8,9,10,12],[["(\\d{2})(\\d{2,3})(\\d{2})","$1-$2 $3",["20"],"0$1",0,"$1 $2 $3"],["(\\d{3})(\\d{4})","$1-$2",["9(?:00|39|44|9)"],"0$1",0,"$1 $2"],["(\\d{2})(\\d{3})(\\d{2})","$1-$2 $3",["[12][136]|3[356]|4[0246]|6[03]|90[1-9]"],"0$1",0,"$1 $2 $3"],["(\\d)(\\d{2,3})(\\d{2})(\\d{2})","$1-$2 $3 $4",["8"],"0$1",0,"$1 $2 $3 $4"],["(\\d{3})(\\d{2,3})(\\d{2})","$1-$2 $3",["1[2457]|2(?:[247-9]|5[0138])|3[0247-9]|4[1357-9]|5[0-35-9]|6(?:[125689]|4[02-57]|7[0-2])|9(?:[125-8]|3[02-5]|4[0-3])"],"0$1",0,"$1 $2 $3"],["(\\d{3})(\\d{2,3})(\\d{3})","$1-$2 $3",["9(?:00|39|44)"],"0$1",0,"$1 $2 $3"],["(\\d{2})(\\d{2,3})(\\d{2})(\\d{2})","$1-$2 $3 $4",["1[13689]|2[0136]|3[1356]|4[0246]|54|6[03]|90[1-9]"],"0$1",0,"$1 $2 $3 $4"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1-$2 $3 $4",["10|7"],"0$1",0,"$1 $2 $3 $4"],["(\\d)(\\d{3})(\\d{3})(\\d{2})","$1-$2 $3 $4",["8"],"0$1",0,"$1 $2 $3 $4"],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1-$2 $3 $4",["[13-5]|2(?:[247-9]|5[0138])|6(?:[124-689]|7[0-2])|9(?:[125-8]|3[02-5]|4[0-3])"],"0$1",0,"$1 $2 $3 $4"],["(\\d{3})(\\d{2})(\\d{2})(\\d{3})","$1-$2 $3 $4",["9"],"0$1",0,"$1 $2 $3 $4"],["(\\d{3})(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1-$2 $3 $4 $5",["[26]"],"0$1",0,"$1 $2 $3 $4 $5"]],"0"],SG:["65","0[0-3]\\d","(?:(?:1\\d|8)\\d\\d|7000)\\d{7}|[3689]\\d{7}",[8,10,11],[["(\\d{4})(\\d{4})","$1 $2",["[369]|8(?:0[1-9]|[1-9])"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["8"]],["(\\d{4})(\\d{4})(\\d{3})","$1 $2 $3",["7"]],["(\\d{4})(\\d{3})(\\d{4})","$1 $2 $3",["1"]]]],SH:["290","00","(?:[256]\\d|8)\\d{3}",[4,5],0,0,0,0,0,0,"[256]"],SI:["386","00|10(?:22|66|88|99)","[1-7]\\d{7}|8\\d{4,7}|90\\d{4,6}",[5,6,7,8],[["(\\d{2})(\\d{3,6})","$1 $2",["8[09]|9"],"0$1"],["(\\d{3})(\\d{5})","$1 $2",["59|8"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[37][01]|4[0139]|51|6"],"0$1"],["(\\d)(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[1-57]"],"(0$1)"]],"0",0,0,0,0,0,0,"00"],SJ:["47","00","0\\d{4}|(?:[489]\\d|79)\\d{6}",[5,8],0,0,0,0,0,0,"79"],SK:["421","00","[2-689]\\d{8}|[2-59]\\d{6}|[2-5]\\d{5}",[6,7,9],[["(\\d)(\\d{2})(\\d{3,4})","$1 $2 $3",["21"],"0$1"],["(\\d{2})(\\d{2})(\\d{2,3})","$1 $2 $3",["[3-5][1-8]1","[3-5][1-8]1[67]"],"0$1"],["(\\d)(\\d{3})(\\d{3})(\\d{2})","$1/$2 $3 $4",["2"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[689]"],"0$1"],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1/$2 $3 $4",["[3-5]"],"0$1"]],"0"],SL:["232","00","(?:[237-9]\\d|66)\\d{6}",[8],[["(\\d{2})(\\d{6})","$1 $2",["[236-9]"],"(0$1)"]],"0"],SM:["378","00","(?:0549|[5-7]\\d)\\d{6}",[8,10],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[5-7]"]],["(\\d{4})(\\d{6})","$1 $2",["0"]]],0,0,"([89]\\d{5})$","0549$1"],SN:["221","00","(?:[378]\\d|93)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"]],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[379]"]]]],SO:["252","00","[346-9]\\d{8}|[12679]\\d{7}|[1-5]\\d{6}|[1348]\\d{5}",[6,7,8,9],[["(\\d{2})(\\d{4})","$1 $2",["8[125]"]],["(\\d{6})","$1",["[134]"]],["(\\d)(\\d{6})","$1 $2",["[15]|2[0-79]|3[0-46-8]|4[0-7]"]],["(\\d)(\\d{7})","$1 $2",["(?:2|90)4|[67]"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[348]|64|79|90"]],["(\\d{2})(\\d{5,7})","$1 $2",["1|28|6[0-35-9]|7[67]|9[2-9]"]]],"0"],SR:["597","00","(?:[2-5]|[6-8]\\d|90)\\d{5}",[6,7],[["(\\d{2})(\\d{2})(\\d{2})","$1-$2-$3",["56"]],["(\\d{3})(\\d{3})","$1-$2",["[2-5]"]],["(\\d{3})(\\d{4})","$1-$2",["[6-9]"]]]],SS:["211","00","[19]\\d{8}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[19]"],"0$1"]],"0"],ST:["239","00","(?:22|9\\d)\\d{5}",[7],[["(\\d{3})(\\d{4})","$1 $2",["[29]"]]]],SV:["503","00","[25-7]\\d{7}|(?:80\\d|900)\\d{4}(?:\\d{4})?",[7,8,11],[["(\\d{3})(\\d{4})","$1 $2",["[89]"]],["(\\d{4})(\\d{4})","$1 $2",["[25-7]"]],["(\\d{3})(\\d{4})(\\d{4})","$1 $2 $3",["[89]"]]]],SX:["1","011","7215\\d{6}|(?:[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"(5\\d{6})$|1","721$1",0,"721"],SY:["963","00","[1-359]\\d{8}|[1-5]\\d{7}",[8,9],[["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[1-4]|5[1-3]"],"0$1",1],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[59]"],"0$1",1]],"0"],SZ:["268","00","0800\\d{4}|(?:[237]\\d|900)\\d{6}",[8,9],[["(\\d{4})(\\d{4})","$1 $2",["[0237]"]],["(\\d{5})(\\d{4})","$1 $2",["9"]]]],TA:["290","00","8\\d{3}",[4],0,0,0,0,0,0,"8"],TC:["1","011","(?:[58]\\d\\d|649|900)\\d{7}",[10],0,"1",0,"([2-479]\\d{6})$|1","649$1",0,"649"],TD:["235","00|16","(?:22|30|[689]\\d|77)\\d{6}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[236-9]"]]],0,0,0,0,0,0,0,"00"],TG:["228","00","[279]\\d{7}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[279]"]]]],TH:["66","00[1-9]","(?:001800|[2-57]|[689]\\d)\\d{7}|1\\d{7,9}",[8,9,10,13],[["(\\d)(\\d{3})(\\d{4})","$1 $2 $3",["2"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[13-9]"],"0$1"],["(\\d{4})(\\d{3})(\\d{3})","$1 $2 $3",["1"]]],"0"],TJ:["992","810","(?:[0-57-9]\\d|66)\\d{7}",[9],[["(\\d{6})(\\d)(\\d{2})","$1 $2 $3",["331","3317"]],["(\\d{3})(\\d{2})(\\d{4})","$1 $2 $3",["44[02-479]|[34]7"]],["(\\d{4})(\\d)(\\d{4})","$1 $2 $3",["3(?:[1245]|3[12])"]],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["\\d"]]],0,0,0,0,0,0,0,"8~10"],TK:["690","00","[2-47]\\d{3,6}",[4,5,6,7]],TL:["670","00","7\\d{7}|(?:[2-47]\\d|[89]0)\\d{5}",[7,8],[["(\\d{3})(\\d{4})","$1 $2",["[2-489]|70"]],["(\\d{4})(\\d{4})","$1 $2",["7"]]]],TM:["993","810","(?:[1-6]\\d|71)\\d{6}",[8],[["(\\d{2})(\\d{2})(\\d{2})(\\d{2})","$1 $2-$3-$4",["12"],"(8 $1)"],["(\\d{3})(\\d)(\\d{2})(\\d{2})","$1 $2-$3-$4",["[1-5]"],"(8 $1)"],["(\\d{2})(\\d{6})","$1 $2",["[67]"],"8 $1"]],"8",0,0,0,0,0,0,"8~10"],TN:["216","00","[2-57-9]\\d{7}",[8],[["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[2-57-9]"]]]],TO:["676","00","(?:0800|(?:[5-8]\\d\\d|999)\\d)\\d{3}|[2-8]\\d{4}",[5,7],[["(\\d{2})(\\d{3})","$1-$2",["[2-4]|50|6[09]|7[0-24-69]|8[05]"]],["(\\d{4})(\\d{3})","$1 $2",["0"]],["(\\d{3})(\\d{4})","$1 $2",["[5-9]"]]]],TR:["90","00","4\\d{6}|8\\d{11,12}|(?:[2-58]\\d\\d|900)\\d{7}",[7,10,12,13],[["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["512|8[01589]|90"],"0$1",1],["(\\d{3})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["5(?:[0-59]|61)","5(?:[0-59]|61[06])","5(?:[0-59]|61[06]1)"],"0$1",1],["(\\d{3})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[24][1-8]|3[1-9]"],"(0$1)",1],["(\\d{3})(\\d{3})(\\d{6,7})","$1 $2 $3",["80"],"0$1",1]],"0"],TT:["1","011","(?:[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-46-8]\\d{6})$|1","868$1",0,"868"],TV:["688","00","(?:2|7\\d\\d|90)\\d{4}",[5,6,7],[["(\\d{2})(\\d{3})","$1 $2",["2"]],["(\\d{2})(\\d{4})","$1 $2",["90"]],["(\\d{2})(\\d{5})","$1 $2",["7"]]]],TW:["886","0(?:0[25-79]|19)","[2-689]\\d{8}|7\\d{9,10}|[2-8]\\d{7}|2\\d{6}",[7,8,9,10,11],[["(\\d{2})(\\d)(\\d{4})","$1 $2 $3",["202"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["[258]0"],"0$1"],["(\\d)(\\d{3,4})(\\d{4})","$1 $2 $3",["[23568]|4(?:0[02-48]|[1-47-9])|7[1-9]","[23568]|4(?:0[2-48]|[1-47-9])|(?:400|7)[1-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[49]"],"0$1"],["(\\d{2})(\\d{4})(\\d{4,5})","$1 $2 $3",["7"],"0$1"]],"0",0,0,0,0,0,0,0,"#"],TZ:["255","00[056]","(?:[25-8]\\d|41|90)\\d{7}",[9],[["(\\d{3})(\\d{2})(\\d{4})","$1 $2 $3",["[89]"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[24]"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["5"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[67]"],"0$1"]],"0"],UA:["380","00","[89]\\d{9}|[3-9]\\d{8}",[9,10],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["6[12][29]|(?:3[1-8]|4[136-8]|5[12457]|6[49])2|(?:56|65)[24]","6[12][29]|(?:35|4[1378]|5[12457]|6[49])2|(?:56|65)[24]|(?:3[1-46-8]|46)2[013-9]"],"0$1"],["(\\d{4})(\\d{5})","$1 $2",["3[1-8]|4(?:[1367]|[45][6-9]|8[4-6])|5(?:[1-5]|6[0135689]|7[4-6])|6(?:[12][3-7]|[459])","3[1-8]|4(?:[1367]|[45][6-9]|8[4-6])|5(?:[1-5]|6(?:[015689]|3[02389])|7[4-6])|6(?:[12][3-7]|[459])"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[3-7]|89|9[1-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["[89]"],"0$1"]],"0",0,0,0,0,0,0,"0~0"],UG:["256","00[057]","800\\d{6}|(?:[29]0|[347]\\d)\\d{7}",[9],[["(\\d{4})(\\d{5})","$1 $2",["202","2024"],"0$1"],["(\\d{3})(\\d{6})","$1 $2",["[27-9]|4(?:6[45]|[7-9])"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["[34]"],"0$1"]],"0"],US:["1","011","[2-9]\\d{9}|3\\d{6}",[10],[["(\\d{3})(\\d{4})","$1-$2",["310"],0,1],["(\\d{3})(\\d{3})(\\d{4})","($1) $2-$3",["[2-9]"],0,1,"$1-$2-$3"]],"1",0,0,0,0,0,[["3052(?:0[0-8]|[1-9]\\d)\\d{4}|(?:2742|305[3-9])\\d{6}|(?:472|983)[2-47-9]\\d{6}|(?:2(?:0[1-35-9]|1[02-9]|2[03-57-9]|3[1459]|4[08]|5[1-46]|6[0279]|7[0269]|8[13])|3(?:0[1-47-9]|1[02-9]|2[013-79]|3[0-24679]|4[167]|5[0-2]|6[01349]|8[056])|4(?:0[124-9]|1[02-579]|2[3-5]|3[0245]|4[023578]|58|6[349]|7[0589]|8[04])|5(?:0[1-57-9]|1[0235-8]|20|3[0149]|4[01]|5[179]|6[1-47]|7[0-5]|8[0256])|6(?:0[1-35-9]|1[024-9]|2[03689]|3[016]|4[0156]|5[01679]|6[0-279]|78|8[0-269])|7(?:0[1-46-8]|1[2-9]|2[04-8]|3[0-247]|4[0378]|5[47]|6[02359]|7[0-59]|8[156])|8(?:0[1-68]|1[02-8]|2[0168]|3[0-2589]|4[03578]|5[046-9]|6[02-5]|7[028])|9(?:0[1346-9]|1[02-9]|2[0589]|3[0146-8]|4[01357-9]|5[12469]|7[0-3589]|8[04-69]))[2-9]\\d{6}"],[""],["8(?:00|33|44|55|66|77|88)[2-9]\\d{6}"],["900[2-9]\\d{6}"],["52(?:3(?:[2-46-9][02-9]\\d|5(?:[02-46-9]\\d|5[0-46-9]))|4(?:[2-478][02-9]\\d|5(?:[034]\\d|2[024-9]|5[0-46-9])|6(?:0[1-9]|[2-9]\\d)|9(?:[05-9]\\d|2[0-5]|49)))\\d{4}|52[34][2-9]1[02-9]\\d{4}|5(?:00|2[125-9]|33|44|66|77|88)[2-9]\\d{6}"],0,0,0,["305209\\d{4}"]]],UY:["598","0(?:0|1[3-9]\\d)","0004\\d{2,9}|[1249]\\d{7}|2\\d{3,4}|(?:[49]\\d|80)\\d{5}",[4,5,6,7,8,9,10,11,12,13],[["(\\d{4,5})","$1",["21"]],["(\\d{3})(\\d{3,4})","$1 $2",["0"]],["(\\d{3})(\\d{4})","$1 $2",["[49]0|8"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["9"],"0$1"],["(\\d{4})(\\d{4})","$1 $2",["[124]"]],["(\\d{3})(\\d{3})(\\d{2,4})","$1 $2 $3",["0"]],["(\\d{3})(\\d{3})(\\d{3})(\\d{2,4})","$1 $2 $3 $4",["0"]]],"0",0,0,0,0,0,0,"00"," int. "],UZ:["998","00","(?:20|33|[5-9]\\d)\\d{7}",[9],[["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["[235-9]"]]]],VA:["39","00","0\\d{5,10}|3[0-8]\\d{7,10}|55\\d{8}|8\\d{5}(?:\\d{2,4})?|(?:1\\d|39)\\d{7,8}",[6,7,8,9,10,11,12],0,0,0,0,0,0,"06698"],VC:["1","011","(?:[58]\\d\\d|784|900)\\d{7}",[10],0,"1",0,"([2-7]\\d{6})$|1","784$1",0,"784"],VE:["58","00","[68]00\\d{7}|(?:[24]\\d|[59]0)\\d{8}",[10],[["(\\d{3})(\\d{7})","$1-$2",["[24-689]"],"0$1"]],"0"],VG:["1","011","(?:284|[58]\\d\\d|900)\\d{7}",[10],0,"1",0,"([2-578]\\d{6})$|1","284$1",0,"284"],VI:["1","011","[58]\\d{9}|(?:34|90)0\\d{7}",[10],0,"1",0,"([2-9]\\d{6})$|1","340$1",0,"340"],VN:["84","00","[12]\\d{9}|[135-9]\\d{8}|[16]\\d{7}|[16-8]\\d{6}",[7,8,9,10],[["(\\d{2})(\\d{5})","$1 $2",["80"],"0$1",1],["(\\d{4})(\\d{4,6})","$1 $2",["1"],0,1],["(\\d{2})(\\d{3})(\\d{2})(\\d{2})","$1 $2 $3 $4",["6"],"0$1",1],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[357-9]"],"0$1",1],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["2[48]"],"0$1",1],["(\\d{3})(\\d{4})(\\d{3})","$1 $2 $3",["2"],"0$1",1]],"0"],VU:["678","00","[57-9]\\d{6}|(?:[238]\\d|48)\\d{3}",[5,7],[["(\\d{3})(\\d{4})","$1 $2",["[57-9]"]]]],WF:["681","00","(?:40|72|8\\d{4})\\d{4}|[89]\\d{5}",[6,9],[["(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3",["[47-9]"]],["(\\d{3})(\\d{2})(\\d{2})(\\d{2})","$1 $2 $3 $4",["8"]]]],WS:["685","0","(?:[2-6]|8\\d{5})\\d{4}|[78]\\d{6}|[68]\\d{5}",[5,6,7,10],[["(\\d{5})","$1",["[2-5]|6[1-9]"]],["(\\d{3})(\\d{3,7})","$1 $2",["[68]"]],["(\\d{2})(\\d{5})","$1 $2",["7"]]]],XK:["383","00","2\\d{7,8}|3\\d{7,11}|(?:4\\d\\d|[89]00)\\d{5}",[8,9,10,11,12],[["(\\d{3})(\\d{5})","$1 $2",["[89]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3})","$1 $2 $3",["[2-4]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["2|39"],"0$1"],["(\\d{2})(\\d{7,10})","$1 $2",["3"],"0$1"]],"0"],YE:["967","00","(?:1|7\\d)\\d{7}|[1-7]\\d{6}",[7,8,9],[["(\\d)(\\d{3})(\\d{3,4})","$1 $2 $3",["[1-6]|7(?:[24-6]|8[0-7])"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["7"],"0$1"]],"0"],YT:["262","00","7093\\d{5}|(?:80|9\\d)\\d{7}|(?:26|63)9\\d{6}",[9],0,"0",0,0,0,0,0,[["269(?:0[0-467]|15|5[0-4]|6\\d|[78]0)\\d{4}"],["(?:639(?:0[0-79]|1[019]|[267]\\d|3[09]|40|5[05-9]|9[04-79])|7093[5-7])\\d{4}"],["80\\d{7}"],0,0,0,0,0,["9(?:(?:39|47)8[01]|769\\d)\\d{4}"]]],ZA:["27","00","[1-79]\\d{8}|8\\d{4,9}",[5,6,7,8,9,10],[["(\\d{2})(\\d{3,4})","$1 $2",["8[1-4]"],"0$1"],["(\\d{2})(\\d{3})(\\d{2,3})","$1 $2 $3",["8[1-4]"],"0$1"],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["860"],"0$1"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["[1-9]"],"0$1"],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["8"],"0$1"]],"0"],ZM:["260","00","800\\d{6}|(?:21|[579]\\d|63)\\d{7}",[9],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[28]"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["[579]"],"0$1"]],"0"],ZW:["263","00","2(?:[0-57-9]\\d{6,8}|6[0-24-9]\\d{6,7})|[38]\\d{9}|[35-8]\\d{8}|[3-6]\\d{7}|[1-689]\\d{6}|[1-3569]\\d{5}|[1356]\\d{4}",[5,6,7,8,9,10],[["(\\d{3})(\\d{3,5})","$1 $2",["2(?:0[45]|2[278]|[49]8)|3(?:[09]8|17)|6(?:[29]8|37|75)|[23][78]|(?:33|5[15]|6[68])[78]"],"0$1"],["(\\d)(\\d{3})(\\d{2,4})","$1 $2 $3",["[49]"],"0$1"],["(\\d{3})(\\d{4})","$1 $2",["80"],"0$1"],["(\\d{2})(\\d{7})","$1 $2",["24|8[13-59]|(?:2[05-79]|39|5[45]|6[15-8])2","2(?:02[014]|4|[56]20|[79]2)|392|5(?:42|525)|6(?:[16-8]21|52[013])|8[13-59]"],"(0$1)"],["(\\d{2})(\\d{3})(\\d{4})","$1 $2 $3",["7"],"0$1"],["(\\d{3})(\\d{3})(\\d{3,4})","$1 $2 $3",["2(?:1[39]|2[0157]|[378]|[56][14])|3(?:12|29)","2(?:1[39]|2[0157]|[378]|[56][14])|3(?:123|29)"],"0$1"],["(\\d{4})(\\d{6})","$1 $2",["8"],"0$1"],["(\\d{2})(\\d{3,5})","$1 $2",["1|2(?:0[0-36-9]|12|29|[56])|3(?:1[0-689]|[24-6])|5(?:[0236-9]|1[2-4])|6(?:[013-59]|7[0-46-9])|(?:33|55|6[68])[0-69]|(?:29|3[09]|62)[0-79]"],"0$1"],["(\\d{2})(\\d{3})(\\d{3,4})","$1 $2 $3",["29[013-9]|39|54"],"0$1"],["(\\d{4})(\\d{3,5})","$1 $2",["(?:25|54)8","258|5483"],"0$1"]],"0"]},nonGeographic:{800:["800",0,"(?:00|[1-9]\\d)\\d{6}",[8],[["(\\d{4})(\\d{4})","$1 $2",["\\d"]]],0,0,0,0,0,0,[0,0,["(?:00|[1-9]\\d)\\d{6}"]]],808:["808",0,"[1-9]\\d{7}",[8],[["(\\d{4})(\\d{4})","$1 $2",["[1-9]"]]],0,0,0,0,0,0,[0,0,0,0,0,0,0,0,0,["[1-9]\\d{7}"]]],870:["870",0,"7\\d{11}|[235-7]\\d{8}",[9,12],[["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["[235-7]"]]],0,0,0,0,0,0,[0,["(?:[356]|774[45])\\d{8}|7[6-8]\\d{7}"],0,0,0,0,0,0,["2\\d{8}",[9]]]],878:["878",0,"10\\d{10}",[12],[["(\\d{2})(\\d{5})(\\d{5})","$1 $2 $3",["1"]]],0,0,0,0,0,0,[0,0,0,0,0,0,0,0,["10\\d{10}"]]],881:["881",0,"6\\d{9}|[0-36-9]\\d{8}",[9,10],[["(\\d)(\\d{3})(\\d{5})","$1 $2 $3",["[0-37-9]"]],["(\\d)(\\d{3})(\\d{5,6})","$1 $2 $3",["6"]]],0,0,0,0,0,0,[0,["6\\d{9}|[0-36-9]\\d{8}"]]],882:["882",0,"[13]\\d{6}(?:\\d{2,5})?|[19]\\d{7}|(?:[25]\\d\\d|4)\\d{7}(?:\\d{2})?",[7,8,9,10,11,12],[["(\\d{2})(\\d{5})","$1 $2",["16|342"]],["(\\d{2})(\\d{6})","$1 $2",["49"]],["(\\d{2})(\\d{2})(\\d{4})","$1 $2 $3",["1[36]|9"]],["(\\d{2})(\\d{4})(\\d{3})","$1 $2 $3",["3[23]"]],["(\\d{2})(\\d{3,4})(\\d{4})","$1 $2 $3",["16"]],["(\\d{2})(\\d{4})(\\d{4})","$1 $2 $3",["10|23|3(?:[15]|4[57])|4|51"]],["(\\d{3})(\\d{4})(\\d{4})","$1 $2 $3",["34"]],["(\\d{2})(\\d{4,5})(\\d{5})","$1 $2 $3",["[1-35]"]]],0,0,0,0,0,0,[0,["342\\d{4}|(?:337|49)\\d{6}|(?:3(?:2|47|7\\d{3})|50\\d{3})\\d{7}",[7,8,9,10,12]],0,0,0,["348[57]\\d{7}",[11]],0,0,["1(?:3(?:0[0347]|[13][0139]|2[035]|4[013568]|6[0459]|7[06]|8[15-8]|9[0689])\\d{4}|6\\d{5,10})|(?:345\\d|9[89])\\d{6}|(?:10|2(?:3|85\\d)|3(?:[15]|[69]\\d\\d)|4[15-8]|51)\\d{8}"]]],883:["883",0,"(?:[1-4]\\d|51)\\d{6,10}",[8,9,10,11,12],[["(\\d{3})(\\d{3})(\\d{2,8})","$1 $2 $3",["[14]|2[24-689]|3[02-689]|51[24-9]"]],["(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3",["510"]],["(\\d{3})(\\d{3})(\\d{4})","$1 $2 $3",["21"]],["(\\d{4})(\\d{4})(\\d{4})","$1 $2 $3",["51[13]"]],["(\\d{3})(\\d{3})(\\d{3})(\\d{3})","$1 $2 $3 $4",["[235]"]]],0,0,0,0,0,0,[0,0,0,0,0,0,0,0,["(?:2(?:00\\d\\d|10)|(?:370[1-9]|51\\d0)\\d)\\d{7}|51(?:00\\d{5}|[24-9]0\\d{4,7})|(?:1[0-79]|2[24-689]|3[02-689]|4[0-4])0\\d{5,9}"]]],888:["888",0,"\\d{11}",[11],[["(\\d{3})(\\d{3})(\\d{5})","$1 $2 $3"]],0,0,0,0,0,0,[0,0,0,0,0,0,["\\d{11}"]]],979:["979",0,"[1359]\\d{8}",[9],[["(\\d)(\\d{4})(\\d{4})","$1 $2 $3",["[1359]"]]],0,0,0,0,0,0,[0,0,0,["[1359]\\d{8}"]]]}};function m5(t,e){var n=Array.prototype.slice.call(e);return n.push(g5),t.apply(this,n)}function Fg(t,e){t=t.split("-"),e=e.split("-");for(var n=t[0].split("."),r=e[0].split("."),i=0;i<3;i++){var s=Number(n[i]),a=Number(r[i]);if(s>a)return 1;if(a>s)return-1;if(!isNaN(s)&&isNaN(a))return 1;if(isNaN(s)&&!isNaN(a))return-1}return t[1]&&e[1]?t[1]>e[1]?1:t[1]<e[1]?-1:0:!t[1]&&e[1]?1:t[1]&&!e[1]?-1:0}var _5={}.constructor;function Kr(t){return t!=null&&t.constructor===_5}function li(t){"@babel/helpers - typeof";return li=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},li(t)}function el(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function y5(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,w5(r.key),r)}}function tl(t,e,n){return e&&y5(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function w5(t){var e=b5(t,"string");return li(e)=="symbol"?e:e+""}function b5(t,e){if(li(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(li(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}var v5="1.2.0",$5="1.7.35",Hg=" ext. ",k5=/^\d+$/,Je=(function(){function t(e){el(this,t),C1(e),this.metadata=e,N1.call(this,e)}return tl(t,[{key:"getCountries",value:function(){return Object.keys(this.metadata.countries).filter(function(n){return n!=="001"})}},{key:"getCountryMetadata",value:function(n){return this.metadata.countries[n]}},{key:"nonGeographic",value:function(){if(!(this.v1||this.v2||this.v3))return this.metadata.nonGeographic||this.metadata.nonGeographical}},{key:"hasCountry",value:function(n){return this.getCountryMetadata(n)!==void 0}},{key:"hasCallingCode",value:function(n){if(this.getCountryCodesForCallingCode(n))return!0;if(this.nonGeographic()){if(this.nonGeographic()[n])return!0}else{var r=this.countryCallingCodes()[n];if(r&&r.length===1&&r[0]==="001")return!0}}},{key:"isNonGeographicCallingCode",value:function(n){return this.nonGeographic()?!!this.nonGeographic()[n]:!this.getCountryCodesForCallingCode(n)}},{key:"country",value:function(n){return this.selectNumberingPlan(n)}},{key:"selectNumberingPlan",value:function(n,r){if(n&&k5.test(n)&&(r=n,n=null),n&&n!=="001"){if(!this.hasCountry(n))throw new Error("Unknown country: ".concat(n));this.numberingPlan=new Vg(this.getCountryMetadata(n),this)}else if(r){if(!this.hasCallingCode(r))throw new Error("Unknown calling code: ".concat(r));this.numberingPlan=new Vg(this.getNumberingPlanMetadata(r),this)}else this.numberingPlan=void 0;return this}},{key:"getCountryCodesForCallingCode",value:function(n){var r=this.countryCallingCodes()[n];if(r)return r.length===1&&r[0].length===3?void 0:r}},{key:"getCountryCodeForCallingCode",value:function(n){var r=this.getCountryCodesForCallingCode(n);if(r)return r[0]}},{key:"getNumberingPlanMetadata",value:function(n){var r=this.getCountryCodeForCallingCode(n);if(r)return this.getCountryMetadata(r);if(this.nonGeographic()){var i=this.nonGeographic()[n];if(i)return i}else{var s=this.countryCallingCodes()[n];if(s&&s.length===1&&s[0]==="001")return this.metadata.countries["001"]}}},{key:"countryCallingCode",value:function(){return this.numberingPlan.callingCode()}},{key:"IDDPrefix",value:function(){return this.numberingPlan.IDDPrefix()}},{key:"defaultIDDPrefix",value:function(){return this.numberingPlan.defaultIDDPrefix()}},{key:"nationalNumberPattern",value:function(){return this.numberingPlan.nationalNumberPattern()}},{key:"possibleLengths",value:function(){return this.numberingPlan.possibleLengths()}},{key:"formats",value:function(){return this.numberingPlan.formats()}},{key:"nationalPrefixForParsing",value:function(){return this.numberingPlan.nationalPrefixForParsing()}},{key:"nationalPrefixTransformRule",value:function(){return this.numberingPlan.nationalPrefixTransformRule()}},{key:"leadingDigits",value:function(){return this.numberingPlan.leadingDigits()}},{key:"hasTypes",value:function(){return this.numberingPlan.hasTypes()}},{key:"type",value:function(n){return this.numberingPlan.type(n)}},{key:"ext",value:function(){return this.numberingPlan.ext()}},{key:"countryCallingCodes",value:function(){return this.v1?this.metadata.country_phone_code_to_countries:this.metadata.country_calling_codes}},{key:"chooseCountryByCountryCallingCode",value:function(n){return this.selectNumberingPlan(n)}},{key:"hasSelectedNumberingPlan",value:function(){return this.numberingPlan!==void 0}}])})(),Vg=(function(){function t(e,n){el(this,t),this.globalMetadataObject=n,this.metadata=e,N1.call(this,n.metadata)}return tl(t,[{key:"callingCode",value:function(){return this.metadata[0]}},{key:"getDefaultCountryMetadataForRegion",value:function(){return this.globalMetadataObject.getNumberingPlanMetadata(this.callingCode())}},{key:"IDDPrefix",value:function(){if(!(this.v1||this.v2))return this.metadata[1]}},{key:"defaultIDDPrefix",value:function(){if(!(this.v1||this.v2))return this.metadata[12]}},{key:"nationalNumberPattern",value:function(){return this.v1||this.v2?this.metadata[1]:this.metadata[2]}},{key:"possibleLengths",value:function(){if(!this.v1)return this.metadata[this.v2?2:3]}},{key:"_getFormats",value:function(n){return n[this.v1?2:this.v2?3:4]}},{key:"formats",value:function(){var n=this,r=this._getFormats(this.metadata)||this._getFormats(this.getDefaultCountryMetadataForRegion())||[];return r.map(function(i){return new x5(i,n)})}},{key:"nationalPrefix",value:function(){return this.metadata[this.v1?3:this.v2?4:5]}},{key:"_getNationalPrefixFormattingRule",value:function(n){return n[this.v1?4:this.v2?5:6]}},{key:"nationalPrefixFormattingRule",value:function(){return this._getNationalPrefixFormattingRule(this.metadata)||this._getNationalPrefixFormattingRule(this.getDefaultCountryMetadataForRegion())}},{key:"_nationalPrefixForParsing",value:function(){return this.metadata[this.v1?5:this.v2?6:7]}},{key:"nationalPrefixForParsing",value:function(){return this._nationalPrefixForParsing()||this.nationalPrefix()}},{key:"nationalPrefixTransformRule",value:function(){return this.metadata[this.v1?6:this.v2?7:8]}},{key:"_getNationalPrefixIsOptionalWhenFormatting",value:function(){return!!this.metadata[this.v1?7:this.v2?8:9]}},{key:"nationalPrefixIsOptionalWhenFormattingInNationalFormat",value:function(){return this._getNationalPrefixIsOptionalWhenFormatting(this.metadata)||this._getNationalPrefixIsOptionalWhenFormatting(this.getDefaultCountryMetadataForRegion())}},{key:"leadingDigits",value:function(){return this.metadata[this.v1?8:this.v2?9:10]}},{key:"types",value:function(){return this.metadata[this.v1?9:this.v2?10:11]}},{key:"hasTypes",value:function(){return this.types()&&this.types().length===0?!1:!!this.types()}},{key:"type",value:function(n){if(this.hasTypes()&&Kg(this.types(),n))return new z5(Kg(this.types(),n),this)}},{key:"ext",value:function(){return this.v1||this.v2?Hg:this.metadata[13]||Hg}}])})(),x5=(function(){function t(e,n){el(this,t),this._format=e,this.metadata=n}return tl(t,[{key:"pattern",value:function(){return this._format[0]}},{key:"format",value:function(){return this._format[1]}},{key:"leadingDigitsPatterns",value:function(){return this._format[2]||[]}},{key:"nationalPrefixFormattingRule",value:function(){return this._format[3]||this.metadata.nationalPrefixFormattingRule()}},{key:"nationalPrefixIsOptionalWhenFormattingInNationalFormat",value:function(){return!!this._format[4]||this.metadata.nationalPrefixIsOptionalWhenFormattingInNationalFormat()}},{key:"nationalPrefixIsMandatoryWhenFormattingInNationalFormat",value:function(){return this.usesNationalPrefix()&&!this.nationalPrefixIsOptionalWhenFormattingInNationalFormat()}},{key:"usesNationalPrefix",value:function(){return!!(this.nationalPrefixFormattingRule()&&!S5.test(this.nationalPrefixFormattingRule()))}},{key:"internationalFormat",value:function(){return this._format[5]||this.format()}}])})(),S5=/^\(?\$1\)?$/,z5=(function(){function t(e,n){el(this,t),this.type=e,this.metadata=n}return tl(t,[{key:"pattern",value:function(){return this.metadata.v1?this.type:this.type[0]}},{key:"possibleLengths",value:function(){if(!this.metadata.v1)return this.type[1]||this.metadata.possibleLengths()}}])})();function Kg(t,e){switch(e){case"FIXED_LINE":return t[0];case"MOBILE":return t[1];case"TOLL_FREE":return t[2];case"PREMIUM_RATE":return t[3];case"PERSONAL_NUMBER":return t[4];case"VOICEMAIL":return t[5];case"UAN":return t[6];case"PAGER":return t[7];case"VOIP":return t[8];case"SHARED_COST":return t[9]}}function C1(t){if(!t)throw new Error("[libphonenumber-js] `metadata` argument not passed. Check your arguments.");if(!Kr(t)||!Kr(t.countries))throw new Error("[libphonenumber-js] `metadata` argument was passed but it's not a valid metadata. Must be an object having `.countries` child object property. Got ".concat(Kr(t)?"an object of shape: { "+Object.keys(t).join(", ")+" }":"a "+A5(t)+": "+t,"."))}var A5=function(e){return li(e)};function Rp(t,e){if(e=new Je(e),e.hasCountry(t))return e.selectNumberingPlan(t).countryCallingCode();throw new Error("Unknown country: ".concat(t))}function E5(t,e){return e.countries.hasOwnProperty(t)}function N1(t){var e=t.version;typeof e=="number"?(this.v1=e===1,this.v2=e===2,this.v3=e===3,this.v4=e===4):e?Fg(e,v5)===-1?this.v2=!0:Fg(e,$5)===-1?this.v3=!0:this.v4=!0:this.v1=!0}function Bp(t,e,n){return C5(t,e,void 0,n)}function C5(t,e,n,r){e&&(r=new Je(r.metadata),r.selectNumberingPlan(e));var i=r.type(n),s=i&&i.possibleLengths()||r.possibleLengths();if(!s)return"IS_POSSIBLE";var a=t.length,c=s[0];return c===a?"IS_POSSIBLE":c>a?"TOO_SHORT":s[s.length-1]<a?"TOO_LONG":s.indexOf(a,1)>=0?"IS_POSSIBLE":"INVALID_LENGTH"}function N5(t,e,n){if(e===void 0&&(e={}),n=new Je(n),e.v2){if(!t.countryCallingCode)throw new Error("Invalid phone number object passed");n.selectNumberingPlan(t.countryCallingCode)}else{if(!t.phone)return!1;if(t.country){if(!n.hasCountry(t.country))throw new Error("Unknown country: ".concat(t.country));n.selectNumberingPlan(t.country)}else{if(!t.countryCallingCode)throw new Error("Invalid phone number object passed");n.selectNumberingPlan(t.countryCallingCode)}}if(n.possibleLengths())return I1(t.phone||t.nationalNumber,t.country,n);if(t.countryCallingCode&&n.isNonGeographicCallingCode(t.countryCallingCode))return!0;throw new Error('Missing "possibleLengths" in metadata. Perhaps the metadata has been generated before v1.0.18.')}function I1(t,e,n){return Bp(t,e,n)==="IS_POSSIBLE"}function _n(t,e){return t=t||"",new RegExp("^(?:"+e+")$").test(t)}function I5(t,e){var n=typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=j5(t))||e){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
83
83
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function j5(t,e){if(t){if(typeof t=="string")return Gg(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Gg(t,e):void 0}}function Gg(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}var P5=["MOBILE","PREMIUM_RATE","TOLL_FREE","SHARED_COST","VOIP","PERSONAL_NUMBER","PAGER","UAN","VOICEMAIL"];function Lp(t,e,n){if(e=e||{},!(!t.country&&!t.countryCallingCode)){n=new Je(n),n.selectNumberingPlan(t.country,t.countryCallingCode);var r=e.v2?t.nationalNumber:t.phone;if(_n(r,n.nationalNumberPattern())){if(zl(r,"FIXED_LINE",n))return n.type("MOBILE")&&n.type("MOBILE").pattern()===""||!n.type("MOBILE")||zl(r,"MOBILE",n)?"FIXED_LINE_OR_MOBILE":"FIXED_LINE";for(var i=I5(P5),s;!(s=i()).done;){var a=s.value;if(zl(r,a,n))return a}}}}function zl(t,e,n){return e=n.type(e),!e||!e.pattern()||e.possibleLengths()&&e.possibleLengths().indexOf(t.length)<0?!1:_n(t,e.pattern())}function O5(t,e,n){if(e=e||{},n=new Je(n),n.selectNumberingPlan(t.country,t.countryCallingCode),n.hasTypes())return Lp(t,e,n.metadata)!==void 0;var r=e.v2?t.nationalNumber:t.phone;return _n(r,n.nationalNumberPattern())}function T5(t,e,n){var r=new Je(n),i=r.getCountryCodesForCallingCode(t);return i?i.filter(function(s){return R5(e,s,n)}):[]}function R5(t,e,n){var r=new Je(n);return r.selectNumberingPlan(e),r.numberingPlan.possibleLengths().indexOf(t.length)>=0}var Up=2,B5=17,L5=3,Ot="0-90-9٠-٩۰-۹",U5="-‐-―−ー-",D5="//",M5="..",q5="  ­​⁠ ",F5="()()[]\\[\\]",H5="~⁓∼~",qa="".concat(U5).concat(D5).concat(M5).concat(q5).concat(F5).concat(H5),Dp="++",V5=new RegExp("(["+Ot+"])");function K5(t,e,n,r){if(e){var i=new Je(r);i.selectNumberingPlan(e,n);var s=new RegExp(i.IDDPrefix());if(t.search(s)===0){t=t.slice(t.match(s)[0].length);var a=t.match(V5);if(!(a&&a[1]!=null&&a[1].length>0&&a[1]==="0"))return t}}}function G5(t,e){if(t&&e.numberingPlan.nationalPrefixForParsing()){var n=new RegExp("^(?:"+e.numberingPlan.nationalPrefixForParsing()+")"),r=n.exec(t);if(r){var i,s,a=r.length-1,c=a>0&&r[a];if(e.nationalPrefixTransformRule()&&c)i=t.replace(n,e.nationalPrefixTransformRule()),a>1&&(s=r[1]);else{var l=r[0];i=t.slice(l.length),c&&(s=r[1])}var d;if(c){var u=t.indexOf(r[1]),f=t.slice(0,u);f===e.numberingPlan.nationalPrefix()&&(d=e.numberingPlan.nationalPrefix())}else d=r[0];return{nationalNumber:i,nationalPrefix:d,carrierCode:s}}}return{nationalNumber:t}}function W5(t,e){var n=typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=J5(t))||e){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[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 J5(t,e){if(t){if(typeof t=="string")return Wg(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Wg(t,e):void 0}}function Wg(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function X5(t,e){var n=e.countries,r=e.metadata;r=new Je(r);for(var i=W5(n),s;!(s=i()).done;){var a=s.value;if(r.selectNumberingPlan(a),r.leadingDigits()){if(t&&t.search(r.leadingDigits())===0)return a}else if(Lp({phone:t,country:a},void 0,r.metadata))return a}}function j1(t,e){var n=e.nationalNumber,r=e.metadata,i=r.getCountryCodesForCallingCode(t);if(i)return i.length===1?i[0]:X5(n,{countries:i,metadata:r.metadata})}function fu(t,e,n){var r=G5(t,n),i=r.carrierCode,s=r.nationalNumber;if(s!==t){if(!Z5(t,s,n))return{nationalNumber:t};if(n.numberingPlan.possibleLengths()&&(e||(e=j1(n.numberingPlan.callingCode(),{nationalNumber:s,metadata:n})),!Y5(s,e,n)))return{nationalNumber:t}}return{nationalNumber:s,carrierCode:i}}function Z5(t,e,n){return!(_n(t,n.nationalNumberPattern())&&!_n(e,n.nationalNumberPattern()))}function Y5(t,e,n){switch(Bp(t,e,n)){case"TOO_SHORT":case"INVALID_LENGTH":return!1;default:return!0}}function Q5(t,e,n,r,i){var s=n?Rp(n,i):r;if(t.indexOf(s)===0){i=new Je(i),i.selectNumberingPlan(n,s);var a=t.slice(s.length),c=fu(a,e,i),l=c.nationalNumber,d=fu(t,e,i),u=d.nationalNumber;if(!_n(u,i.nationalNumberPattern())&&_n(l,i.nationalNumberPattern())||Bp(u,e,i)==="TOO_LONG")return{countryCallingCode:s,number:a}}return{number:t}}function P1(t,e,n,r,i){if(!t)return{};var s;if(t[0]!=="+"){var a=K5(t,n,r,i);if(a&&a!==t)s=!0,t="+"+a;else{if(n||r){var c=Q5(t,e,n,r,i),l=c.countryCallingCode,d=c.number;if(l)return{countryCallingCodeSource:"FROM_NUMBER_WITHOUT_PLUS_SIGN",countryCallingCode:l,number:d}}return{number:t}}}if(t[1]==="0")return{};i=new Je(i);for(var u=2;u-1<=L5&&u<=t.length;){var f=t.slice(1,u);if(i.hasCallingCode(f))return i.selectNumberingPlan(f),{countryCallingCodeSource:s?"FROM_NUMBER_WITH_IDD":"FROM_NUMBER_WITH_PLUS_SIGN",countryCallingCode:f,number:t.slice(u)};u++}return{}}function e6(t){return t.replace(new RegExp("[".concat(qa,"]+"),"g")," ").trim()}var t6=/(\$\d)/;function n6(t,e,n){var r=n.useInternationalFormat,i=n.withNationalPrefix,s=t.replace(new RegExp(e.pattern()),r?e.internationalFormat():i&&e.nationalPrefixFormattingRule()?e.format().replace(t6,e.nationalPrefixFormattingRule()):e.format());return r?e6(s):s}var r6=/^[\d]+(?:[~\u2053\u223C\uFF5E][\d]+)?$/;function i6(t,e,n){var r=new Je(n);if(r.selectNumberingPlan(t,e),r.defaultIDDPrefix())return r.defaultIDDPrefix();if(r6.test(r.IDDPrefix()))return r.IDDPrefix()}var o6=";ext=",Nr=function(e){return"([".concat(Ot,"]{1,").concat(e,"})")};function O1(t){var e="20",n="15",r="9",i="6",s="[  \\t,]*",a="[:\\..]?[  \\t,-]*",c="#?",l="(?:e?xt(?:ensi(?:ó?|ó))?n?|e?xtn?|доб|anexo)",d="(?:[xx##~~]|int|int)",u="[- ]+",f="[  \\t]*",g="(?:,{2}|;)",_=o6+Nr(e),w=s+l+a+Nr(e)+c,k=s+d+a+Nr(r)+c,z=u+Nr(i)+"#",N=f+g+a+Nr(n)+c,I=f+"(?:,)+"+a+Nr(r)+c;return _+"|"+w+"|"+k+"|"+z+"|"+N+"|"+I}var s6="["+Ot+"]{"+Up+"}",a6="["+Dp+"]{0,1}(?:["+qa+"]*["+Ot+"]){3,}["+qa+Ot+"]*",c6=new RegExp("^["+Dp+"]{0,1}(?:["+qa+"]*["+Ot+"]){1,2}$","i"),l6=a6+"(?:"+O1()+")?",d6=new RegExp("^"+s6+"$|^"+l6+"$","i");function u6(t){return t.length>=Up&&d6.test(t)}function p6(t){return c6.test(t)}function f6(t){var e=t.number,n=t.ext;if(!e)return"";if(e[0]!=="+")throw new Error('"formatRFC3966()" expects "number" to be in E.164 format.');return"tel:".concat(e).concat(n?";ext="+n:"")}var Jg={formatExtension:function(e,n,r){return"".concat(e).concat(r.ext()).concat(n)}};function h6(t,e,n,r){if(n?n=_6({},Jg,n):n=Jg,r=new Je(r),t.country&&t.country!=="001"){if(!r.hasCountry(t.country))throw new Error("Unknown country: ".concat(t.country));r.selectNumberingPlan(t.country)}else if(t.countryCallingCode)r.selectNumberingPlan(t.countryCallingCode);else return t.phone||"";var i=r.countryCallingCode(),s=n.v2?t.nationalNumber:t.phone,a;switch(e){case"NATIONAL":return s?(a=Fa(s,t.carrierCode,"NATIONAL",r,n),Al(a,t.ext,r,n.formatExtension)):"";case"INTERNATIONAL":return s?(a=Fa(s,null,"INTERNATIONAL",r,n),a="+".concat(i," ").concat(a),Al(a,t.ext,r,n.formatExtension)):"+".concat(i);case"E.164":return"+".concat(i).concat(s);case"RFC3966":return f6({number:"+".concat(i).concat(s),ext:t.ext});case"IDD":if(!n.fromCountry)return;var c=m6(s,t.carrierCode,i,n.fromCountry,r);return Al(c,t.ext,r,n.formatExtension);default:throw new Error('Unknown "format" argument passed to "formatNumber()": "'.concat(e,'"'))}}function Fa(t,e,n,r,i){var s=g6(r.formats(),t);return s?n6(t,s,{useInternationalFormat:n==="INTERNATIONAL",withNationalPrefix:!(s.nationalPrefixIsOptionalWhenFormattingInNationalFormat()&&i&&i.nationalPrefix===!1)}):t}function g6(t,e){return y6(t,function(n){if(n.leadingDigitsPatterns().length>0){var r=n.leadingDigitsPatterns()[n.leadingDigitsPatterns().length-1];if(e.search(r)!==0)return!1}return _n(e,n.pattern())})}function Al(t,e,n,r){return e?r(t,e,n):t}function m6(t,e,n,r,i){var s=Rp(r,i.metadata);if(s===n){var a=Fa(t,e,"NATIONAL",i);return n==="1"?n+" "+a:a}var c=i6(r,void 0,i.metadata);if(c)return"".concat(c," ").concat(n," ").concat(Fa(t,null,"INTERNATIONAL",i))}function _6(){for(var t=1,e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];for(;t<n.length;){if(n[t])for(var i in n[t])n[0][i]=n[t][i];t++}return n[0]}function y6(t,e){for(var n=0;n<t.length;){if(e(t[n]))return t[n];n++}}function Po(t){"@babel/helpers - typeof";return Po=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Po(t)}function Xg(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function Zg(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Xg(Object(n),!0).forEach(function(r){w6(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Xg(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function w6(t,e,n){return(e=T1(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function b6(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function v6(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,T1(r.key),r)}}function $6(t,e,n){return e&&v6(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function T1(t){var e=k6(t,"string");return Po(e)=="symbol"?e:e+""}function k6(t,e){if(Po(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(Po(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}var x6=(function(){function t(e,n,r){if(b6(this,t),!e)throw new TypeError("First argument is required");if(typeof e!="string")throw new TypeError("First argument must be a string");if(e[0]==="+"&&!n)throw new TypeError("`metadata` argument not passed");if(Kr(n)&&Kr(n.countries)){r=n;var i=e;if(!A6.test(i))throw new Error('Invalid `number` argument passed: must consist of a "+" followed by digits');var s=P1(i,void 0,void 0,void 0,r),a=s.countryCallingCode,c=s.number;if(n=c,e=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");C1(r);var l=z6(e,r),d=l.country,u=l.countryCallingCode;this.country=d,this.countryCallingCode=u,this.nationalNumber=n,this.number="+"+this.countryCallingCode+this.nationalNumber,this.getMetadata=function(){return r}}return $6(t,[{key:"setExt",value:function(n){this.ext=n}},{key:"getPossibleCountries",value:function(){return this.country?[this.country]:T5(this.countryCallingCode,this.nationalNumber,this.getMetadata())}},{key:"isPossible",value:function(){return N5(this,{v2:!0},this.getMetadata())}},{key:"isValid",value:function(){return O5(this,{v2:!0},this.getMetadata())}},{key:"isNonGeographic",value:function(){var n=new Je(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 Lp(this,{v2:!0},this.getMetadata())}},{key:"format",value:function(n,r){return h6(this,n,r?Zg(Zg({},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)}}])})(),S6=function(e){return/^[A-Z]{2}$/.test(e)};function z6(t,e){var n,r,i=new Je(e);return S6(t)?(n=t,i.selectNumberingPlan(n),r=i.countryCallingCode()):r=t,{country:n,countryCallingCode:r}}var A6=/^\+\d+$/;function hu(t){"@babel/helpers - typeof";return hu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},hu(t)}function E6(t,e,n){return Object.defineProperty(t,"prototype",{writable:!1}),t}function C6(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function N6(t,e,n){return e=To(e),I6(t,Mp()?Reflect.construct(e,n||[],To(t).constructor):e.apply(t,n))}function I6(t,e){if(e&&(hu(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return j6(t)}function j6(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function P6(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&Oo(t,e)}function gu(t){var e=typeof Map=="function"?new Map:void 0;return gu=function(r){if(r===null||!T6(r))return r;if(typeof r!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(r))return e.get(r);e.set(r,i)}function i(){return O6(r,arguments,To(this).constructor)}return i.prototype=Object.create(r.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),Oo(i,r)},gu(t)}function O6(t,e,n){if(Mp())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,e);var i=new(t.bind.apply(t,r));return n&&Oo(i,n.prototype),i}function Mp(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Mp=function(){return!!t})()}function T6(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function Oo(t,e){return Oo=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},Oo(t,e)}function To(t){return To=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},To(t)}var an=(function(t){function e(n){var r;return C6(this,e),r=N6(this,e,[n]),Object.setPrototypeOf(r,e.prototype),r.name=r.constructor.name,r}return P6(e,t),E6(e)})(gu(Error)),Yg=new RegExp("(?:"+O1()+")$","i");function R6(t){var e=t.search(Yg);if(e<0)return{};for(var n=t.slice(0,e),r=t.match(Yg),i=1;i<r.length;){if(r[i])return{number:n,ext:r[i]};i++}}var B6={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 L6(t){return B6[t]}function U6(t,e){var n=typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=D6(t))||e){n&&(t=n);var r=0;return function(){return r>=t.length?{done:!0}:{done:!1,value:t[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 D6(t,e){if(t){if(typeof t=="string")return Qg(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Qg(t,e):void 0}}function Qg(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function e0(t){for(var e="",n=U6(t.split("")),r;!(r=n()).done;){var i=r.value;e+=M6(i,e)||""}return e}function M6(t,e,n){return t==="+"?e?void 0:"+":L6(t)}var R1="+",q6="[\\-\\.\\(\\)]?",t0="(["+Ot+"]|"+q6+")",F6="^\\"+R1+t0+"*["+Ot+"]"+t0+"*$",H6=new RegExp(F6,"g"),mu=Ot,V6="["+mu+"]+((\\-)*["+mu+"])*",K6="a-zA-Z",G6="["+K6+"]+((\\-)*["+mu+"])*",W6="^("+V6+"\\.)*"+G6+"\\.?$",J6=new RegExp(W6,"g"),n0="tel:",_u=";phone-context=",X6=";isub=";function Z6(t){var e=t.indexOf(_u);if(e<0)return null;var n=e+_u.length;if(n>=t.length)return"";var r=t.indexOf(";",n);return r>=0?t.substring(n,r):t.substring(n)}function Y6(t){return t===null?!0:t.length===0?!1:H6.test(t)||J6.test(t)}function Q6(t,e){var n=e.extractFormattedPhoneNumber,r=Z6(t);if(!Y6(r))throw new an("NOT_A_NUMBER");var i;if(r===null)i=n(t)||"";else{i="",r.charAt(0)===R1&&(i+=r);var s=t.indexOf(n0),a;s>=0?a=s+n0.length:a=0;var c=t.indexOf(_u);i+=t.substring(a,c)}var l=i.indexOf(X6);if(l>0&&(i=i.substring(0,l)),i!=="")return i}var e8=250,t8=new RegExp("["+Dp+Ot+"]"),n8=new RegExp("[^"+Ot+"#]+$");function r8(t,e,n){if(e=e||{},n=new Je(n),e.defaultCountry&&!n.hasCountry(e.defaultCountry))throw e.v2?new an("INVALID_COUNTRY"):new Error("Unknown country: ".concat(e.defaultCountry));var r=o8(t,e.v2,e.extract),i=r.number,s=r.ext,a=r.error;if(!i){if(e.v2)throw a==="TOO_SHORT"?new an("TOO_SHORT"):new an("NOT_A_NUMBER");return{}}var c=a8(i,e.defaultCountry,e.defaultCallingCode,n),l=c.country,d=c.nationalNumber,u=c.countryCallingCode,f=c.countryCallingCodeSource,g=c.carrierCode;if(!n.hasSelectedNumberingPlan()){if(e.v2)throw new an("INVALID_COUNTRY");return{}}if(!d||d.length<Up){if(e.v2)throw new an("TOO_SHORT");return{}}if(d.length>B5){if(e.v2)throw new an("TOO_LONG");return{}}if(e.v2){var _=new x6(u,d,n.metadata);return l&&(_.country=l),g&&(_.carrierCode=g),s&&(_.ext=s),_.__countryCallingCodeSource=f,_}var w=(e.extended?n.hasSelectedNumberingPlan():l)?_n(d,n.nationalNumberPattern()):!1;return e.extended?{country:l,countryCallingCode:u,carrierCode:g,valid:w,possible:w?!0:!!(e.extended===!0&&n.possibleLengths()&&I1(d,l,n)),phone:d,ext:s}:w?s8(l,d,s):{}}function i8(t,e,n){if(t){if(t.length>e8){if(n)throw new an("TOO_LONG");return}if(e===!1)return t;var r=t.search(t8);if(!(r<0))return t.slice(r).replace(n8,"")}}function o8(t,e,n){var r=Q6(t,{extractFormattedPhoneNumber:function(a){return i8(a,n,e)}});if(!r)return{};if(!u6(r))return p6(r)?{error:"TOO_SHORT"}:{};var i=R6(r);return i.ext?i:{number:r}}function s8(t,e,n){var r={country:t,phone:e};return n&&(r.ext=n),r}function a8(t,e,n,r){var i=P1(e0(t),void 0,e,n,r.metadata),s=i.countryCallingCodeSource,a=i.countryCallingCode,c=i.number,l;if(a)r.selectNumberingPlan(a);else if(c&&(e||n))r.selectNumberingPlan(e,n),e&&(l=e),a=n||Rp(e,r.metadata);else return{};if(!c)return{countryCallingCodeSource:s,countryCallingCode:a};var d=fu(e0(c),l,r),u=d.nationalNumber,f=d.carrierCode,g=j1(a,{nationalNumber:u,metadata:r});return g&&(l=g,g==="001"||r.selectNumberingPlan(l)),{country:l,countryCallingCode:a,countryCallingCodeSource:s,nationalNumber:u,carrierCode:f}}function Ro(t){"@babel/helpers - typeof";return Ro=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ro(t)}function r0(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function i0(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?r0(Object(n),!0).forEach(function(r){c8(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):r0(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function c8(t,e,n){return(e=l8(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function l8(t){var e=d8(t,"string");return Ro(e)=="symbol"?e:e+""}function d8(t,e){if(Ro(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(Ro(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function u8(t,e,n){return r8(t,i0(i0({},e),{},{v2:!0}),n)}function Bo(t){"@babel/helpers - typeof";return Bo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Bo(t)}function o0(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function p8(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?o0(Object(n),!0).forEach(function(r){f8(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):o0(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function f8(t,e,n){return(e=h8(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function h8(t){var e=g8(t,"string");return Bo(e)=="symbol"?e:e+""}function g8(t,e){if(Bo(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(Bo(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function m8(t,e){return b8(t)||w8(t,e)||y8(t,e)||_8()}function _8(){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 y8(t,e){if(t){if(typeof t=="string")return s0(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?s0(t,e):void 0}}function s0(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function w8(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,i,s,a,c=[],l=!0,d=!1;try{if(s=(n=n.call(t)).next,e!==0)for(;!(l=(r=s.call(n)).done)&&(c.push(r.value),c.length!==e);l=!0);}catch(u){d=!0,i=u}finally{try{if(!l&&n.return!=null&&(a=n.return(),Object(a)!==a))return}finally{if(d)throw i}}return c}}function b8(t){if(Array.isArray(t))return t}function v8(t){var e=Array.prototype.slice.call(t),n=m8(e,4),r=n[0],i=n[1],s=n[2],a=n[3],c,l,d;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,d=a):(l=void 0,d=s),i&&(l=p8({defaultCountry:i},l));else if(Kr(i))s?(l=i,d=s):d=i;else throw new Error("Invalid second argument: ".concat(i));return{text:c,options:l,metadata:d}}function Lo(t){"@babel/helpers - typeof";return Lo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Lo(t)}function a0(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function c0(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?a0(Object(n),!0).forEach(function(r){$8(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):a0(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function $8(t,e,n){return(e=k8(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function k8(t){var e=x8(t,"string");return Lo(e)=="symbol"?e:e+""}function x8(t,e){if(Lo(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(Lo(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function S8(t,e,n){e&&e.defaultCountry&&!E5(e.defaultCountry,n)&&(e=c0(c0({},e),{},{defaultCountry:void 0}));try{return u8(t,e,n)}catch(r){if(!(r instanceof an))throw r}}function z8(){var t=v8(arguments),e=t.text,n=t.options,r=t.metadata;return S8(e,n,r)}function A8(){return m5(z8,arguments)}function nl(t,e="US"){const n=t.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=A8(n,{defaultCountry:e});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:"auth2"}}function qp(t){let e=t.trim();e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1));const n=e.indexOf("%");return n!==-1&&(e=e.slice(0,n)),e}function E8(t){const n=qp(t).split(".");return n.length!==4?!1:n.every(r=>/^\d+$/.test(r)&&Number(r)>=0&&Number(r)<=255)}function C8(t){const e=qp(t);if(e.length<2||e.indexOf(":")===-1||!/^[0-9a-fA-F:.]+$/.test(e))return!1;const n=e.split(":");return e.includes("::")?n.length<=8:n.length===8}function N8(t){let e=t.trim();const n=/^\[([^\]]+)\](?::\d+)?$/,r=e.match(n);if(r&&r[1])return r[1];const i=e.lastIndexOf(":");if(i!==-1){const s=e.slice(0,i),a=e.slice(i+1);/^[0-9.]+$/.test(s)&&/^\d+$/.test(a)&&(e=s)}return e}function l0(t){if(!t)return null;const e=qp(N8(t));return E8(e)?{family:4,normalized:e}:C8(e)?{family:6,normalized:e.toLowerCase()}:null}function d0(t){if(t.includes("::")){let[e,n]=t.split("::"),r=e?e.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 t.split(":").map(e=>e.toLowerCase()||"0")}function I8(t,e,n=!0){const r=l0(t),i=l0(e);if(!r||!i||r.family!==i.family)return!1;if(r.family===4)return r.normalized===i.normalized;const s=d0(r.normalized),a=d0(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 vr extends Error{location;status;constructor(e,n=302){super(`Redirect to ${e}`),this.name=vr.name,this.location=e,this.status=n}}const j8=o.z.object({client_id:o.z.string(),username:o.z.string().transform(t=>t.toLowerCase()),otp:o.z.string(),authParams:go.optional(),enforceIpCheck:o.z.boolean().optional().default(!1)});async function B1(t,{client_id:e,username:n,otp:r,authParams:i,enforceIpCheck:s=!1}){const a=t.get("ip"),c=t.get("countryCode"),{connectionType:l,normalized:d}=nl(n,c);if(!d)throw new B(400,{message:"Invalid username format"});const u=await t.env.data.legacyClients.get(e);if(!u)throw new B(403,{message:"Client not found"});const{env:f}=t,g=await f.data.codes.get(u.tenant.id,r,"otp");if(!g)throw new B(400,{message:X("code_invalid")});if(g.expires_at<new Date().toISOString())throw new B(400,{message:X("code_expired")});if(g.used_at)throw new B(400,{message:X("code_used")});const _=await f.data.loginSessions.get(u.tenant.id,g.login_id);if(!_||_.authParams.username!==n)throw new B(400,{message:"Code not found or expired"});if(s&&_.ip&&a&&!I8(_.ip,a))throw new vr(`${De(t.env)}invalid-session?state=${_.id}`);const w=await nc(t,{client:u,username:d,provider:l,connection:l,isSocial:!1,ip:t.var.ip});return await f.data.codes.used(u.tenant.id,r),{user:w,client:u,loginSession:_,session_id:_.session_id,authParams:{..._.authParams,...i||{}}}}async function Fp(t,e){const n=await B1(t,e);return Gt(t,{authParams:n.authParams,client:n.client,user:n.user,loginSession:n.loginSession,authStrategy:{strategy:"email",strategy_type:"passwordless"}})}const u0=o.z.object({client_id:o.z.string().optional(),client_secret:o.z.string().optional()}),p0=o.z.union([E1.extend(u0.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(),...u0.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 P8(t){if(!t)return{};const[e,n]=t.split(" ");if(e?.toLowerCase()==="basic"&&n){const[r,i]=atob(n).split(":");return{client_id:r,client_secret:i}}return{}}const O8=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:p0},"application/json":{schema:p0}}}},responses:{200:{content:{"application/json":{schema:Iu}},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 t=>{const n=(t.req.header("Content-Type")||"").includes("application/json")?t.req.valid("json"):t.req.valid("form"),r=P8(t.req.header("Authorization")),i={...n,...r};if(!i.client_id)throw new v(400,{message:"client_id is required"});t.set("client_id",i.client_id);let s;switch(n.grant_type){case St.AuthorizationCode:s=await p5(t,u5.parse(i));break;case St.ClientCredential:s=await d5(t,E1.parse(i));break;case St.RefreshToken:s=await h5(t,f5.parse(i));break;case St.OTP:s=await B1(t,j8.parse(i));break;default:return t.json({error:"unsupported_grant_type",error_description:"Grant type not implemented"},400)}const a=new Headers;if(s.session_id){const d=ta(s.client.tenant.id,s.session_id,t.var.host||"");a.set("Set-Cookie",d)}let c=[];if(s.authParams.audience)try{let d;if(n.grant_type===St.ClientCredential)d=await na(t,{grantType:St.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 B(400,{error:"invalid_request",error_description:"User ID is required for user-based grants"});d=await na(t,{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=d.scopes.join(" "),c=d.permissions}catch(d){if(d instanceof v)throw d;console.error("Error calculating scopes and permissions:",d)}const l=await Ya(t,{...s,grantType:n.grant_type,permissions:c.length>0?c:void 0});return t.json(l,{headers:a})}),kn={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 Ht extends Error{code;params;constructor(e,n,r){super(n),this.code=e,this.params=r,this.name="PasswordPolicyError"}}async function Hp(t,e){const{newPassword:n,userData:r,data:i,tenantId:s,userId:a}=e,c=t.passwordPolicy!==void 0||t.password_complexity_options!==void 0||t.password_history!==void 0||t.password_no_personal_info!==void 0||t.password_dictionary!==void 0,l=c?t.passwordPolicy:"good",d=c?t.password_complexity_options?.min_length:8;if(d&&n.length<d)throw new Ht(kn.TOO_SHORT,`Password must be at least ${d} characters`,{minLength:d});if(l&&l!=="none"&&l==="good"){if(!/[a-z]/.test(n))throw new Ht(kn.MISSING_LOWERCASE,"Password must contain at least one lowercase letter");if(!/[A-Z]/.test(n))throw new Ht(kn.MISSING_UPPERCASE,"Password must contain at least one uppercase letter");if(!/\d/.test(n))throw new Ht(kn.MISSING_NUMBER,"Password must contain at least one number");if(!/[^A-Za-z0-9]/.test(n))throw new Ht(kn.MISSING_SPECIAL,"Password must contain at least one special character")}if(t.password_history?.enable){const u=t.password_history.size||5,f=await i.passwords.list(s,a,u);for(const g of f)if(await Pn.compare(n,g.password))throw new Ht(kn.REUSED,"Password was used recently and cannot be reused",{historySize:u})}if(t.password_no_personal_info?.enable&&r&&[r.email,r.name].filter(Boolean).join(" ").toLowerCase().includes(n.toLowerCase()))throw new Ht(kn.CONTAINS_PERSONAL_INFO,"Password cannot contain personal information like your name or email");if(t.password_dictionary?.enable&&t.password_dictionary.dictionary&&t.password_dictionary.dictionary.some(u=>n.toLowerCase().includes(u.toLowerCase())))throw new Ht(kn.CONTAINS_FORBIDDEN_WORD,"Password contains a forbidden word")}async function Vp(t,e,n){return(await t.connections.get(e,n))?.options||{}}async function us(t,e){const n=await t.env.data.emailProviders.get(t.var.tenant_id)||(t.env.DEFAULT_TENANT_ID?await t.env.data.emailProviders.get(t.env.DEFAULT_TENANT_ID):null);if(!n)throw new v(500,{message:"Email provider not found"});const r=t.env.emailProviders?.[n.name];if(!r)throw new v(500,{message:"Email provider not found"});await r({emailProvider:n,...e,from:n.default_from_address||`login@${t.env.ISSUER}`})}async function L1(t,e){if(!t.var.client_id)throw new v(500,{message:"Client not found"});const n=await zi(t.env,t.var.client_id),r=n.connections.find(a=>a.strategy==="sms");if(!r)throw new v(500,{message:"SMS provider not found"});const i=r.options?.provider||"twilio",s=t.env.smsProviders?.[i];if(!s)throw new v(500,{message:"SMS provider not found"});await s({options:r.options,to:e.to,from:e.from,text:e.text,template:"auth-code",data:{code:e.code,tenantName:n.tenant.friendly_name,tenantId:n.tenant.id}})}async function U1(t,e,n,r,i){const s=await t.env.data.tenants.get(t.var.tenant_id);if(!s)throw new v(500,{message:"Tenant not found"});const a=`${De(t.env)}reset-password?state=${r}&code=${n}`,c=await t.env.data.branding.get(t.var.tenant_id),l=c?.logo_url||"",d=c?.colors?.primary||"#7d68f4",u={vendorName:s.friendly_name,lng:"en"};await us(t,{to:e,subject:X("reset_password_title",u),html:`Click here to reset your password: ${De(t.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:d,passwordResetTitle:X("password_reset_title",u),resetPasswordEmailClickToReset:X("reset_password_email_click_to_reset",u),resetPasswordEmailReset:X("reset_password_email_reset",u),supportInfo:X("support_info",u),contactUs:X("contact_us",u),copyright:X("copyright",u),tenantName:s.friendly_name,tenantId:s.id}}),ie(t,s.id,{type:te.SUCCESS_CHANGE_PASSWORD_REQUEST,description:e})}async function Kp(t,{to:e,code:n,language:r}){const i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new v(500,{message:"Tenant not found"});const{connectionType:s}=nl(e),a=await t.env.data.branding.get(t.var.tenant_id),c=a?.logo_url||"",l=a?.colors?.primary||"#7d68f4",d=new URL(De(t.env)),u={vendorName:i.friendly_name,vendorId:i.id,loginDomain:d.hostname,code:n,lng:r||"en"};s==="email"?await us(t,{to:e,subject:X("code_email_subject",u),html:`Click here to validate your email: ${De(t.env)}validate-email`,template:"auth-code",data:{code:n,vendorName:i.friendly_name,logo:c,supportUrl:i.support_url||"",buttonColor:l,welcomeToYourAccount:X("welcome_to_your_account",u),linkEmailClickToLogin:X("link_email_click_to_login",u),linkEmailLogin:X("link_email_login",u),linkEmailOrEnterCode:X("link_email_or_enter_code",u),codeValid30Mins:X("code_valid_30_minutes",u),supportInfo:X("support_info",u),contactUs:X("contact_us",u),copyright:X("copyright",u)}}):s==="sms"&&await L1(t,{to:e,text:X("sms_code_text",u),code:n,from:i.friendly_name}),ie(t,i.id,{type:te.CODE_LINK_SENT,description:e})}async function Gp(t,{to:e,code:n,authParams:r,language:i}){const s=await t.env.data.tenants.get(t.var.tenant_id);if(!s)throw new v(500,{message:"Tenant not found"});if(!r.redirect_uri)throw new v(400,{message:"redirect_uri is required"});const{connectionType:a}=nl(e),c=await t.env.data.branding.get(t.var.tenant_id),l=c?.logo_url||"",d=c?.colors?.primary||"",u=new URL(me(t.env));u.pathname="passwordless/verify_redirect",u.searchParams.set("verification_code",n),u.searchParams.set("connection",a),u.searchParams.set("client_id",r.client_id),u.searchParams.set("redirect_uri",r.redirect_uri),u.searchParams.set("email",e),r.response_type&&u.searchParams.set("response_type",r.response_type),r.scope&&u.searchParams.set("scope",r.scope),r.state&&u.searchParams.set("state",r.state),r.nonce&&u.searchParams.set("nonce",r.nonce),r.code_challenge&&u.searchParams.set("code_challenge",r.code_challenge),r.code_challenge_method&&u.searchParams.set("code_challenge_method",r.code_challenge_method),r.audience&&u.searchParams.set("audience",r.audience);const f={vendorName:s.friendly_name,code:n,lng:i||"en"};if(a==="email")await us(t,{to:e,subject:X("code_email_subject",f),html:`Click here to validate your email: ${De(t.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:s.friendly_name,logo:l,supportUrl:s.support_url||"",magicLink:u.toString(),buttonColor:d,welcomeToYourAccount:X("welcome_to_your_account",f),linkEmailClickToLogin:X("link_email_click_to_login",f),linkEmailLogin:X("link_email_login",f),linkEmailOrEnterCode:X("link_email_or_enter_code",f),codeValid30Mins:X("code_valid_30_minutes",f),supportInfo:X("support_info",f),contactUs:X("contact_us",f),copyright:X("copyright",f)}});else if(a==="sms")await L1(t,{to:e,text:`${X("link_sms_login",f)}: ${u.toString()}`,code:n,from:s.friendly_name});else throw new v(400,{message:"Only email and SMS connections are supported for magic links"});ie(t,s.id,{type:te.CODE_LINK_SENT,description:e})}async function Wp(t,e,n){const r=await t.env.data.tenants.get(t.var.tenant_id);if(!r)throw new v(500,{message:"Tenant not found"});if(!e.email)throw new v(400,{message:"User has no email"});const i=await t.env.data.branding.get(t.var.tenant_id),s=i?.logo_url||"",a=i?.colors?.primary||"#7d68f4",c={vendorName:r.friendly_name,lng:n||"en"};await us(t,{to:e.email,subject:X("welcome_to_your_account",c),html:`Click here to validate your email: ${De(t.env)}validate-email`,template:"auth-verify-email",data:{vendorName:r.friendly_name,logo:s,emailValidationUrl:`${De(t.env)}validate-email`,supportUrl:r.support_url||"https://support.sesamy.com",buttonColor:a,welcomeToYourAccount:X("welcome_to_your_account",c),verifyEmailVerify:X("verify_email_verify",c),supportInfo:X("support_info",c),contactUs:X("contact_us",c),copyright:X("copyright",c)}})}async function T8(t,e,n,r,i){const s=await t.env.data.tenants.get(t.var.tenant_id);if(!s)throw new v(500,{message:"Tenant not found"});const a=await t.env.data.branding.get(t.var.tenant_id),c=a?.logo_url||"",l=a?.colors?.primary||"#7d68f4",d={vendorName:s.friendly_name,lng:"en"},u=`${De(t.env)}signup?state=${r}&code=${n}`;await us(t,{to:e,subject:X("register_password_account",d),html:`Click here to register: ${u}`,template:"auth-pre-signup-verification",data:{vendorName:s.friendly_name,logo:c,signupUrl:u,setPassword:X("set_password",d),registerPasswordAccount:X("register_password_account",d),clickToSignUpDescription:X("click_to_sign_up_description",d),supportUrl:s.support_url||"https://support.sesamy.com",buttonColor:l,welcomeToYourAccount:X("welcome_to_your_account",d),verifyEmailVerify:X("verify_email_verify",d),supportInfo:X("support_info",d),contactUs:X("contact_us",d),copyright:X("copyright",d)}})}const R8=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(t=>t.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 t=>{const{email:e,password:n,client_id:r}=t.req.valid("json"),i=await t.env.data.legacyClients.get(r);if(!i)throw new v(400,{message:"Client not found"});t.set("client_id",i.client_id),t.set("tenant_id",i.tenant.id);const a=i.connections.find(f=>f.strategy==="Username-Password-Authentication")?.name||"Username-Password-Authentication",c=await Vp(t.env.data,i.tenant.id,a);try{await Hp(c,{tenantId:i.tenant.id,userId:"",newPassword:n,data:t.env.data})}catch(f){throw new v(400,{message:f?.message||"Password does not meet the requirements"})}if(await yo({userAdapter:t.env.data.users,tenant_id:i.tenant.id,username:e,provider:"auth2"}))throw new v(400,{message:"Invalid sign up"});const d=await t.env.data.users.create(i.tenant.id,{user_id:`auth2|${Xa()}`,email:e,email_verified:!1,provider:"auth2",connection:"Username-Password-Authentication",is_social:!1});t.set("user_id",d.user_id),t.set("username",d.email),t.set("connection",d.connection);const u=await Pn.hash(n,10);return await t.env.data.passwords.create(i.tenant.id,{user_id:d.user_id,password:u,algorithm:"bcrypt",is_current:!0}),await Wp(t,d),ie(t,i.tenant.id,{type:te.SUCCESS_SIGNUP,description:"Successful signup"}),t.json({_id:d.user_id,email:d.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(t=>t.toLowerCase())})}}}},responses:{200:{description:"Redirect to the client's redirect uri"}}}),async t=>{const{email:e,client_id:n}=t.req.valid("json"),r=await t.env.data.legacyClients.get(n);if(!r)throw new v(400,{message:"Client not found"});if(t.set("client_id",r.client_id),t.set("tenant_id",r.tenant.id),!await pi({userAdapter:t.env.data.users,tenant_id:r.tenant.id,username:e,provider:"auth2"}))return t.html("If an account with that email exists, we've sent instructions to reset your password.");const s={client_id:n,username:e},a=await t.env.data.loginSessions.create(r.tenant.id,{expires_at:new Date(Date.now()+or*1e3).toISOString(),authParams:s,csrf_token:pe(),ip:t.get("ip"),useragent:t.get("useragent"),auth0Client:mn(t.get("auth0_client"))});return await U1(t,e,a.id,a.authParams.state),t.html("If an account with that email exists, we've sent instructions to reset your password.")});function Ln(){const t="1234567890";let e="";for(let n=0;n<6;n+=1)e+=t[Math.floor(Math.random()*10)];return e.toString()}const B8=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(t=>t.toLowerCase()),send:o.z.enum(["link","code"]),authParams:go.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:go.omit({client_id:!0})})])}}}},responses:{200:{description:"Status"}}}),async t=>{const e=t.req.valid("json"),{env:n}=t,{client_id:r,send:i,authParams:s,connection:a}=e,c=await t.env.data.legacyClients.get(r);if(!c)throw new v(400,{message:"Client not found"});t.set("client_id",c.client_id),t.set("tenant_id",c.tenant.id);const l=a==="email"?e.email:e.phone_number,d=t.get("ip"),u=t.get("useragent"),f=t.get("auth0_client"),g=mn(f),_=await n.data.loginSessions.create(c.tenant.id,{authParams:{...s,client_id:r,username:l},expires_at:new Date(Date.now()+As).toISOString(),csrf_token:pe(),ip:d,useragent:u,auth0Client:g}),w=await n.data.codes.create(c.tenant.id,{code_id:Ln(),code_type:"otp",login_id:_.id,expires_at:new Date(Date.now()+As).toISOString(),redirect_uri:s.redirect_uri}),k=s?.ui_locales?.split(" ")?.map(z=>z.split("-")[0])[0];return i==="link"?await Gp(t,{to:l,code:w.code_id,authParams:{...s,client_id:r},language:k}):await Kp(t,{to:l,code:w.code_id,language:k}),t.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(mt),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(t=>t.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 t=>{const{env:e}=t,{client_id:n,email:r,verification_code:i,redirect_uri:s,state:a,scope:c,audience:l,response_type:d,nonce:u}=t.req.valid("query"),f=await zi(e,n);t.set("client_id",f.client_id),t.set("tenant_id",f.tenant.id),t.set("connection","email");const g={client_id:n,redirect_uri:s,state:a,nonce:u,scope:c,audience:l,response_type:d};let _="Something went wrong. Please try again later.";try{const S=await Fp(t,{client_id:n,username:r,otp:i,authParams:g,enforceIpCheck:!0});if(S instanceof Response)return S;if(S&&typeof S=="object"&&"access_token"in S)return t.json(S)}catch(S){const E=S;"message"in E&&typeof E.message=="string"&&(_=E.message)}const w=t.get("ip"),k=t.get("useragent"),z=t.get("auth0_client"),N=mn(z),I=await e.data.loginSessions.create(f.tenant.id,{authParams:{...g,username:r},expires_at:new Date(Date.now()+As).toISOString(),csrf_token:pe(),ip:w,useragent:k,auth0Client:N});return t.redirect(`${De(t.env)}invalid-session?state=${I.id}&error=${encodeURIComponent(_)}`,302)});class Tr extends v{_code;constructor(e,n){super(e,n),this._code=n?.code}get code(){return this._code}}async function L8(t,e,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 t.users.update(e,n.user_id,{app_metadata:r})}function U8(t){const n=(t.app_metadata||{}).failed_logins||[],r=Date.now();return n.filter(i=>r-i<1e3*60*5)}async function D1(t,e,n,r){const{data:i}=t.env,{username:s}=n;if(t.set("username",s),!s)throw new B(400,{message:"Username is required"});const a=await pi({userAdapter:t.env.data.users,tenant_id:e.tenant.id,username:s,provider:"auth2"});if(!a)throw ie(t,e.tenant.id,{type:te.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"}),new Tr(403,{message:"User not found",code:"USER_NOT_FOUND"});const c=a.linked_to?await i.users.get(e.tenant.id,a.linked_to):a;if(!c)throw new Tr(403,{message:"User not found",code:"USER_NOT_FOUND"});if(t.set("connection",a.connection),t.set("user_id",c.user_id),U8(c).length>=3)throw ie(t,e.tenant.id,{type:te.FAILED_LOGIN,description:"Too many failed login attempts"}),new Tr(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"});const d=await i.passwords.get(e.tenant.id,a.user_id);if(!(d&&await Pn.compare(n.password,d.password)))throw ie(t,e.tenant.id,{type:te.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"}),L8(i,e.tenant.id,c),new Tr(403,{message:"Invalid password",code:"INVALID_PASSWORD"});if(!a.email_verified&&e.client_metadata?.email_validation==="enforced"){const g=r?.authParams?.ui_locales?.split(" ")?.map(_=>_.split("-")[0])[0];throw await Wp(t,a,g),ie(t,e.tenant.id,{type:te.FAILED_LOGIN,description:"Email not verified"}),new Tr(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(e.tenant.id,c.user_id,{app_metadata:f})),{client:e,authParams:n,user:c,loginSession:r}}async function M1(t,e,n,r,i){const s=await D1(t,e,n,r);return Gt(t,{...s,ticketAuth:i,authStrategy:{strategy:"Username-Password-Authentication",strategy_type:"database"}})}async function D8(t,e,n,r){await nc(t,{client:e,username:n,provider:"auth2",connection:"Username-Password-Authentication",isSocial:!1,ip:t.var.ip});let i=Ln(),s=await t.env.data.codes.get(e.tenant.id,i,"password_reset");for(;s;)i=Ln(),s=await t.env.data.codes.get(e.tenant.id,i,"password_reset");const a=t.get("ip"),c=t.get("useragent"),l=t.get("auth0_client"),d=mn(l),u=await t.env.data.loginSessions.create(e.tenant.id,{expires_at:new Date(Date.now()+dv).toISOString(),authParams:{client_id:e.client_id,username:n},csrf_token:pe(),ip:a,useragent:c,auth0Client:d}),f=await t.env.data.codes.create(e.tenant.id,{code_id:i,code_type:"password_reset",login_id:u.id,expires_at:new Date(Date.now()+lv).toISOString()});await U1(t,n,f.code_id,r)}const M8=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(t=>t.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(t=>t.toLowerCase()),password:o.z.string(),realm:o.z.enum(["Username-Password-Authentication"]),scope:o.z.string().optional()})])}}}},responses:{200:{description:"List of tenants"}}}),async t=>{const e=t.req.valid("json"),{client_id:n,username:r}=e;t.set("username",r);const i=await t.env.data.legacyClients.get(n);if(!i)throw new v(400,{message:"Client not found"});t.set("client_id",n),t.set("tenant_id",i.tenant.id);const s=r.toLocaleLowerCase(),a=t.get("ip"),c=t.get("useragent"),l=t.get("auth0_client");let d;if("otp"in e)d=await Fp(t,{client_id:n,username:s,otp:e.otp});else if("password"in e){const u=await t.env.data.loginSessions.create(i.tenant.id,{expires_at:new Date(Date.now()+or*1e3).toISOString(),authParams:{client_id:n,username:s},csrf_token:pe(),ip:a,useragent:c,auth0Client:mn(l)});d=await M1(t,i,{username:s,password:e.password,client_id:n},u,!0)}else throw new v(400,{message:"Code or password required"});if(!(d instanceof Response))throw new v(500,{message:"Unexpected response from loginWithPassword"});return d});function q1(t,e){if(!t||e.length===0)return!1;const n=El(t)?.host??null;if(!n)return!1;for(const r of e){let i;if(r.startsWith("http://")||r.startsWith("https://")?i=El(r)?.host??null:i=El("https://"+r)?.host??null,n===i)return!0}return!1}function El(t){try{return new URL(t)}catch{return null}}async function q8({ctx:t,session:e,client:n,authParams:r,connection:i,login_hint:s}){const a=new URL(t.req.url);t.var.custom_domain&&(a.hostname=t.var.custom_domain);const{ip:c,auth0_client:l,useragent:d}=t.var,u=mn(l),f=await t.env.data.loginSessions.create(n.tenant.id,{expires_at:new Date(Date.now()+or*1e3).toISOString(),authParams:r,csrf_token:pe(),authorization_url:a.toString(),ip:c,useragent:d,auth0Client:u});if(e&&s){const g=await t.env.data.users.get(n.tenant.id,e.user_id);if(g?.email===s)return await t.env.data.loginSessions.update(n.tenant.id,f.id,{session_id:e.id}),Gt(t,{client:n,loginSession:{...f,session_id:e.id},authParams:r,user:g,sessionId:e.id})}if(i==="email"&&s){const g=Ln();return await t.env.data.codes.create(n.tenant.id,{code_id:g,code_type:"otp",login_id:f.id,expires_at:new Date(Date.now()+or*1e3).toISOString(),redirect_uri:r.redirect_uri}),await Gp(t,{code:g,to:s,authParams:r}),t.redirect(`/u/enter-code?state=${f.id}`)}return e?t.redirect(`/u/check-account?state=${f.id}`):t.redirect(`/u/login/identifier?state=${f.id}`)}function F8(t){if(t==="Username-Password-Authentication")return"auth2";if(t==="email")return"email";throw new B(403,{message:"Invalid realm"})}async function H8(t,e,n,r,i){const{env:s}=t;t.set("connection",i);const a=await s.data.codes.get(e,n,"ticket");if(!a||a.used_at)throw new B(403,{message:"Ticket not found"});const c=await s.data.loginSessions.get(e,a.login_id);if(!c||!c.authParams.username)throw new B(403,{message:"Session not found"});const l=await s.data.legacyClients.get(c.authParams.client_id);if(!l)throw new B(403,{message:"Client not found"});t.set("client_id",c.authParams.client_id),await s.data.codes.used(e,n);const d=F8(i),f=l.connections.find(k=>k.name===i)?.strategy||(d==="auth2"?"Username-Password-Authentication":"email"),g=f==="Username-Password-Authentication"?"database":"passwordless";let _=await nc(t,{username:c.authParams.username,provider:d,client:l,connection:i,isSocial:!1,ip:t.var.ip});t.set("username",_.email||_.phone_number),t.set("user_id",_.user_id);const w=await u_(t,{user:_,client:l,loginSession:c});return Gt(t,{authParams:{scope:c.authParams?.scope,...r},loginSession:c,sessionId:w.id,user:_,client:l,authStrategy:{strategy:f,strategy_type:g}})}async function V8({ctx:t,client:e,session:n,redirect_uri:r,state:i,nonce:s,code_challenge_method:a,code_challenge:c,audience:l,scope:d,response_type:u,organization:f}){const{env:g}=t,_=new URL(r),w=`${_.protocol}//${_.host}`;async function k(Z="Login required"){const W=new Headers;if(n){ie(t,e.tenant.id,{type:te.FAILED_SILENT_AUTH,description:Z});const M=r_(e.tenant.id,t.req.header("host"));W.set("set-cookie",M)}return Vl(t,w,JSON.stringify({error:"login_required",error_description:Z,state:i}),W)}if(!n||n?.expires_at&&new Date(n.expires_at)<new Date||n?.idle_expires_at&&new Date(n.idle_expires_at)<new Date)return k();t.set("user_id",n.user_id);const N=await g.data.users.get(e.tenant.id,n.user_id);if(!N)return console.error("User not found",n.user_id),k("User not found");t.set("username",N.email),t.set("connection",N.connection);const I=await g.data.loginSessions.create(e.tenant.id,{csrf_token:pe(),authParams:{client_id:e.client_id,audience:l,scope:d,state:i,nonce:s,response_type:u,redirect_uri:r,organization:f},expires_at:new Date(Date.now()+300*1e3).toISOString(),session_id:n.id,ip:t.var.ip,useragent:t.var.useragent}),S={client:e,authParams:{client_id:e.client_id,audience:l,code_challenge_method:a,code_challenge:c,scope:d,state:i,nonce:s,response_type:u,redirect_uri:r},user:N,session_id:n.id},E=u===mt.CODE?await l_(t,{user:N,client:e,authParams:S.authParams,login_id:I.id}):await Ya(t,S);await g.data.sessions.update(e.tenant.id,n.id,{used_at:new Date().toISOString(),last_interaction_at:new Date().toISOString(),login_session_id:I.id,device:{...n.device,last_ip:t.var.ip||"",last_user_agent:t.var.useragent||""},idle_expires_at:n.idle_expires_at?new Date(Date.now()+Za*1e3).toISOString():void 0}),ie(t,e.tenant.id,{type:te.SUCCESS_SILENT_AUTH,description:"Successful silent authentication"});const P=new Headers,G=ta(e.tenant.id,n.id,t.req.header("host"));return P.set("set-cookie",G),Vl(t,w,JSON.stringify({...E,state:i}),P)}const K8=["email","sms","Username-Password-Authentication"],G8=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:o.z.object({client_id:o.z.string(),vendor_id:o.z.string().optional(),redirect_uri:o.z.string(),scope:o.z.string().optional(),state:o.z.string(),prompt:o.z.string().optional(),response_mode:o.z.nativeEnum(Ct).optional(),response_type:o.z.nativeEnum(mt).optional(),audience:o.z.string().optional(),connection:o.z.string().optional(),nonce:o.z.string().optional(),max_age:o.z.string().optional(),login_ticket:o.z.string().optional(),code_challenge_method:o.z.nativeEnum(Ga).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().openapi({example:"signup",description:'Optional hint for the screen to show, like "signup" or "login".'}).optional(),ui_locales:o.z.string().optional()})},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:Iu}}},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 t=>{const{env:e}=t,{client_id:n,vendor_id:r,redirect_uri:i,scope:s,state:a,audience:c,nonce:l,connection:d,response_type:u,response_mode:f,code_challenge:g,code_challenge_method:_,prompt:w,login_ticket:k,realm:z,auth0Client:N,login_hint:I,ui_locales:S,organization:E}=t.req.valid("query");t.set("log","authorize");const P=await zi(e,n);t.set("client_id",P.client_id),t.set("tenant_id",P.tenant.id);const G={redirect_uri:i.split("#")[0],scope:s,state:a,client_id:n,vendor_id:r,audience:c,nonce:l,prompt:w,response_type:u,response_mode:f,code_challenge:g,code_challenge_method:_,username:I,ui_locales:S,organization:E},Z=t.req.header("origin");if(Z&&!q1(Z,P.web_origins||[]))throw new v(403,{message:`Origin ${Z} not allowed`});if(G.redirect_uri){const fe=P.callbacks||[];if(t.var.host&&(fe.push(`${ic(t.env)}/*`),fe.push(`${De(t.env)}/*`)),!Tp(G.redirect_uri,fe,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new v(400,{message:`Invalid redirect URI - ${G.redirect_uri}`})}const W=Wr(P.tenant.id,t.req.header("cookie")),M=W?await e.data.sessions.get(P.tenant.id,W):void 0,ce=M&&!M.revoked_at?M:void 0;if(w=="none"){if(!u)throw new v(400,{message:"Missing response_type"});return V8({ctx:t,session:ce||void 0,redirect_uri:i,state:a,response_type:u,client:P,nonce:l,code_challenge_method:_,code_challenge:g,audience:c,scope:s,organization:E})}if(P.connections.length===1&&P.connections[0]&&!K8.includes(P.connections[0].strategy||""))return Lg(t,P,P.connections[0].name,G);if(d&&d!=="email")return Lg(t,P,d,G);if(k){const fe=await H8(t,P.tenant.id,k,G,z);return fe instanceof Response?fe:t.json(fe)}const le=await q8({ctx:t,client:P,authParams:G,session:ce||void 0,connection:d,login_hint:I});return le instanceof Response?le:t.json(le)}),W8=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 t=>{const{env:e}=t,{client_id:n,redirect_url:r,login_hint:i,screen_hint:s}=t.req.valid("query");t.set("log","account");const a=await zi(e,n);t.set("client_id",a.client_id),t.set("tenant_id",a.tenant.id);const c={redirect_uri:r||t.req.url,client_id:n,username:i},l=t.req.header("origin");if(l&&!q1(l,a.web_origins||[]))throw new v(403,{message:`Origin ${l} not allowed`});if(c.redirect_uri){const I=a.callbacks||[];if(t.var.host&&(I.push(`${ic(t.env)}/*`),I.push(`${De(t.env)}/*`)),!Tp(c.redirect_uri,I,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new v(400,{message:`Invalid redirect URI - ${c.redirect_uri}`})}const d=Wr(a.tenant.id,t.req.header("cookie")),u=d?await e.data.sessions.get(a.tenant.id,d):void 0,f=u&&!u.revoked_at?u:void 0,g=new URL(t.req.url);t.var.custom_domain&&(g.hostname=t.var.custom_domain);const{ip:_,auth0_client:w,useragent:k}=t.var,z=mn(w),N=await e.data.loginSessions.create(a.tenant.id,{expires_at:new Date(Date.now()+or*1e3).toISOString(),authParams:c,csrf_token:pe(),authorization_url:g.toString(),ip:_,useragent:k,auth0Client:z});if(f){if(i&&(await e.data.users.get(a.tenant.id,f.user_id))?.email!==i)return t.redirect(`${De(t.env)}login/identifier?state=${encodeURIComponent(N.id)}`);if(await e.data.loginSessions.update(a.tenant.id,N.id,{session_id:f.id}),s==="change-email"){const S=new URL("/u/account/change-email",t.req.url);return S.searchParams.set("state",N.id),t.redirect(S.toString())}const I=new URL("/u/account",t.req.url);return I.searchParams.set("state",N.id),t.redirect(I.toString())}return t.redirect(`${De(t.env)}login/identifier?state=${encodeURIComponent(N.id)}`)});function J8(t){const e=new o.OpenAPIHono;e.use(async(r,i)=>{const s=qo(r,t.dataAdapter),a=t.dataAdapter.cache||ds({defaultTtlSeconds:0,maxEntries:100,cleanupIntervalMs:0}),c=t.dataAdapter.cache?300:0,l=Qc(s,{defaultTtl:c,cacheEntities:["tenants","connections","customDomains","clients","legacyClients","branding","themes","promptSettings","forms","resourceServers","roles","organizations","userRoles","userPermissions"],cache:a});return r.env.data=Xc(r,l),i()}),e.use("/oauth/token",M0({origin:r=>r||"",allowHeaders:["Tenant-Id","Content-Type","Auth0-Client","Upgrade-Insecure-Requests"],allowMethods:["POST"],maxAge:600})),e.use(Yc).use(Zc).use(Pp(e));const n=e.route("/v2/logout",a5).route("/userinfo",c5).route("/.well-known",l5).route("/oauth/token",O8).route("/dbconnections",R8).route("/passwordless",B8).route("/co/authenticate",M8).route("/authorize",G8).route("/account",W8).route("/callback",o5);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Oauth API"},security:[{oauth2:["openid","email","profile"]}]}),jp(n),n}async function he(t,e,n=!1){const{env:r}=t,i=await r.data.loginSessions.get(t.var.tenant_id||"",e);if(!i)throw new B(400,{message:"Login session not found"});t.set("loginSession",i);const s=await zi(r,i.authParams.client_id);t.set("client_id",s.client_id),t.set("tenant_id",s.tenant.id);let a;try{a=ck(t,"auth_ui_style")}catch{a=void 0}let c=!1;t.req?.url&&(c=(new URL(t.req.url).searchParams.get("style")||a||"classic")==="shadcn");const l=await r.data.tenants.get(s.tenant.id);if(l){if(i.session_id&&!n){if(!i.authParams.redirect_uri)throw new B(400,{message:"Login session closed and no redirect URI available"});const g=new URL(i.authParams.redirect_uri);throw g.searchParams.set("error","access_denied"),g.searchParams.set("error_description","Login session closed"),i.authParams.state&&g.searchParams.set("state",i.authParams.state),new vr(g.toString(),302)}}else throw new B(400,{message:"Tenant not found"});const d=await r.data.themes.get(l.id,"default"),u=await r.data.branding.get(l.id),f=i.authParams?.ui_locales?.split(" ")?.map(g=>g.split("-")[0])?.find(g=>{if(Array.isArray(y.options.supportedLngs))return y.options.supportedLngs.includes(g)});return await y.changeLanguage(f||"en"),{theme:d,branding:u,client:s,tenant:l,loginSession:i,useShadcn:c}}async function $r(t,e){const{theme:n,branding:r,client:i,tenant:s,loginSession:a,useShadcn:c}=await he(t,e,!0),l=Wr(i.tenant.id,t.req.header("cookie")),d=l?await t.env.data.sessions.get(i.tenant.id,l):null;if(!d||!a.session_id)throw new vr(`/u/login/identifier?state=${encodeURIComponent(e)}`);const u=await t.env.data.sessions.get(i.tenant.id,a.session_id),f=await t.env.data.users.get(i.tenant.id,d.user_id);if(!f||u?.user_id!==d.user_id)throw new vr(`/u/login/identifier?state=${encodeURIComponent(e)}`);return{theme:n,branding:r,client:i,user:f,tenant:s,loginSession:a,session:u,useShadcn:c}}const Cl={"Username-Password-Authentication":"password",email:"email",sms:"sms"};async function X8(t,e,n,r,i){if(i==="password")return"password";if(i==="code")return r==="sms"?"sms":"email";const a=(await tc({userAdapter:t.env.data.users,tenant_id:e.tenant.id,email:n}))?.app_metadata?.strategy;if(a&&Cl[a])return Cl[a];const c=e.connections.map(d=>Cl[d.strategy]).filter(d=>d!==void 0);return c.length===1&&c[0]?c[0]:(await t.env.data.promptSettings.get(e.tenant.id)).password_first&&c.includes("password")?"password":r==="sms"?"sms":"email"}var Nl={exports:{}};var f0;function Z8(){return f0||(f0=1,(function(t){(function(){var e={}.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)e.call(s,c)&&s[c]&&(a=i(a,c));return a}function i(s,a){return a?s?s+" "+a:s+a:s}t.exports?(n.default=n,t.exports=n):window.classNames=n})()})(Nl)),Nl.exports}var Y8=Z8();const Q=O3(Y8),en=({children:t,className:e,style:n})=>p("div",{className:Q("rounded-lg border border-gray-200 bg-white shadow-sm dark:border-gray-700 dark:bg-gray-800",e),style:n,children:t}),tn=({children:t,className:e})=>p("div",{className:Q("flex flex-col space-y-1.5 p-6",e),children:t}),nn=({children:t,className:e,style:n})=>p("h3",{className:Q("text-2xl font-semibold leading-none tracking-tight",e),style:n,children:t}),rn=({children:t,className:e,style:n})=>p("p",{className:Q("text-sm text-gray-500 dark:text-gray-400",e),style:n,children:t}),on=({children:t,className:e})=>p("div",{className:Q("p-6 pt-0",e),children:t}),F1=({children:t,className:e})=>p("div",{className:Q("flex items-center p-6 pt-0",e),children:t}),Pt=({id:t,type:e="text",name:n,placeholder:r,className:i,required:s=!1,value:a,disabled:c=!1,error:l=!1,style:d})=>p("input",{id:t,type:e,name:n,placeholder:r,required:s,value:a,disabled:c,className:Q("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:d}),Jt=({children:t,className:e,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 p("button",{type:i,disabled:s,className:Q("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],e),style:a,children:t})},_t=({htmlFor:t,className:e,style:n,children:r})=>p("label",{for:t,className:Q("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",e),style:n,children:r}),Re=({children:t,className:e})=>p("div",{className:Q("mb-2 text-sm text-red",e),children:t}),Rt=({theme:t,branding:e})=>{const n=t?.widget?.logo_url||e?.logo_url;return n?p("div",{className:"inline-flex h-9 items-center",children:p("img",{src:n,className:"h-full w-auto",alt:"Logo"})}):p(bo,{})},Ts=({error:t,theme:e,branding:n,loginSession:r,email:i,client:s,className:a,isEmbedded:c,browserName:l})=>{const d=s.connections.map(({strategy:ne})=>ne),u=d.includes("email")||d.includes("Username-Password-Authentication"),f=d.includes("sms"),g=new Set(["email","sms","Username-Password-Authentication","auth0"]),_=s.connections.filter(ne=>!g.has(ne.strategy)).filter(ne=>ne.show_as_button!==!1).map(ne=>{const Vn=Fu[ne.strategy];return Vn?{...Vn,connectionName:ne.name,displayName:ne.display_name||Vn.displayName||ne.name,iconUrl:ne.options.icon_url}:null}).filter(ne=>ne!==null).filter(ne=>!(c&&ne.disableEmbeddedBrowsers)),w=u||f,k=u&&f?"email_or_phone_placeholder":u?"email_placeholder":f?"phone_placeholder":null,z=k?y.t(k,u&&f?"Email or Phone Number":u?"Email Address":"Phone Number"):"",N=e?.colors?.primary_button||n?.colors?.primary||"#0066cc",I=e?.colors?.primary_button_label||"#ffffff",S=e?.colors?.body_text||"#333333",E=e?.colors?.input_background||"#ffffff",P=e?.colors?.input_border||"#d1d5db",G=e?.colors?.input_filled_text||"#111827",Z=e?.colors?.error||"#dc2626",W=e?.colors?.widget_background||"#ffffff",M=e?.colors?.widget_border||"#e5e7eb",ce=e?.borders?.widget_corner_radius||8,le=e?.borders?.input_border_radius||4,fe=e?.borders?.button_border_radius||4,$e=e?.borders?.show_widget_shadow??!0,be=e?.fonts?.title?.size||24,sn=e?.fonts?.title?.bold??!0,Be=e?.fonts?.body_text?.size||14,Qe={backgroundColor:W,borderColor:M,borderRadius:`${ce}px`,boxShadow:$e?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:S},Lt={fontSize:`${be}px`,fontWeight:sn?"700":"400",color:e?.colors?.header||S},Ut={fontSize:`${Be}px`,color:e?.colors?.input_labels_placeholders||"#6b7280"},Hn={backgroundColor:E,borderColor:t?Z:P,borderRadius:`${le}px`,color:G},Pe={backgroundColor:N,color:I,borderRadius:`${fe}px`},et=e?.widget?.logo_position||"center",K=et==="left"?"text-left":et==="right"?"text-right":"text-center",vt=e?.widget?.logo_url||n?.logo_url,il=et!=="none"&&vt;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",a),children:[p("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:p("div",{className:"flex items-start gap-3",children:[p("span",{className:"text-lg leading-none",children:"⚠️"}),p("div",{children:[p("strong",{children:y.t("incognito_mode_detected")}),p("p",{className:"mt-1 text-xs opacity-90",children:y.t("incognito_mode_warning")})]})]})}),c&&p("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:p("div",{className:"flex items-start gap-3",children:[p("span",{className:"text-lg leading-none",children:"⚠️"}),p("div",{children:[p("strong",{children:y.t("embedded_browser_detected")}),p("p",{className:"mt-1 text-xs opacity-90",children:y.t("embedded_browser_warning",{browserName:l||"the app"})})]})]})}),p(en,{style:Qe,className:"border",children:[p(tn,{children:[il&&p("div",{className:Q("mb-4",K),children:p(Rt,{theme:e,branding:n})}),p(nn,{style:Lt,children:y.t("welcome","Login")}),p(rn,{style:Ut,children:w?y.t("login_description_template",{authMethod:y.t(k,{defaultValue:u&&f?"email or phone number":u?"email address":"phone number"}).toLocaleLowerCase(),defaultValue:"Enter your {{authMethod}} below to login to your account"}):y.t("login_description_social_only","Choose how to login")})]}),p(on,{children:p("form",{method:"post",children:p("div",{className:"grid gap-6",children:[w&&p(bo,{children:[p("div",{className:"grid gap-2",children:[p(_t,{htmlFor:"username",style:Ut,children:y.t(k,u&&f?"Email or Phone Number":u?"Email":"Phone Number")}),p(Pt,{id:"username",name:"username",type:"text",placeholder:z,required:!0,value:i||"",error:!!t,className:"border lowercase",style:Hn}),t&&p(Re,{children:t})]}),p(Jt,{type:"submit",className:"w-full transition-colors hover:brightness-90",style:Pe,children:y.t("continue","Continue")})]}),_.length>0&&p(bo,{children:[w&&p("div",{className:"relative text-center",style:{color:e?.colors?.input_labels_placeholders||"#6b7280",fontSize:`${Be}px`},children:[p("div",{className:"absolute left-0 right-0 top-1/2 border-b",style:{borderColor:M}}),p("div",{className:"relative inline-block px-2",style:{backgroundColor:W},children:y.t("or","Or")})]}),p("div",{className:"flex gap-4 sm:flex-col short:flex-row",children:_.map(ne=>{const Vn=ne.logo;return p("a",{href:`/authorize/redirect?state=${r.id}&connection=${ne.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:P,borderRadius:`${fe}px`,color:S},children:[p(Vn,{className:"h-5 w-5",iconUrl:ne.iconUrl}),p("span",{className:"sm:inline short:hidden",children:y.t("continue_with","Login with {{provider}}",{provider:ne.displayName})}),p("span",{className:"hidden short:inline",children:ne.displayName})]},ne.connectionName)})})]})]})})})]})]})},H1=t=>p("div",{className:"mt-8",children:t.client?.client_metadata?.termsAndConditionsUrl&&p("div",{className:"text-xs text-gray-300",children:[y.t("agree_to")," ",p("a",{href:t.client.client_metadata.termsAndConditionsUrl,className:"text-primary hover:underline",target:"_blank",rel:"noreferrer",children:y.t("terms")})]})}),Q8=t=>t==="small"?"text-base":t==="medium"?"text-2xl":t==="large"?"text-3xl":"",Ne=({name:t,size:e,className:n=""})=>{const r=Q8(e);return p("span",{className:Q(`uicon-${t}`,n,r)})},ex=(t,e)=>{const n=t.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)*e)),l=Math.min(255,Math.round(s+(255-s)*e)),d=Math.min(255,Math.round(a+(255-a)*e));return`#${(c<<16|l<<8|d).toString(16).padStart(6,"0")}`},tx=(t,e)=>{const n=t?.colors?.primary_button||e?.colors?.primary||"#000000",r=t?.colors?.base_hover_color||ex(n,.2),i=t?.colors?.primary_button_label||"#ffffff";return`
86
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function y8(t,e){if(t){if(typeof t=="string")return s0(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?s0(t,e):void 0}}function s0(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function w8(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,i,s,a,c=[],l=!0,d=!1;try{if(s=(n=n.call(t)).next,e!==0)for(;!(l=(r=s.call(n)).done)&&(c.push(r.value),c.length!==e);l=!0);}catch(u){d=!0,i=u}finally{try{if(!l&&n.return!=null&&(a=n.return(),Object(a)!==a))return}finally{if(d)throw i}}return c}}function b8(t){if(Array.isArray(t))return t}function v8(t){var e=Array.prototype.slice.call(t),n=m8(e,4),r=n[0],i=n[1],s=n[2],a=n[3],c,l,d;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,d=a):(l=void 0,d=s),i&&(l=p8({defaultCountry:i},l));else if(Kr(i))s?(l=i,d=s):d=i;else throw new Error("Invalid second argument: ".concat(i));return{text:c,options:l,metadata:d}}function Lo(t){"@babel/helpers - typeof";return Lo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Lo(t)}function a0(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),n.push.apply(n,r)}return n}function c0(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?a0(Object(n),!0).forEach(function(r){$8(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):a0(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function $8(t,e,n){return(e=k8(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function k8(t){var e=x8(t,"string");return Lo(e)=="symbol"?e:e+""}function x8(t,e){if(Lo(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(Lo(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function S8(t,e,n){e&&e.defaultCountry&&!E5(e.defaultCountry,n)&&(e=c0(c0({},e),{},{defaultCountry:void 0}));try{return u8(t,e,n)}catch(r){if(!(r instanceof an))throw r}}function z8(){var t=v8(arguments),e=t.text,n=t.options,r=t.metadata;return S8(e,n,r)}function A8(){return m5(z8,arguments)}function nl(t,e="US"){const n=t.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=A8(n,{defaultCountry:e});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:"auth2"}}function qp(t){let e=t.trim();e.startsWith("[")&&e.endsWith("]")&&(e=e.slice(1,-1));const n=e.indexOf("%");return n!==-1&&(e=e.slice(0,n)),e}function E8(t){const n=qp(t).split(".");return n.length!==4?!1:n.every(r=>/^\d+$/.test(r)&&Number(r)>=0&&Number(r)<=255)}function C8(t){const e=qp(t);if(e.length<2||e.indexOf(":")===-1||!/^[0-9a-fA-F:.]+$/.test(e))return!1;const n=e.split(":");return e.includes("::")?n.length<=8:n.length===8}function N8(t){let e=t.trim();const n=/^\[([^\]]+)\](?::\d+)?$/,r=e.match(n);if(r&&r[1])return r[1];const i=e.lastIndexOf(":");if(i!==-1){const s=e.slice(0,i),a=e.slice(i+1);/^[0-9.]+$/.test(s)&&/^\d+$/.test(a)&&(e=s)}return e}function l0(t){if(!t)return null;const e=qp(N8(t));return E8(e)?{family:4,normalized:e}:C8(e)?{family:6,normalized:e.toLowerCase()}:null}function d0(t){if(t.includes("::")){let[e,n]=t.split("::"),r=e?e.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 t.split(":").map(e=>e.toLowerCase()||"0")}function I8(t,e,n=!0){const r=l0(t),i=l0(e);if(!r||!i||r.family!==i.family)return!1;if(r.family===4)return r.normalized===i.normalized;const s=d0(r.normalized),a=d0(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 vr extends Error{location;status;constructor(e,n=302){super(`Redirect to ${e}`),this.name=vr.name,this.location=e,this.status=n}}const j8=o.z.object({client_id:o.z.string(),username:o.z.string().transform(t=>t.toLowerCase()),otp:o.z.string(),authParams:mo.optional(),enforceIpCheck:o.z.boolean().optional().default(!1)});async function B1(t,{client_id:e,username:n,otp:r,authParams:i,enforceIpCheck:s=!1}){const a=t.get("ip"),c=t.get("countryCode"),{connectionType:l,normalized:d}=nl(n,c);if(!d)throw new B(400,{message:"Invalid username format"});const u=await t.env.data.legacyClients.get(e);if(!u)throw new B(403,{message:"Client not found"});const{env:f}=t,g=await f.data.codes.get(u.tenant.id,r,"otp");if(!g)throw new B(400,{message:X("code_invalid")});if(g.expires_at<new Date().toISOString())throw new B(400,{message:X("code_expired")});if(g.used_at)throw new B(400,{message:X("code_used")});const _=await f.data.loginSessions.get(u.tenant.id,g.login_id);if(!_||_.authParams.username!==n)throw new B(400,{message:"Code not found or expired"});if(s&&_.ip&&a&&!I8(_.ip,a))throw new vr(`${De(t.env)}invalid-session?state=${_.id}`);const w=await nc(t,{client:u,username:d,provider:l,connection:l,isSocial:!1,ip:t.var.ip});return await f.data.codes.used(u.tenant.id,r),{user:w,client:u,loginSession:_,session_id:_.session_id,authParams:{..._.authParams,...i||{}}}}async function Fp(t,e){const n=await B1(t,e);return Gt(t,{authParams:n.authParams,client:n.client,user:n.user,loginSession:n.loginSession,authStrategy:{strategy:"email",strategy_type:"passwordless"}})}const u0=o.z.object({client_id:o.z.string().optional(),client_secret:o.z.string().optional()}),p0=o.z.union([E1.extend(u0.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(),...u0.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 P8(t){if(!t)return{};const[e,n]=t.split(" ");if(e?.toLowerCase()==="basic"&&n){const[r,i]=atob(n).split(":");return{client_id:r,client_secret:i}}return{}}const O8=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:p0},"application/json":{schema:p0}}}},responses:{200:{content:{"application/json":{schema:Iu}},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 t=>{const n=(t.req.header("Content-Type")||"").includes("application/json")?t.req.valid("json"):t.req.valid("form"),r=P8(t.req.header("Authorization")),i={...n,...r};if(!i.client_id)throw new v(400,{message:"client_id is required"});t.set("client_id",i.client_id);let s;switch(n.grant_type){case St.AuthorizationCode:s=await p5(t,u5.parse(i));break;case St.ClientCredential:s=await d5(t,E1.parse(i));break;case St.RefreshToken:s=await h5(t,f5.parse(i));break;case St.OTP:s=await B1(t,j8.parse(i));break;default:return t.json({error:"unsupported_grant_type",error_description:"Grant type not implemented"},400)}const a=new Headers;if(s.session_id){const d=ta(s.client.tenant.id,s.session_id,t.var.host||"");a.set("Set-Cookie",d)}let c=[];if(s.authParams.audience)try{let d;if(n.grant_type===St.ClientCredential)d=await na(t,{grantType:St.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 B(400,{error:"invalid_request",error_description:"User ID is required for user-based grants"});d=await na(t,{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=d.scopes.join(" "),c=d.permissions}catch(d){if(d instanceof v)throw d;console.error("Error calculating scopes and permissions:",d)}const l=await Ya(t,{...s,grantType:n.grant_type,permissions:c.length>0?c:void 0});return t.json(l,{headers:a})}),kn={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 Ht extends Error{code;params;constructor(e,n,r){super(n),this.code=e,this.params=r,this.name="PasswordPolicyError"}}async function Hp(t,e){const{newPassword:n,userData:r,data:i,tenantId:s,userId:a}=e,c=t.passwordPolicy!==void 0||t.password_complexity_options!==void 0||t.password_history!==void 0||t.password_no_personal_info!==void 0||t.password_dictionary!==void 0,l=c?t.passwordPolicy:"good",d=c?t.password_complexity_options?.min_length:8;if(d&&n.length<d)throw new Ht(kn.TOO_SHORT,`Password must be at least ${d} characters`,{minLength:d});if(l&&l!=="none"&&l==="good"){if(!/[a-z]/.test(n))throw new Ht(kn.MISSING_LOWERCASE,"Password must contain at least one lowercase letter");if(!/[A-Z]/.test(n))throw new Ht(kn.MISSING_UPPERCASE,"Password must contain at least one uppercase letter");if(!/\d/.test(n))throw new Ht(kn.MISSING_NUMBER,"Password must contain at least one number");if(!/[^A-Za-z0-9]/.test(n))throw new Ht(kn.MISSING_SPECIAL,"Password must contain at least one special character")}if(t.password_history?.enable){const u=t.password_history.size||5,f=await i.passwords.list(s,a,u);for(const g of f)if(await Pn.compare(n,g.password))throw new Ht(kn.REUSED,"Password was used recently and cannot be reused",{historySize:u})}if(t.password_no_personal_info?.enable&&r&&[r.email,r.name].filter(Boolean).join(" ").toLowerCase().includes(n.toLowerCase()))throw new Ht(kn.CONTAINS_PERSONAL_INFO,"Password cannot contain personal information like your name or email");if(t.password_dictionary?.enable&&t.password_dictionary.dictionary&&t.password_dictionary.dictionary.some(u=>n.toLowerCase().includes(u.toLowerCase())))throw new Ht(kn.CONTAINS_FORBIDDEN_WORD,"Password contains a forbidden word")}async function Vp(t,e,n){return(await t.connections.get(e,n))?.options||{}}async function us(t,e){const n=await t.env.data.emailProviders.get(t.var.tenant_id)||(t.env.DEFAULT_TENANT_ID?await t.env.data.emailProviders.get(t.env.DEFAULT_TENANT_ID):null);if(!n)throw new v(500,{message:"Email provider not found"});const r=t.env.emailProviders?.[n.name];if(!r)throw new v(500,{message:"Email provider not found"});await r({emailProvider:n,...e,from:n.default_from_address||`login@${t.env.ISSUER}`})}async function L1(t,e){if(!t.var.client_id)throw new v(500,{message:"Client not found"});const n=await Ai(t.env,t.var.client_id),r=n.connections.find(a=>a.strategy==="sms");if(!r)throw new v(500,{message:"SMS provider not found"});const i=r.options?.provider||"twilio",s=t.env.smsProviders?.[i];if(!s)throw new v(500,{message:"SMS provider not found"});await s({options:r.options,to:e.to,from:e.from,text:e.text,template:"auth-code",data:{code:e.code,tenantName:n.tenant.friendly_name,tenantId:n.tenant.id}})}async function U1(t,e,n,r,i){const s=await t.env.data.tenants.get(t.var.tenant_id);if(!s)throw new v(500,{message:"Tenant not found"});const a=`${De(t.env)}reset-password?state=${r}&code=${n}`,c=await t.env.data.branding.get(t.var.tenant_id),l=c?.logo_url||"",d=c?.colors?.primary||"#7d68f4",u={vendorName:s.friendly_name,lng:"en"};await us(t,{to:e,subject:X("reset_password_title",u),html:`Click here to reset your password: ${De(t.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:d,passwordResetTitle:X("password_reset_title",u),resetPasswordEmailClickToReset:X("reset_password_email_click_to_reset",u),resetPasswordEmailReset:X("reset_password_email_reset",u),supportInfo:X("support_info",u),contactUs:X("contact_us",u),copyright:X("copyright",u),tenantName:s.friendly_name,tenantId:s.id}}),ie(t,s.id,{type:te.SUCCESS_CHANGE_PASSWORD_REQUEST,description:e})}async function Kp(t,{to:e,code:n,language:r}){const i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new v(500,{message:"Tenant not found"});const{connectionType:s}=nl(e),a=await t.env.data.branding.get(t.var.tenant_id),c=a?.logo_url||"",l=a?.colors?.primary||"#7d68f4",d=new URL(De(t.env)),u={vendorName:i.friendly_name,vendorId:i.id,loginDomain:d.hostname,code:n,lng:r||"en"};s==="email"?await us(t,{to:e,subject:X("code_email_subject",u),html:`Click here to validate your email: ${De(t.env)}validate-email`,template:"auth-code",data:{code:n,vendorName:i.friendly_name,logo:c,supportUrl:i.support_url||"",buttonColor:l,welcomeToYourAccount:X("welcome_to_your_account",u),linkEmailClickToLogin:X("link_email_click_to_login",u),linkEmailLogin:X("link_email_login",u),linkEmailOrEnterCode:X("link_email_or_enter_code",u),codeValid30Mins:X("code_valid_30_minutes",u),supportInfo:X("support_info",u),contactUs:X("contact_us",u),copyright:X("copyright",u)}}):s==="sms"&&await L1(t,{to:e,text:X("sms_code_text",u),code:n,from:i.friendly_name}),ie(t,i.id,{type:te.CODE_LINK_SENT,description:e})}async function Gp(t,{to:e,code:n,authParams:r,language:i}){const s=await t.env.data.tenants.get(t.var.tenant_id);if(!s)throw new v(500,{message:"Tenant not found"});if(!r.redirect_uri)throw new v(400,{message:"redirect_uri is required"});const{connectionType:a}=nl(e),c=await t.env.data.branding.get(t.var.tenant_id),l=c?.logo_url||"",d=c?.colors?.primary||"",u=new URL(me(t.env));u.pathname="passwordless/verify_redirect",u.searchParams.set("verification_code",n),u.searchParams.set("connection",a),u.searchParams.set("client_id",r.client_id),u.searchParams.set("redirect_uri",r.redirect_uri),u.searchParams.set("email",e),r.response_type&&u.searchParams.set("response_type",r.response_type),r.scope&&u.searchParams.set("scope",r.scope),r.state&&u.searchParams.set("state",r.state),r.nonce&&u.searchParams.set("nonce",r.nonce),r.code_challenge&&u.searchParams.set("code_challenge",r.code_challenge),r.code_challenge_method&&u.searchParams.set("code_challenge_method",r.code_challenge_method),r.audience&&u.searchParams.set("audience",r.audience);const f={vendorName:s.friendly_name,code:n,lng:i||"en"};if(a==="email")await us(t,{to:e,subject:X("code_email_subject",f),html:`Click here to validate your email: ${De(t.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:s.friendly_name,logo:l,supportUrl:s.support_url||"",magicLink:u.toString(),buttonColor:d,welcomeToYourAccount:X("welcome_to_your_account",f),linkEmailClickToLogin:X("link_email_click_to_login",f),linkEmailLogin:X("link_email_login",f),linkEmailOrEnterCode:X("link_email_or_enter_code",f),codeValid30Mins:X("code_valid_30_minutes",f),supportInfo:X("support_info",f),contactUs:X("contact_us",f),copyright:X("copyright",f)}});else if(a==="sms")await L1(t,{to:e,text:`${X("link_sms_login",f)}: ${u.toString()}`,code:n,from:s.friendly_name});else throw new v(400,{message:"Only email and SMS connections are supported for magic links"});ie(t,s.id,{type:te.CODE_LINK_SENT,description:e})}async function Wp(t,e,n){const r=await t.env.data.tenants.get(t.var.tenant_id);if(!r)throw new v(500,{message:"Tenant not found"});if(!e.email)throw new v(400,{message:"User has no email"});const i=await t.env.data.branding.get(t.var.tenant_id),s=i?.logo_url||"",a=i?.colors?.primary||"#7d68f4",c={vendorName:r.friendly_name,lng:n||"en"};await us(t,{to:e.email,subject:X("welcome_to_your_account",c),html:`Click here to validate your email: ${De(t.env)}validate-email`,template:"auth-verify-email",data:{vendorName:r.friendly_name,logo:s,emailValidationUrl:`${De(t.env)}validate-email`,supportUrl:r.support_url||"https://support.sesamy.com",buttonColor:a,welcomeToYourAccount:X("welcome_to_your_account",c),verifyEmailVerify:X("verify_email_verify",c),supportInfo:X("support_info",c),contactUs:X("contact_us",c),copyright:X("copyright",c)}})}async function T8(t,e,n,r,i){const s=await t.env.data.tenants.get(t.var.tenant_id);if(!s)throw new v(500,{message:"Tenant not found"});const a=await t.env.data.branding.get(t.var.tenant_id),c=a?.logo_url||"",l=a?.colors?.primary||"#7d68f4",d={vendorName:s.friendly_name,lng:"en"},u=`${De(t.env)}signup?state=${r}&code=${n}`;await us(t,{to:e,subject:X("register_password_account",d),html:`Click here to register: ${u}`,template:"auth-pre-signup-verification",data:{vendorName:s.friendly_name,logo:c,signupUrl:u,setPassword:X("set_password",d),registerPasswordAccount:X("register_password_account",d),clickToSignUpDescription:X("click_to_sign_up_description",d),supportUrl:s.support_url||"https://support.sesamy.com",buttonColor:l,welcomeToYourAccount:X("welcome_to_your_account",d),verifyEmailVerify:X("verify_email_verify",d),supportInfo:X("support_info",d),contactUs:X("contact_us",d),copyright:X("copyright",d)}})}const R8=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(t=>t.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 t=>{const{email:e,password:n,client_id:r}=t.req.valid("json"),i=await t.env.data.legacyClients.get(r);if(!i)throw new v(400,{message:"Client not found"});t.set("client_id",i.client_id),t.set("tenant_id",i.tenant.id);const a=i.connections.find(f=>f.strategy==="Username-Password-Authentication")?.name||"Username-Password-Authentication",c=await Vp(t.env.data,i.tenant.id,a);try{await Hp(c,{tenantId:i.tenant.id,userId:"",newPassword:n,data:t.env.data})}catch(f){throw new v(400,{message:f?.message||"Password does not meet the requirements"})}if(await Jr({userAdapter:t.env.data.users,tenant_id:i.tenant.id,username:e,provider:"auth2"}))throw new v(400,{message:"Invalid sign up"});const d=await t.env.data.users.create(i.tenant.id,{user_id:`auth2|${Xa()}`,email:e,email_verified:!1,provider:"auth2",connection:"Username-Password-Authentication",is_social:!1});t.set("user_id",d.user_id),t.set("username",d.email),t.set("connection",d.connection);const u=await Pn.hash(n,10);return await t.env.data.passwords.create(i.tenant.id,{user_id:d.user_id,password:u,algorithm:"bcrypt",is_current:!0}),await Wp(t,d),ie(t,i.tenant.id,{type:te.SUCCESS_SIGNUP,description:"Successful signup"}),t.json({_id:d.user_id,email:d.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(t=>t.toLowerCase())})}}}},responses:{200:{description:"Redirect to the client's redirect uri"}}}),async t=>{const{email:e,client_id:n}=t.req.valid("json"),r=await t.env.data.legacyClients.get(n);if(!r)throw new v(400,{message:"Client not found"});if(t.set("client_id",r.client_id),t.set("tenant_id",r.tenant.id),!await fi({userAdapter:t.env.data.users,tenant_id:r.tenant.id,username:e,provider:"auth2"}))return t.html("If an account with that email exists, we've sent instructions to reset your password.");const s={client_id:n,username:e},a=await t.env.data.loginSessions.create(r.tenant.id,{expires_at:new Date(Date.now()+or*1e3).toISOString(),authParams:s,csrf_token:pe(),ip:t.get("ip"),useragent:t.get("useragent"),auth0Client:mn(t.get("auth0_client"))});return await U1(t,e,a.id,a.authParams.state),t.html("If an account with that email exists, we've sent instructions to reset your password.")});function Ln(){const t="1234567890";let e="";for(let n=0;n<6;n+=1)e+=t[Math.floor(Math.random()*10)];return e.toString()}const B8=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(t=>t.toLowerCase()),send:o.z.enum(["link","code"]),authParams:mo.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:mo.omit({client_id:!0})})])}}}},responses:{200:{description:"Status"}}}),async t=>{const e=t.req.valid("json"),{env:n}=t,{client_id:r,send:i,authParams:s,connection:a}=e,c=await t.env.data.legacyClients.get(r);if(!c)throw new v(400,{message:"Client not found"});t.set("client_id",c.client_id),t.set("tenant_id",c.tenant.id);const l=a==="email"?e.email:e.phone_number,d=t.get("ip"),u=t.get("useragent"),f=t.get("auth0_client"),g=mn(f),_=await n.data.loginSessions.create(c.tenant.id,{authParams:{...s,client_id:r,username:l},expires_at:new Date(Date.now()+As).toISOString(),csrf_token:pe(),ip:d,useragent:u,auth0Client:g}),w=await n.data.codes.create(c.tenant.id,{code_id:Ln(),code_type:"otp",login_id:_.id,expires_at:new Date(Date.now()+As).toISOString(),redirect_uri:s.redirect_uri}),k=s?.ui_locales?.split(" ")?.map(z=>z.split("-")[0])[0];return i==="link"?await Gp(t,{to:l,code:w.code_id,authParams:{...s,client_id:r},language:k}):await Kp(t,{to:l,code:w.code_id,language:k}),t.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(mt),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(t=>t.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 t=>{const{env:e}=t,{client_id:n,email:r,verification_code:i,redirect_uri:s,state:a,scope:c,audience:l,response_type:d,nonce:u}=t.req.valid("query"),f=await Ai(e,n);t.set("client_id",f.client_id),t.set("tenant_id",f.tenant.id),t.set("connection","email");const g={client_id:n,redirect_uri:s,state:a,nonce:u,scope:c,audience:l,response_type:d};let _="Something went wrong. Please try again later.";try{const S=await Fp(t,{client_id:n,username:r,otp:i,authParams:g,enforceIpCheck:!0});if(S instanceof Response)return S;if(S&&typeof S=="object"&&"access_token"in S)return t.json(S)}catch(S){const E=S;"message"in E&&typeof E.message=="string"&&(_=E.message)}const w=t.get("ip"),k=t.get("useragent"),z=t.get("auth0_client"),N=mn(z),I=await e.data.loginSessions.create(f.tenant.id,{authParams:{...g,username:r},expires_at:new Date(Date.now()+As).toISOString(),csrf_token:pe(),ip:w,useragent:k,auth0Client:N});return t.redirect(`${De(t.env)}invalid-session?state=${I.id}&error=${encodeURIComponent(_)}`,302)});class Tr extends v{_code;constructor(e,n){super(e,n),this._code=n?.code}get code(){return this._code}}async function L8(t,e,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 t.users.update(e,n.user_id,{app_metadata:r})}function U8(t){const n=(t.app_metadata||{}).failed_logins||[],r=Date.now();return n.filter(i=>r-i<1e3*60*5)}async function D1(t,e,n,r){const{data:i}=t.env,{username:s}=n;if(t.set("username",s),!s)throw new B(400,{message:"Username is required"});const a=await fi({userAdapter:t.env.data.users,tenant_id:e.tenant.id,username:s,provider:"auth2"});if(!a)throw ie(t,e.tenant.id,{type:te.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"}),new Tr(403,{message:"User not found",code:"USER_NOT_FOUND"});const c=a.linked_to?await i.users.get(e.tenant.id,a.linked_to):a;if(!c)throw new Tr(403,{message:"User not found",code:"USER_NOT_FOUND"});if(t.set("connection",a.connection),t.set("user_id",c.user_id),U8(c).length>=3)throw ie(t,e.tenant.id,{type:te.FAILED_LOGIN,description:"Too many failed login attempts"}),new Tr(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"});const d=await i.passwords.get(e.tenant.id,a.user_id);if(!(d&&await Pn.compare(n.password,d.password)))throw ie(t,e.tenant.id,{type:te.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"}),L8(i,e.tenant.id,c),new Tr(403,{message:"Invalid password",code:"INVALID_PASSWORD"});if(!a.email_verified&&e.client_metadata?.email_validation==="enforced"){const g=r?.authParams?.ui_locales?.split(" ")?.map(_=>_.split("-")[0])[0];throw await Wp(t,a,g),ie(t,e.tenant.id,{type:te.FAILED_LOGIN,description:"Email not verified"}),new Tr(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(e.tenant.id,c.user_id,{app_metadata:f})),{client:e,authParams:n,user:c,loginSession:r}}async function M1(t,e,n,r,i){const s=await D1(t,e,n,r);return Gt(t,{...s,ticketAuth:i,authStrategy:{strategy:"Username-Password-Authentication",strategy_type:"database"}})}async function D8(t,e,n,r){await nc(t,{client:e,username:n,provider:"auth2",connection:"Username-Password-Authentication",isSocial:!1,ip:t.var.ip});let i=Ln(),s=await t.env.data.codes.get(e.tenant.id,i,"password_reset");for(;s;)i=Ln(),s=await t.env.data.codes.get(e.tenant.id,i,"password_reset");const a=t.get("ip"),c=t.get("useragent"),l=t.get("auth0_client"),d=mn(l),u=await t.env.data.loginSessions.create(e.tenant.id,{expires_at:new Date(Date.now()+dv).toISOString(),authParams:{client_id:e.client_id,username:n},csrf_token:pe(),ip:a,useragent:c,auth0Client:d}),f=await t.env.data.codes.create(e.tenant.id,{code_id:i,code_type:"password_reset",login_id:u.id,expires_at:new Date(Date.now()+lv).toISOString()});await U1(t,n,f.code_id,r)}const M8=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(t=>t.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(t=>t.toLowerCase()),password:o.z.string(),realm:o.z.enum(["Username-Password-Authentication"]),scope:o.z.string().optional()})])}}}},responses:{200:{description:"List of tenants"}}}),async t=>{const e=t.req.valid("json"),{client_id:n,username:r}=e;t.set("username",r);const i=await t.env.data.legacyClients.get(n);if(!i)throw new v(400,{message:"Client not found"});t.set("client_id",n),t.set("tenant_id",i.tenant.id);const s=r.toLocaleLowerCase(),a=t.get("ip"),c=t.get("useragent"),l=t.get("auth0_client");let d;if("otp"in e)d=await Fp(t,{client_id:n,username:s,otp:e.otp});else if("password"in e){const u=await t.env.data.loginSessions.create(i.tenant.id,{expires_at:new Date(Date.now()+or*1e3).toISOString(),authParams:{client_id:n,username:s},csrf_token:pe(),ip:a,useragent:c,auth0Client:mn(l)});d=await M1(t,i,{username:s,password:e.password,client_id:n},u,!0)}else throw new v(400,{message:"Code or password required"});if(!(d instanceof Response))throw new v(500,{message:"Unexpected response from loginWithPassword"});return d});function q1(t,e){if(!t||e.length===0)return!1;const n=El(t)?.host??null;if(!n)return!1;for(const r of e){let i;if(r.startsWith("http://")||r.startsWith("https://")?i=El(r)?.host??null:i=El("https://"+r)?.host??null,n===i)return!0}return!1}function El(t){try{return new URL(t)}catch{return null}}async function q8({ctx:t,session:e,client:n,authParams:r,connection:i,login_hint:s}){const a=new URL(t.req.url);t.var.custom_domain&&(a.hostname=t.var.custom_domain);const{ip:c,auth0_client:l,useragent:d}=t.var,u=mn(l),f=await t.env.data.loginSessions.create(n.tenant.id,{expires_at:new Date(Date.now()+or*1e3).toISOString(),authParams:r,csrf_token:pe(),authorization_url:a.toString(),ip:c,useragent:d,auth0Client:u});if(e&&s){const g=await t.env.data.users.get(n.tenant.id,e.user_id);if(g?.email===s)return await t.env.data.loginSessions.update(n.tenant.id,f.id,{session_id:e.id}),Gt(t,{client:n,loginSession:{...f,session_id:e.id},authParams:r,user:g,sessionId:e.id})}if(i==="email"&&s){const g=Ln();return await t.env.data.codes.create(n.tenant.id,{code_id:g,code_type:"otp",login_id:f.id,expires_at:new Date(Date.now()+or*1e3).toISOString(),redirect_uri:r.redirect_uri}),await Gp(t,{code:g,to:s,authParams:r}),t.redirect(`/u/enter-code?state=${f.id}`)}return e?t.redirect(`/u/check-account?state=${f.id}`):t.redirect(`/u/login/identifier?state=${f.id}`)}function F8(t){if(t==="Username-Password-Authentication")return"auth2";if(t==="email")return"email";throw new B(403,{message:"Invalid realm"})}async function H8(t,e,n,r,i){const{env:s}=t;t.set("connection",i);const a=await s.data.codes.get(e,n,"ticket");if(!a||a.used_at)throw new B(403,{message:"Ticket not found"});const c=await s.data.loginSessions.get(e,a.login_id);if(!c||!c.authParams.username)throw new B(403,{message:"Session not found"});const l=await s.data.legacyClients.get(c.authParams.client_id);if(!l)throw new B(403,{message:"Client not found"});t.set("client_id",c.authParams.client_id),await s.data.codes.used(e,n);const d=F8(i),f=l.connections.find(k=>k.name===i)?.strategy||(d==="auth2"?"Username-Password-Authentication":"email"),g=f==="Username-Password-Authentication"?"database":"passwordless";let _=await nc(t,{username:c.authParams.username,provider:d,client:l,connection:i,isSocial:!1,ip:t.var.ip});t.set("username",_.email||_.phone_number),t.set("user_id",_.user_id);const w=await u_(t,{user:_,client:l,loginSession:c});return Gt(t,{authParams:{scope:c.authParams?.scope,...r},loginSession:c,sessionId:w.id,user:_,client:l,authStrategy:{strategy:f,strategy_type:g}})}async function V8({ctx:t,client:e,session:n,redirect_uri:r,state:i,nonce:s,code_challenge_method:a,code_challenge:c,audience:l,scope:d,response_type:u,organization:f}){const{env:g}=t,_=new URL(r),w=`${_.protocol}//${_.host}`;async function k(Z="Login required"){const W=new Headers;if(n){ie(t,e.tenant.id,{type:te.FAILED_SILENT_AUTH,description:Z});const M=r_(e.tenant.id,t.req.header("host"));W.set("set-cookie",M)}return Vl(t,w,JSON.stringify({error:"login_required",error_description:Z,state:i}),W)}if(!n||n?.expires_at&&new Date(n.expires_at)<new Date||n?.idle_expires_at&&new Date(n.idle_expires_at)<new Date)return k();t.set("user_id",n.user_id);const N=await g.data.users.get(e.tenant.id,n.user_id);if(!N)return console.error("User not found",n.user_id),k("User not found");t.set("username",N.email),t.set("connection",N.connection);const I=await g.data.loginSessions.create(e.tenant.id,{csrf_token:pe(),authParams:{client_id:e.client_id,audience:l,scope:d,state:i,nonce:s,response_type:u,redirect_uri:r,organization:f},expires_at:new Date(Date.now()+300*1e3).toISOString(),session_id:n.id,ip:t.var.ip,useragent:t.var.useragent}),S={client:e,authParams:{client_id:e.client_id,audience:l,code_challenge_method:a,code_challenge:c,scope:d,state:i,nonce:s,response_type:u,redirect_uri:r},user:N,session_id:n.id},E=u===mt.CODE?await l_(t,{user:N,client:e,authParams:S.authParams,login_id:I.id}):await Ya(t,S);await g.data.sessions.update(e.tenant.id,n.id,{used_at:new Date().toISOString(),last_interaction_at:new Date().toISOString(),login_session_id:I.id,device:{...n.device,last_ip:t.var.ip||"",last_user_agent:t.var.useragent||""},idle_expires_at:n.idle_expires_at?new Date(Date.now()+Za*1e3).toISOString():void 0}),ie(t,e.tenant.id,{type:te.SUCCESS_SILENT_AUTH,description:"Successful silent authentication"});const P=new Headers,G=ta(e.tenant.id,n.id,t.req.header("host"));return P.set("set-cookie",G),Vl(t,w,JSON.stringify({...E,state:i}),P)}const K8=["email","sms","Username-Password-Authentication"],G8=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:o.z.object({client_id:o.z.string(),vendor_id:o.z.string().optional(),redirect_uri:o.z.string(),scope:o.z.string().optional(),state:o.z.string(),prompt:o.z.string().optional(),response_mode:o.z.nativeEnum(Ct).optional(),response_type:o.z.nativeEnum(mt).optional(),audience:o.z.string().optional(),connection:o.z.string().optional(),nonce:o.z.string().optional(),max_age:o.z.string().optional(),login_ticket:o.z.string().optional(),code_challenge_method:o.z.nativeEnum(Ga).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().openapi({example:"signup",description:'Optional hint for the screen to show, like "signup" or "login".'}).optional(),ui_locales:o.z.string().optional()})},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:Iu}}},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 t=>{const{env:e}=t,{client_id:n,vendor_id:r,redirect_uri:i,scope:s,state:a,audience:c,nonce:l,connection:d,response_type:u,response_mode:f,code_challenge:g,code_challenge_method:_,prompt:w,login_ticket:k,realm:z,auth0Client:N,login_hint:I,ui_locales:S,organization:E}=t.req.valid("query");t.set("log","authorize");const P=await Ai(e,n);t.set("client_id",P.client_id),t.set("tenant_id",P.tenant.id);const G={redirect_uri:i.split("#")[0],scope:s,state:a,client_id:n,vendor_id:r,audience:c,nonce:l,prompt:w,response_type:u,response_mode:f,code_challenge:g,code_challenge_method:_,username:I,ui_locales:S,organization:E},Z=t.req.header("origin");if(Z&&!q1(Z,P.web_origins||[]))throw new v(403,{message:`Origin ${Z} not allowed`});if(G.redirect_uri){const fe=P.callbacks||[];if(t.var.host&&(fe.push(`${ic(t.env)}/*`),fe.push(`${De(t.env)}/*`)),!Tp(G.redirect_uri,fe,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new v(400,{message:`Invalid redirect URI - ${G.redirect_uri}`})}const W=Wr(P.tenant.id,t.req.header("cookie")),M=W?await e.data.sessions.get(P.tenant.id,W):void 0,ce=M&&!M.revoked_at?M:void 0;if(w=="none"){if(!u)throw new v(400,{message:"Missing response_type"});return V8({ctx:t,session:ce||void 0,redirect_uri:i,state:a,response_type:u,client:P,nonce:l,code_challenge_method:_,code_challenge:g,audience:c,scope:s,organization:E})}if(P.connections.length===1&&P.connections[0]&&!K8.includes(P.connections[0].strategy||""))return Lg(t,P,P.connections[0].name,G);if(d&&d!=="email")return Lg(t,P,d,G);if(k){const fe=await H8(t,P.tenant.id,k,G,z);return fe instanceof Response?fe:t.json(fe)}const le=await q8({ctx:t,client:P,authParams:G,session:ce||void 0,connection:d,login_hint:I});return le instanceof Response?le:t.json(le)}),W8=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 t=>{const{env:e}=t,{client_id:n,redirect_url:r,login_hint:i,screen_hint:s}=t.req.valid("query");t.set("log","account");const a=await Ai(e,n);t.set("client_id",a.client_id),t.set("tenant_id",a.tenant.id);const c={redirect_uri:r||t.req.url,client_id:n,username:i},l=t.req.header("origin");if(l&&!q1(l,a.web_origins||[]))throw new v(403,{message:`Origin ${l} not allowed`});if(c.redirect_uri){const I=a.callbacks||[];if(t.var.host&&(I.push(`${ic(t.env)}/*`),I.push(`${De(t.env)}/*`)),!Tp(c.redirect_uri,I,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new v(400,{message:`Invalid redirect URI - ${c.redirect_uri}`})}const d=Wr(a.tenant.id,t.req.header("cookie")),u=d?await e.data.sessions.get(a.tenant.id,d):void 0,f=u&&!u.revoked_at?u:void 0,g=new URL(t.req.url);t.var.custom_domain&&(g.hostname=t.var.custom_domain);const{ip:_,auth0_client:w,useragent:k}=t.var,z=mn(w),N=await e.data.loginSessions.create(a.tenant.id,{expires_at:new Date(Date.now()+or*1e3).toISOString(),authParams:c,csrf_token:pe(),authorization_url:g.toString(),ip:_,useragent:k,auth0Client:z});if(f){if(i&&(await e.data.users.get(a.tenant.id,f.user_id))?.email!==i)return t.redirect(`${De(t.env)}login/identifier?state=${encodeURIComponent(N.id)}`);if(await e.data.loginSessions.update(a.tenant.id,N.id,{session_id:f.id}),s==="change-email"){const S=new URL("/u/account/change-email",t.req.url);return S.searchParams.set("state",N.id),t.redirect(S.toString())}const I=new URL("/u/account",t.req.url);return I.searchParams.set("state",N.id),t.redirect(I.toString())}return t.redirect(`${De(t.env)}login/identifier?state=${encodeURIComponent(N.id)}`)});function J8(t){const e=new o.OpenAPIHono;e.use(async(r,i)=>{const s=qo(r,t.dataAdapter),a=t.dataAdapter.cache||ds({defaultTtlSeconds:0,maxEntries:100,cleanupIntervalMs:0}),c=t.dataAdapter.cache?300:0,l=Qc(s,{defaultTtl:c,cacheEntities:["tenants","connections","customDomains","clients","legacyClients","branding","themes","promptSettings","forms","resourceServers","roles","organizations","userRoles","userPermissions"],cache:a});return r.env.data=Xc(r,l),i()}),e.use("/oauth/token",M0({origin:r=>r||"",allowHeaders:["Tenant-Id","Content-Type","Auth0-Client","Upgrade-Insecure-Requests"],allowMethods:["POST"],maxAge:600})),e.use(Yc).use(Zc).use(Pp(e));const n=e.route("/v2/logout",a5).route("/userinfo",c5).route("/.well-known",l5).route("/oauth/token",O8).route("/dbconnections",R8).route("/passwordless",B8).route("/co/authenticate",M8).route("/authorize",G8).route("/account",W8).route("/callback",o5);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Oauth API"},security:[{oauth2:["openid","email","profile"]}]}),jp(n),n}async function he(t,e,n=!1){const{env:r}=t,i=await r.data.loginSessions.get(t.var.tenant_id||"",e);if(!i)throw new B(400,{message:"Login session not found"});t.set("loginSession",i);const s=await Ai(r,i.authParams.client_id);t.set("client_id",s.client_id),t.set("tenant_id",s.tenant.id);let a;try{a=ck(t,"auth_ui_style")}catch{a=void 0}let c=!1;t.req?.url&&(c=(new URL(t.req.url).searchParams.get("style")||a||"classic")==="shadcn");const l=await r.data.tenants.get(s.tenant.id);if(l){if(i.session_id&&!n){if(!i.authParams.redirect_uri)throw new B(400,{message:"Login session closed and no redirect URI available"});const g=new URL(i.authParams.redirect_uri);throw g.searchParams.set("error","access_denied"),g.searchParams.set("error_description","Login session closed"),i.authParams.state&&g.searchParams.set("state",i.authParams.state),new vr(g.toString(),302)}}else throw new B(400,{message:"Tenant not found"});const d=await r.data.themes.get(l.id,"default"),u=await r.data.branding.get(l.id),f=i.authParams?.ui_locales?.split(" ")?.map(g=>g.split("-")[0])?.find(g=>{if(Array.isArray(y.options.supportedLngs))return y.options.supportedLngs.includes(g)});return await y.changeLanguage(f||"en"),{theme:d,branding:u,client:s,tenant:l,loginSession:i,useShadcn:c}}async function $r(t,e){const{theme:n,branding:r,client:i,tenant:s,loginSession:a,useShadcn:c}=await he(t,e,!0),l=Wr(i.tenant.id,t.req.header("cookie")),d=l?await t.env.data.sessions.get(i.tenant.id,l):null;if(!d||!a.session_id)throw new vr(`/u/login/identifier?state=${encodeURIComponent(e)}`);const u=await t.env.data.sessions.get(i.tenant.id,a.session_id),f=await t.env.data.users.get(i.tenant.id,d.user_id);if(!f||u?.user_id!==d.user_id)throw new vr(`/u/login/identifier?state=${encodeURIComponent(e)}`);return{theme:n,branding:r,client:i,user:f,tenant:s,loginSession:a,session:u,useShadcn:c}}const Cl={"Username-Password-Authentication":"password",email:"email",sms:"sms"};async function X8(t,e,n,r,i){if(i==="password")return"password";if(i==="code")return r==="sms"?"sms":"email";const a=(r==="email"?await tc({userAdapter:t.env.data.users,tenant_id:e.tenant.id,email:n}):await Jr({userAdapter:t.env.data.users,tenant_id:e.tenant.id,username:n,provider:r==="sms"?"sms":"auth2"}))?.app_metadata?.strategy;if(a&&Cl[a])return Cl[a];const c=e.connections.map(d=>Cl[d.strategy]).filter(d=>d!==void 0);return c.length===1&&c[0]?c[0]:(await t.env.data.promptSettings.get(e.tenant.id)).password_first&&c.includes("password")?"password":r==="sms"?"sms":"email"}var Nl={exports:{}};var f0;function Z8(){return f0||(f0=1,(function(t){(function(){var e={}.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)e.call(s,c)&&s[c]&&(a=i(a,c));return a}function i(s,a){return a?s?s+" "+a:s+a:s}t.exports?(n.default=n,t.exports=n):window.classNames=n})()})(Nl)),Nl.exports}var Y8=Z8();const Q=O3(Y8),en=({children:t,className:e,style:n})=>p("div",{className:Q("rounded-lg border border-gray-200 bg-white shadow-sm dark:border-gray-700 dark:bg-gray-800",e),style:n,children:t}),tn=({children:t,className:e})=>p("div",{className:Q("flex flex-col space-y-1.5 p-6",e),children:t}),nn=({children:t,className:e,style:n})=>p("h3",{className:Q("text-2xl font-semibold leading-none tracking-tight",e),style:n,children:t}),rn=({children:t,className:e,style:n})=>p("p",{className:Q("text-sm text-gray-500 dark:text-gray-400",e),style:n,children:t}),on=({children:t,className:e})=>p("div",{className:Q("p-6 pt-0",e),children:t}),F1=({children:t,className:e})=>p("div",{className:Q("flex items-center p-6 pt-0",e),children:t}),Pt=({id:t,type:e="text",name:n,placeholder:r,className:i,required:s=!1,value:a,disabled:c=!1,error:l=!1,style:d})=>p("input",{id:t,type:e,name:n,placeholder:r,required:s,value:a,disabled:c,className:Q("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:d}),Jt=({children:t,className:e,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 p("button",{type:i,disabled:s,className:Q("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],e),style:a,children:t})},_t=({htmlFor:t,className:e,style:n,children:r})=>p("label",{for:t,className:Q("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",e),style:n,children:r}),Re=({children:t,className:e})=>p("div",{className:Q("mb-2 text-sm text-red",e),children:t}),Rt=({theme:t,branding:e})=>{const n=t?.widget?.logo_url||e?.logo_url;return n?p("div",{className:"inline-flex h-9 items-center",children:p("img",{src:n,className:"h-full w-auto",alt:"Logo"})}):p(bo,{})},Ts=({error:t,theme:e,branding:n,loginSession:r,email:i,client:s,className:a,isEmbedded:c,browserName:l})=>{const d=s.connections.map(({strategy:ne})=>ne),u=d.includes("email")||d.includes("Username-Password-Authentication"),f=d.includes("sms"),g=new Set(["email","sms","Username-Password-Authentication","auth0"]),_=s.connections.filter(ne=>!g.has(ne.strategy)).filter(ne=>ne.show_as_button!==!1).map(ne=>{const Vn=Fu[ne.strategy];return Vn?{...Vn,connectionName:ne.name,displayName:ne.display_name||Vn.displayName||ne.name,iconUrl:ne.options.icon_url}:null}).filter(ne=>ne!==null).filter(ne=>!(c&&ne.disableEmbeddedBrowsers)),w=u||f,k=u&&f?"email_or_phone_placeholder":u?"email_placeholder":f?"phone_placeholder":null,z=k?y.t(k,u&&f?"Email or Phone Number":u?"Email Address":"Phone Number"):"",N=e?.colors?.primary_button||n?.colors?.primary||"#0066cc",I=e?.colors?.primary_button_label||"#ffffff",S=e?.colors?.body_text||"#333333",E=e?.colors?.input_background||"#ffffff",P=e?.colors?.input_border||"#d1d5db",G=e?.colors?.input_filled_text||"#111827",Z=e?.colors?.error||"#dc2626",W=e?.colors?.widget_background||"#ffffff",M=e?.colors?.widget_border||"#e5e7eb",ce=e?.borders?.widget_corner_radius||8,le=e?.borders?.input_border_radius||4,fe=e?.borders?.button_border_radius||4,$e=e?.borders?.show_widget_shadow??!0,be=e?.fonts?.title?.size||24,sn=e?.fonts?.title?.bold??!0,Be=e?.fonts?.body_text?.size||14,Qe={backgroundColor:W,borderColor:M,borderRadius:`${ce}px`,boxShadow:$e?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:S},Lt={fontSize:`${be}px`,fontWeight:sn?"700":"400",color:e?.colors?.header||S},Ut={fontSize:`${Be}px`,color:e?.colors?.input_labels_placeholders||"#6b7280"},Hn={backgroundColor:E,borderColor:t?Z:P,borderRadius:`${le}px`,color:G},Pe={backgroundColor:N,color:I,borderRadius:`${fe}px`},et=e?.widget?.logo_position||"center",K=et==="left"?"text-left":et==="right"?"text-right":"text-center",vt=e?.widget?.logo_url||n?.logo_url,il=et!=="none"&&vt;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",a),children:[p("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:p("div",{className:"flex items-start gap-3",children:[p("span",{className:"text-lg leading-none",children:"⚠️"}),p("div",{children:[p("strong",{children:y.t("incognito_mode_detected")}),p("p",{className:"mt-1 text-xs opacity-90",children:y.t("incognito_mode_warning")})]})]})}),c&&p("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:p("div",{className:"flex items-start gap-3",children:[p("span",{className:"text-lg leading-none",children:"⚠️"}),p("div",{children:[p("strong",{children:y.t("embedded_browser_detected")}),p("p",{className:"mt-1 text-xs opacity-90",children:y.t("embedded_browser_warning",{browserName:l||"the app"})})]})]})}),p(en,{style:Qe,className:"border",children:[p(tn,{children:[il&&p("div",{className:Q("mb-4",K),children:p(Rt,{theme:e,branding:n})}),p(nn,{style:Lt,children:y.t("welcome","Login")}),p(rn,{style:Ut,children:w?y.t("login_description_template",{authMethod:y.t(k,{defaultValue:u&&f?"email or phone number":u?"email address":"phone number"}).toLocaleLowerCase(),defaultValue:"Enter your {{authMethod}} below to login to your account"}):y.t("login_description_social_only","Choose how to login")})]}),p(on,{children:p("form",{method:"post",children:p("div",{className:"grid gap-6",children:[w&&p(bo,{children:[p("div",{className:"grid gap-2",children:[p(_t,{htmlFor:"username",style:Ut,children:y.t(k,u&&f?"Email or Phone Number":u?"Email":"Phone Number")}),p(Pt,{id:"username",name:"username",type:"text",placeholder:z,required:!0,value:i||"",error:!!t,className:"border lowercase",style:Hn}),t&&p(Re,{children:t})]}),p(Jt,{type:"submit",className:"w-full transition-colors hover:brightness-90",style:Pe,children:y.t("continue","Continue")})]}),_.length>0&&p(bo,{children:[w&&p("div",{className:"relative text-center",style:{color:e?.colors?.input_labels_placeholders||"#6b7280",fontSize:`${Be}px`},children:[p("div",{className:"absolute left-0 right-0 top-1/2 border-b",style:{borderColor:M}}),p("div",{className:"relative inline-block px-2",style:{backgroundColor:W},children:y.t("or","Or")})]}),p("div",{className:"flex gap-4 sm:flex-col short:flex-row",children:_.map(ne=>{const Vn=ne.logo;return p("a",{href:`/authorize/redirect?state=${r.id}&connection=${ne.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:P,borderRadius:`${fe}px`,color:S},children:[p(Vn,{className:"h-5 w-5",iconUrl:ne.iconUrl}),p("span",{className:"sm:inline short:hidden",children:y.t("continue_with","Login with {{provider}}",{provider:ne.displayName})}),p("span",{className:"hidden short:inline",children:ne.displayName})]},ne.connectionName)})})]})]})})})]})]})},H1=t=>p("div",{className:"mt-8",children:t.client?.client_metadata?.termsAndConditionsUrl&&p("div",{className:"text-xs text-gray-300",children:[y.t("agree_to")," ",p("a",{href:t.client.client_metadata.termsAndConditionsUrl,className:"text-primary hover:underline",target:"_blank",rel:"noreferrer",children:y.t("terms")})]})}),Q8=t=>t==="small"?"text-base":t==="medium"?"text-2xl":t==="large"?"text-3xl":"",Ne=({name:t,size:e,className:n=""})=>{const r=Q8(e);return p("span",{className:Q(`uicon-${t}`,n,r)})},ex=(t,e)=>{const n=t.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)*e)),l=Math.min(255,Math.round(s+(255-s)*e)),d=Math.min(255,Math.round(a+(255-a)*e));return`#${(c<<16|l<<8|d).toString(16).padStart(6,"0")}`},tx=(t,e)=>{const n=t?.colors?.primary_button||e?.colors?.primary||"#000000",r=t?.colors?.base_hover_color||ex(n,.2),i=t?.colors?.primary_button_label||"#ffffff";return`
87
87
  body {
88
88
  --primary-color: ${n};
89
89
  --primary-hover: ${r};
90
90
  --text-on-primary: ${i};
91
91
  }
92
- `},nx="https://assets.sesamy.com/images/login-bg.jpg",Se=({title:t,children:e,theme:n,branding:r,client:i})=>{const s={backgroundImage:`url(${n?.page_background?.background_image_url||nx})`};return p("html",{lang:y.language||"en",children:[p("head",{children:[p("title",{children:t}),p("meta",{charset:"UTF-8"}),p("meta",{name:"robots",content:"noindex, follow"}),p("link",{rel:"preload",href:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Regular.woff2",as:"font",type:"font/woff2",crossOrigin:"anonymous"}),p("link",{rel:"preload",href:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Medium.woff2",as:"font",type:"font/woff2",crossOrigin:"anonymous"}),p("link",{rel:"preload",href:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Bold.woff2",as:"font",type:"font/woff2",crossOrigin:"anonymous"}),p("link",{rel:"stylesheet",href:"/u/css/tailwind.css"}),p("meta",{name:"viewport",content:"width=device-width, initial-scale=1, maximum-scale=1"}),p("style",{children:tx(n,r)}),p("meta",{name:"theme-color",content:"#000000"})]}),p("body",{children:[p("div",{className:"row min-h-full w-full overflow-hidden bg-cover bg-center text-sm sm:bg-fixed sm:bg-left-top sm:pt-16 py-2",style:s,children:p("div",{className:"row-up-left w-[calc(100%-theme(space.2)-theme(space.2))] max-w-[1295px] !flex-nowrap sm:w-[calc(100%-theme(space.16)-theme(space.16))]",children:p("div",{className:"column-left w-full sm:w-auto",children:[p("div",{className:"relative flex w-full flex-col rounded-2xl bg-white px-5 py-10 dark:bg-gray-800 dark:text-white sm:min-h-[700px] sm:max-w-md sm:px-14 sm:py-14 md:min-w-[448px] short:min-h-[558px] min-h-[calc(100vh-83px)]",children:[p("div",{className:"mb-16",children:p(Rt,{theme:n,branding:r})}),p("div",{className:"flex flex-1 flex-col",children:[e,p(H1,{theme:n,branding:r,client:i})]})]}),p("div",{className:"flex w-full items-center px-6 pb-8 pt-4 justify-between",children:[p("div",{className:"flex justify-center leading-[0]",children:p("a",{href:"https://sesamy.com",target:"_blank",rel:"noreferrer",children:p(Ne,{name:"sesamy",className:"text-xl text-white"})})}),p("div",{className:"flex justify-center space-x-2 text-xs text-white sm:justify-normal md:text-xs"})]})]})})}),p("div",{id:"client-root"})]}),p("script",{type:"module",src:"/u/js/client.js"})]})},rx=t=>t==="small"?"text-base":t==="medium"?"text-2xl":t==="large"?"text-3xl":"",V1=({size:t})=>{const e=rx(t);return p("div",{className:"relative inline-block leading-[0]",children:[p(Ne,{className:Q("text-gray-200 dark:text-[#201a41]",{[e]:e}),name:"spinner-circle"}),p(Ne,{className:Q("absolute inset-0 animate-spin text-primary",{[e]:e}),name:"spinner-inner"})]})},xe=({children:t,className:e,Component:n="button",variant:r="primary",href:i,disabled:s,isLoading:a,id:c})=>{const l=n==="a"?{href:i}:{};return p(n,{class:Q("btn relative w-full rounded-lg text-center",{"px-4 py-5":r!=="custom","bg-primary text-textOnPrimary hover:bg-primaryHover":r==="primary","border border-gray-300 bg-white text-black":r==="secondary","pointer-events-none cursor-not-allowed opacity-40":s,"is-loading":a},"focus:outline-none focus:ring",e),type:"submit",disabled:s,id:c,...l,children:[p("span",{className:"btn-label flex items-center justify-center space-x-2",children:t}),p("div",{className:"btn-spinner absolute left-0 top-0 flex h-full w-full items-center justify-center",children:p(V1,{size:"medium"})})]})},K1=({connection:t,text:e,icon:n=null,canResize:r=!1,loginSession:i})=>{const s=new URLSearchParams({client_id:i.authParams.client_id,connection:t});i.authParams.response_type&&s.set("response_type",i.authParams.response_type),i.authParams.redirect_uri&&s.set("redirect_uri",i.authParams.redirect_uri),i.authParams.scope&&s.set("scope",i.authParams.scope),i.authParams.nonce&&s.set("nonce",i.authParams.nonce),i.authParams.response_type&&s.set("response_type",i.authParams.response_type),i.authParams.state&&s.set("state",i.id);const a=`/authorize?${s.toString()}`;return p(xe,{className:Q("border border-gray-200 bg-white hover:bg-gray-100 dark:border-gray-400 dark:bg-black dark:hover:bg-black/90",{"px-0 py-3 sm:px-10 sm:py-4 short:px-0 short:py-3":r,"px-10 py-3":!r}),variant:"custom","aria-label":e,Component:"a",href:a,children:[n||"",p("div",{className:Q("text-left text-black dark:text-white sm:text-base",{"hidden sm:inline short:hidden":r}),children:e})]})},Bt=({children:t,className:e})=>p("form",{id:"form",method:"post",className:e,children:t}),Rs=({error:t,theme:e,branding:n,loginSession:r,email:i,client:s,isEmbedded:a,browserName:c})=>{const l=s.connections.map(({strategy:S})=>S),d=l.includes("email")||l.includes("Username-Password-Authentication"),u=l.includes("sms"),f=new Set(["email","sms","Username-Password-Authentication","auth0"]),g=s.connections.filter(S=>!f.has(S.strategy)).filter(S=>S.show_as_button!==!1).map(S=>{const E=Fu[S.strategy];return E?{...E,connectionName:S.name,displayName:S.display_name||E.displayName||S.name,iconUrl:S.options.icon_url}:null}).filter(S=>S!==null).filter(S=>!(a&&S.disableEmbeddedBrowsers)),_=d||u;let w="text",k="username";const z=d&&u?"email_or_phone_placeholder":d?"email_placeholder":"phone_placeholder";let N=y.t(z,d&&u?"Email or Phone Number":d?"Email Address":"Phone Number");return p(Se,{title:y.t("welcome"),theme:e,branding:n,client:s,children:[p("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:p("div",{className:"flex items-start gap-3",children:[p("span",{className:"text-lg leading-none",children:"⚠️"}),p("div",{children:[p("strong",{children:y.t("incognito_mode_detected","Incognito Mode Detected")}),p("p",{className:"mt-1 text-xs opacity-90",children:y.t("incognito_mode_warning","You are in incognito/private mode. Session data may not persist across page refreshes. Some features might not work as expected.")})]})]})}),a&&p("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:p("div",{className:"flex items-start gap-3",children:[p("span",{className:"text-lg leading-none",children:"⚠️"}),p("div",{children:[p("strong",{children:y.t("embedded_browser_detected")}),p("p",{className:"mt-1 text-xs opacity-90",children:y.t("embedded_browser_warning",{browserName:c||"app"})})]})]})}),p("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:y.t("welcome")}),p("div",{className:"mb-8 text-gray-300",children:_?y.t("login_description_template",{authMethod:y.t(z,{defaultValue:d&&u?"email or phone number":d?"email address":"phone number"}).toLocaleLowerCase(),defaultValue:"Sign in with your {{authMethod}}"}):y.t("login_description_social_only","Choose how to login")}),p("div",{className:"flex flex-1 flex-col justify-center",children:[_&&p(Bt,{className:"mb-7",children:[p("input",{type:w,name:k,placeholder:N,className:Q("mb-2 w-full rounded-lg border bg-gray-100 px-4 py-5 text-base lowercase placeholder:normal-case placeholder:text-gray-300 dark:bg-gray-600 md:text-base",{"border-red":t,"border-gray-100 dark:border-gray-500":!t}),required:!0,value:i||""}),t&&p(Re,{children:t}),p(xe,{className:"sm:mt-4 !text-base",children:[p("span",{children:y.t("continue")}),p(Ne,{className:"text-xs",name:"arrow-right"})]})]}),_&&g.length>0&&p("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[p("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),p("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:y.t("continue_social_login")})]}),p("div",{className:"flex space-x-4 sm:flex-col sm:space-x-0 sm:space-y-4 short:flex-row short:space-x-4 short:space-y-0",children:g.map(S=>{const E=S.logo;return p(K1,{connection:S.connectionName,text:y.t("continue_with",{provider:S.displayName}),canResize:!0,icon:p(E,{className:"h-5 w-5 sm:absolute sm:left-4 sm:top-1/2 sm:h-6 sm:w-6 sm:-translate-y-1/2 short:static short:left-auto short:top-auto short:h-5 short:w-5 short:translate-y-0",iconUrl:S.iconUrl}),loginSession:r},S.connectionName)})})]})]})},ix="https://assets.sesamy.com/images/login-bg.jpg",we=({title:t,children:e,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??ix,l=c?.startsWith("linear-gradient")||c?.startsWith("radial-gradient")||c?.startsWith("conic-gradient"),d=c?l?c:`url(${c})`:void 0;let u="justify-center",f="p-6 md:p-10";i==="left"?(u="justify-start",f="pl-12 pr-6 py-6 md:pl-20 md:pr-10 md:py-10"):i==="right"&&(u="justify-end",f="pr-12 pl-6 py-6 md:pr-20 md:pl-10 md:py-10");const g=Q("min-h-screen w-full flex bg-cover bg-center",u,f),_={...d&&{backgroundImage:d},backgroundColor:s,display:"flex",alignItems:"stretch",justifyContent:i==="left"?"flex-start":i==="right"?"flex-end":"center",minHeight:"100vh",width:"100%"},w=Q("w-full max-w-sm","flex flex-col justify-center");return p("html",{lang:y.language||"en",children:[p("head",{children:[p("title",{children:t}),p("meta",{charset:"UTF-8"}),p("meta",{name:"robots",content:"noindex, follow"}),p("link",{rel:"stylesheet",href:"/u/css/tailwind.css"}),p("link",{rel:"stylesheet",href:"/u/css/shadcn-ui.css"}),p("meta",{name:"viewport",content:"width=device-width, initial-scale=1, maximum-scale=1"}),p("meta",{name:"theme-color",content:"#000000"}),r?.favicon_url&&p("link",{rel:"icon",type:"image/x-icon",href:r.favicon_url}),n?.fonts?.font_url&&p("link",{rel:"stylesheet",href:n.fonts.font_url})]}),p("body",{children:[p("div",{className:g,style:_,children:p("div",{className:w,children:[e,r?.powered_by_logo_url&&p("div",{className:"mt-5 text-left",children:p("a",{href:"https://authhero.com",target:"_blank",rel:"noopener noreferrer",className:"inline-block",children:p("img",{src:r.powered_by_logo_url,alt:"Powered by",className:"h-9 opacity-60 hover:opacity-100 transition-opacity"})})})]})}),p("div",{id:"client-root"}),p("script",{type:"module",src:"/u/js/client.js"})]})]})};class ox{parse(e){const n=this.detectEmbedded(e);return{browser:n.browser,isEmbedded:n.isEmbedded}}detectEmbedded(e){const n=[[/wv\)/i,"WebView"],[/GSA\//i,"Google Search App"],[/FBAN\//i,"Facebook"],[/FBAV\//i,"Facebook"],[/Instagram/i,"Instagram"],[/Snapchat/i,"Snapchat"],[/TikTok/i,"TikTok"],[/Twitter/i,"Twitter/X"],[/LinkedIn/i,"LinkedIn"],[/UC Browser/i,"UC Browser"],[/SamsungBrowser/i,"Samsung Internet"],[/Electron/i,"Electron"],[/Tauri/i,"Tauri"]];for(const[r,i]of n)if(r.test(e))return{isEmbedded:!0,browser:{name:i}};return{isEmbedded:!1}}}function h0(t){const n=new ox().parse(t);return{isEmbedded:n.isEmbedded??!1,browserName:n.browser?.name}}const sx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),impersonation:o.z.string().optional()})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,loginSession:i,client:s,useShadcn:a}=await he(t,e),c=t.req.header("user-agent")||"",{isEmbedded:l,browserName:d}=h0(c);return a?t.html(p(we,{title:y.t("welcome","Login"),theme:n,branding:r,client:s,children:p(Ts,{theme:n,branding:r,loginSession:i,client:s,email:i.authParams.username,isEmbedded:l,browserName:d})})):t.html(p(Rs,{theme:n,branding:r,loginSession:i,client:s,email:i.authParams.username,isEmbedded:l,browserName:d}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),style:o.z.enum(["classic","shadcn"]).optional().openapi({description:"UI style to use for the login page"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({username:o.z.string().transform(t=>t.toLowerCase()),login_selection:o.z.enum(["code","password"]).optional()})}}}},responses:{400:{description:"Error response"},302:{description:"Redirect to enter code or password"}}}),async t=>{const{env:e}=t,{state:n}=t.req.valid("query"),r=t.req.valid("form");t.set("body",r),t.set("username",r.username);const{client:i,loginSession:s,theme:a,branding:c,useShadcn:l}=await he(t,n);t.set("client_id",i.client_id);const d=t.req.header("user-agent")||"",{isEmbedded:u,browserName:f}=h0(d),g=t.get("countryCode"),{normalized:_,connectionType:w,provider:k}=nl(r.username,g),z=_?w==="email"?await tc({userAdapter:e.data.users,tenant_id:i.tenant.id,email:_}):await yo({userAdapter:e.data.users,tenant_id:i.tenant.id,username:_,provider:k}):null;if(!(i.connections.find(W=>W.strategy===w)||z)||!_)return l?t.html(p(we,{title:y.t("welcome","Login"),theme:a,branding:c,client:i,children:p(Ts,{theme:a,branding:c,loginSession:s,error:y.t("invalid_identifier"),email:r.username,client:i,isEmbedded:u,browserName:f})}),400):t.html(p(Rs,{theme:a,branding:c,loginSession:s,error:y.t("invalid_identifier"),email:r.username,client:i}),400);if(z&&t.set("user_id",z.user_id),!z){const W=await p_(t,i,t.env.data,_,w);if(!W.allowed)return await ie(t,i.tenant.id,{type:te.FAILED_SIGNUP,description:W.reason||"Public signup is disabled"}),l?t.html(p(we,{title:y.t("welcome","Login"),theme:a,branding:c,client:i,children:p(Ts,{theme:a,branding:c,loginSession:s,error:y.t("user_account_does_not_exist"),email:r.username,client:i,isEmbedded:u,browserName:f})}),400):t.html(p(Rs,{theme:a,branding:c,loginSession:s,error:y.t("user_account_does_not_exist"),email:r.username,client:i,isEmbedded:u,browserName:f}),400)}if(s.authParams.username=_,await e.data.loginSessions.update(i.tenant.id,s.id,s),await X8(t,i,r.username,w,r.login_selection)==="password")return t.redirect(`/u/enter-password?state=${n}`);let S=Ln(),E=await e.data.codes.get(i.tenant.id,S,"otp");for(;E;)S=Ln(),E=await e.data.codes.get(i.tenant.id,S,"otp");const P=await t.env.data.codes.create(i.tenant.id,{code_id:S,code_type:"otp",login_id:s.id,expires_at:new Date(Date.now()+As).toISOString(),redirect_uri:s.authParams.redirect_uri}),G=i.connections.find(W=>W.strategy===w);if(!G)throw new v(400,{message:y.t("connection_not_found",{connection:w})});const Z=s.authParams?.ui_locales?.split(" ")?.map(W=>W.split("-")[0])[0];return w==="email"&&G.options.authentication_method==="magic_link"?await Gp(t,{to:_,code:P.code_id,authParams:s.authParams,language:Z}):await Kp(t,{to:_,code:P.code_id,language:Z}),t.redirect(`/u/enter-code?state=${n}`)}),lt=t=>p("a",{className:"block text-primary hover:text-primaryHover text-center",href:`/u/login/identifier?state=${t.state}`,children:y.t("go_back")});var Uo="_hp",ax={Change:"Input",DoubleClick:"DblClick"},cx={svg:"2000/svg",math:"1998/Math/MathML"},Do=[],yu=new WeakMap,li=void 0,lx=()=>li,cn=t=>"t"in t,Il={onClick:["click",!1]},g0=t=>{if(!t.startsWith("on"))return;if(Il[t])return Il[t];const e=t.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(e){const[,n,r]=e;return Il[t]=[(ax[n]||n).toLowerCase(),!!r]}},m0=(t,e)=>li&&t instanceof SVGElement&&/[A-Z]/.test(e)&&(e in t.style||e.match(/^(?:o|pai|str|u|ve)/))?e.replace(/([A-Z])/g,"-$1").toLowerCase():e,dx=(t,e,n)=>{e||={};for(let r in e){const i=e[r];if(r!=="children"&&(!n||n[r]!==i)){r=ia(r);const s=g0(r);if(s){if(n?.[r]!==i&&(n&&t.removeEventListener(s[0],n[r],s[1]),i!=null)){if(typeof i!="function")throw new Error(`Event handler for "${r}" is not a function`);t.addEventListener(s[0],i,s[1])}}else if(r==="dangerouslySetInnerHTML"&&i)t.innerHTML=i.__html;else if(r==="ref"){let a;typeof i=="function"?a=i(t)||(()=>i(null)):i&&"current"in i&&(i.current=t,a=()=>i.current=null),yu.set(t,a)}else if(r==="style"){const a=t.style;typeof i=="string"?a.cssText=i:(a.cssText="",i!=null&&b_(i,a.setProperty.bind(a)))}else{if(r==="value"){const c=t.nodeName;if(c==="INPUT"||c==="TEXTAREA"||c==="SELECT"){if(t.value=i==null||i===!1?null:i,c==="TEXTAREA"){t.textContent=i;continue}else if(c==="SELECT"){t.selectedIndex===-1&&(t.selectedIndex=0);continue}}}else(r==="checked"&&t.nodeName==="INPUT"||r==="selected"&&t.nodeName==="OPTION")&&(t[r]=i);const a=m0(t,r);i==null||i===!1?t.removeAttribute(a):i===!0?t.setAttribute(a,""):typeof i=="string"||typeof i=="number"?t.setAttribute(a,i):t.setAttribute(a,i.toString())}}}if(n)for(let r in n){const i=n[r];if(r!=="children"&&!(r in e)){r=ia(r);const s=g0(r);s?t.removeEventListener(s[0],i,s[1]):r==="ref"?yu.get(t)?.():t.removeAttribute(m0(t,r))}}},ux=(t,e)=>{e[ke][0]=0,Do.push([t,e]);const n=e.tag[Bu]||e.tag,r=n.defaultProps?{...n.defaultProps,...e.props}:e.props;try{return[n.call(null,r)]}finally{Do.pop()}},G1=(t,e,n,r,i)=>{t.vR?.length&&(r.push(...t.vR),delete t.vR),typeof t.tag=="function"&&t[ke][1][Z1]?.forEach(s=>i.push(s)),t.vC.forEach(s=>{if(cn(s))n.push(s);else if(typeof s.tag=="function"||s.tag===""){s.c=e;const a=n.length;if(G1(s,e,n,r,i),s.s){for(let c=a;c<n.length;c++)n[c].s=!0;s.s=!1}}else n.push(s),s.vR?.length&&(r.push(...s.vR),delete s.vR)})},px=t=>{for(;;t=t.tag===Uo||!t.vC||!t.pP?t.nN:t.vC[0]){if(!t)return null;if(t.tag!==Uo&&t.e)return t.e}},W1=t=>{cn(t)||(t[ke]?.[1][Z1]?.forEach(e=>e[2]?.()),yu.get(t.e)?.(),t.p===2&&t.vC?.forEach(e=>e.p=2),t.vC?.forEach(W1)),t.p||(t.e?.remove(),delete t.e),typeof t.tag=="function"&&(eo.delete(t),Bs.delete(t),delete t[ke][3],t.a=!0)},J1=(t,e,n)=>{t.c=e,X1(t,e,n)},_0=(t,e)=>{if(e){for(let n=0,r=t.length;n<r;n++)if(t[n]===e)return n}},y0=Symbol(),X1=(t,e,n)=>{const r=[],i=[],s=[];G1(t,e,r,i,s),i.forEach(W1);const a=n?void 0:e.childNodes;let c,l=null;if(n)c=-1;else if(!a.length)c=0;else{const d=_0(a,px(t.nN));d!==void 0?(l=a[d],c=d):c=_0(a,r.find(u=>u.tag!==Uo&&u.e)?.e)??-1,c===-1&&(n=!0)}for(let d=0,u=r.length;d<u;d++,c++){const f=r[d];let g;if(f.s&&f.e)g=f.e,f.s=!1;else{const _=n||!f.e;cn(f)?(f.e&&f.d&&(f.e.textContent=f.t),f.d=!1,g=f.e||=document.createTextNode(f.t)):(g=f.e||=f.n?document.createElementNS(f.n,f.tag):document.createElement(f.tag),dx(g,f.props,f.pP),X1(f,g,_))}f.tag===Uo?c--:n?g.parentNode||e.appendChild(g):a[c]!==g&&a[c-1]!==g&&(a[c+1]===g?e.appendChild(a[c]):e.insertBefore(g,l||a[c]||null))}if(t.pP&&delete t.pP,s.length){const d=[],u=[];s.forEach(([,f,,g,_])=>{f&&d.push(f),g&&u.push(g),_?.()}),d.forEach(f=>f()),u.length&&requestAnimationFrame(()=>{u.forEach(f=>f())})}},fx=(t,e)=>!!(t&&t.length===e.length&&t.every((n,r)=>n[1]===e[r][1])),Bs=new WeakMap,wu=(t,e,n)=>{const r=!n&&e.pC;n&&(e.pC||=e.vC);let i;try{n||=typeof e.tag=="function"?ux(t,e):Fo(e.props.children),n[0]?.tag===""&&n[0][Gl]&&(i=n[0][Gl],t[5].push([t,i,e]));const s=r?[...e.pC]:e.vC?[...e.vC]:void 0,a=[];let c;for(let l=0;l<n.length;l++){Array.isArray(n[l])&&n.splice(l,1,...n[l].flat());let d=hx(n[l]);if(d){typeof d.tag=="function"&&!d.tag[h_]&&(Jr.length>0&&(d[ke][2]=Jr.map(f=>[f,f.values.at(-1)])),t[5]?.length&&(d[ke][3]=t[5].at(-1)));let u;if(s&&s.length){const f=s.findIndex(cn(d)?g=>cn(g):d.key!==void 0?g=>g.key===d.key&&g.tag===d.tag:g=>g.tag===d.tag);f!==-1&&(u=s[f],s.splice(f,1))}if(u)if(cn(d))u.t!==d.t&&(u.t=d.t,u.d=!0),d=u;else{const f=u.pP=u.props;if(u.props=d.props,u.f||=d.f||e.f,typeof d.tag=="function"){const g=u[ke][2];u[ke][2]=d[ke][2]||[],u[ke][3]=d[ke][3],!u.f&&((u.o||u)===d.o||u.tag[s2]?.(f,u.props))&&fx(g,u[ke][2])&&(u.s=!0)}d=u}else if(!cn(d)&&li){const f=fi(li);f&&(d.n=f)}if(!cn(d)&&!d.s&&(wu(t,d),delete d.f),a.push(d),c&&!c.s&&!d.s)for(let f=c;f&&!cn(f);f=f.vC?.at(-1))f.nN=d;c=d}}e.vR=r?[...e.vC,...s||[]]:s||[],e.vC=a,r&&delete e.pC}catch(s){if(e.f=!0,s===y0){if(i)return;throw s}const[a,c,l]=e[ke]?.[3]||[];if(c){const d=()=>Ls([0,!1,t[2]],l),u=Bs.get(l)||[];u.push(d),Bs.set(l,u);const f=c(s,()=>{const g=Bs.get(l);if(g){const _=g.indexOf(d);if(_!==-1)return g.splice(_,1),d()}});if(f){if(t[0]===1)t[1]=!0;else if(wu(t,l,[f]),(c.length===1||t!==a)&&l.c){J1(l,l.c,!1);return}throw y0}}throw s}finally{i&&t[5].pop()}},hx=t=>{if(!(t==null||typeof t=="boolean")){if(typeof t=="string"||typeof t=="number")return{t:t.toString(),d:!0};if("vR"in t&&(t={tag:t.tag,props:t.props,key:t.key,f:t.f,type:t.tag,ref:t.props.ref,o:t.o||t}),typeof t.tag=="function")t[ke]=[0,[]];else{const e=cx[t.tag];e&&(li||=m_(""),t.props.children=[{tag:li,props:{value:t.n=`http://www.w3.org/${e}`,children:t.props.children}}])}return t}},w0=(t,e)=>{e[ke][2]?.forEach(([n,r])=>{n.values.push(r)});try{wu(t,e,void 0)}catch{return}if(e.a){delete e.a;return}e[ke][2]?.forEach(([n])=>{n.values.pop()}),(t[0]!==1||!t[1])&&J1(e,e.c,!1)},eo=new WeakMap,b0=[],Ls=async(t,e)=>{t[5]||=[];const n=eo.get(e);n&&n[0](void 0);let r;const i=new Promise(s=>r=s);if(eo.set(e,[r,()=>{t[2]?t[2](t,e,s=>{w0(s,e)}).then(()=>r(e)):(w0(t,e),r(e))}]),b0.length)b0.at(-1).add(e);else{await Promise.resolve();const s=eo.get(e);s&&(eo.delete(e),s[1]())}return i},gx=(t,e,n)=>({tag:Uo,props:{children:t},key:n,e,p:1}),mx=0,Z1=1,_x=2,yx=3,jl=new WeakMap,Y1=(t,e)=>!t||!e||t.length!==e.length||e.some((n,r)=>n!==t[r]),wx=void 0,v0=[],bx=t=>{const e=()=>typeof t=="function"?t():t,n=Do.at(-1);if(!n)return[e(),()=>{}];const[,r]=n,i=r[ke][1][mx]||=[],s=r[ke][0]++;return i[s]||=[e(),a=>{const c=wx,l=i[s];if(typeof a=="function"&&(a=a(l[0])),!Object.is(a,l[0]))if(l[0]=a,v0.length){const[d,u]=v0.at(-1);Promise.all([d===3?r:Ls([d,!1,c],r),u]).then(([f])=>{if(!f||!(d===2||d===3))return;const g=f.vC;requestAnimationFrame(()=>{setTimeout(()=>{g===f.vC&&Ls([d===3?1:0,!1,c],f)})})})}else Ls([0,!1,c],r)}]},Jp=(t,e)=>{const n=Do.at(-1);if(!n)return t;const[,r]=n,i=r[ke][1][_x]||=[],s=r[ke][0]++,a=i[s];return Y1(a?.[1],e)?i[s]=[t,e]:t=i[s][0],t},vx=t=>{const e=jl.get(t);if(e){if(e.length===2)throw e[1];return e[0]}throw t.then(n=>jl.set(t,[n]),n=>jl.set(t,[void 0,n])),t},$x=(t,e)=>{const n=Do.at(-1);if(!n)return t();const[,r]=n,i=r[ke][1][yx]||=[],s=r[ke][0]++,a=i[s];return Y1(a?.[1],e)&&(i[s]=[t(),e]),i[s][0]},kx=m_({pending:!1,data:null,method:null,action:null}),$0=new Set,xx=t=>{$0.add(t),t.finally(()=>$0.delete(t))},Xp=(t,e)=>$x(()=>n=>{let r;t&&(typeof t=="function"?r=t(n)||(()=>{t(null)}):t&&"current"in t&&(t.current=n,r=()=>{t.current=null}));const i=e(n);return()=>{i?.(),r?.()}},[t]),k0=Object.create(null),x0=Object.create(null),ps=(t,e,n,r,i)=>{if(e?.itemProp)return{tag:t,props:e,type:t,ref:e.ref};const s=document.head;let{onLoad:a,onError:c,precedence:l,blocking:d,...u}=e,f=null,g=!1;const _=Es[t];let w;if(_.length>0){const I=s.querySelectorAll(t);e:for(const S of I)for(const E of Es[t])if(S.getAttribute(E)===e[E]){f=S;break e}if(!f){const S=_.reduce((E,P)=>e[P]===void 0?E:`${E}-${P}-${e[P]}`,t);g=!x0[S],f=x0[S]||=(()=>{const E=document.createElement(t);for(const P of _)e[P]!==void 0&&E.setAttribute(P,e[P]),e.rel&&E.setAttribute("rel",e.rel);return E})()}}else w=s.querySelectorAll(t);l=r?l??"":void 0,r&&(u[Cs]=l);const k=Jp(I=>{if(_.length>0){let S=!1;for(const E of s.querySelectorAll(t)){if(S&&E.getAttribute(Cs)!==l){s.insertBefore(I,E);return}E.getAttribute(Cs)===l&&(S=!0)}s.appendChild(I)}else if(w){let S=!1;for(const E of w)if(E===I){S=!0;break}S||s.insertBefore(I,s.contains(w[0])?w[0]:s.querySelector(t)),w=void 0}},[l]),z=Xp(e.ref,I=>{const S=_[0];if(n===2&&(I.innerHTML=""),(g||w)&&k(I),!c&&!a)return;let E=k0[I.getAttribute(S)]||=new Promise((P,G)=>{I.addEventListener("load",P),I.addEventListener("error",G)});a&&(E=E.then(a)),c&&(E=E.catch(c)),E.catch(()=>{})});if(i&&d==="render"){const I=Es[t][0];if(e[I]){const S=e[I],E=k0[S]||=new Promise((P,G)=>{k(f),f.addEventListener("load",P),f.addEventListener("error",G)});vx(E)}}const N={tag:t,type:t,props:{...u,ref:z},ref:z};return N.p=n,f&&(N.e=f),gx(N,s)},Sx=t=>{const e=lx();return(e&&fi(e))?.endsWith("svg")?{tag:"title",props:t,type:"title",ref:t.ref}:ps("title",t,void 0,!1,!1)},zx=t=>!t||["src","async"].some(e=>!t[e])?{tag:"script",props:t,type:"script",ref:t.ref}:ps("script",t,1,!1,!0),Ax=t=>!t||!["href","precedence"].every(e=>e in t)?{tag:"style",props:t,type:"style",ref:t.ref}:(t["data-href"]=t.href,delete t.href,ps("style",t,2,!0,!0)),Ex=t=>!t||["onLoad","onError"].some(e=>e in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?{tag:"link",props:t,type:"link",ref:t.ref}:ps("link",t,1,"precedence"in t,!0),Cx=t=>ps("meta",t,void 0,!1,!1),Q1=Symbol(),Nx=t=>{const{action:e,...n}=t;typeof e!="function"&&(n.action=e);const[r,i]=bx([null,!1]),s=Jp(async d=>{const u=d.isTrusted?e:d.detail[Q1];if(typeof u!="function")return;d.preventDefault();const f=new FormData(d.target);i([f,!0]);const g=u(f);g instanceof Promise&&(xx(g),await g),i([null,!0])},[]),a=Xp(t.ref,d=>(d.addEventListener("submit",s),()=>{d.removeEventListener("submit",s)})),[c,l]=r;return r[1]=!1,{tag:kx,props:{value:{pending:c!==null,data:c,method:c?"post":null,action:c?e:null},children:{tag:"form",props:{...n,ref:a},type:"form",ref:a}},f:l}},ew=(t,{formAction:e,...n})=>{if(typeof e=="function"){const r=Jp(i=>{i.preventDefault(),i.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[Q1]:e}}))},[]);n.ref=Xp(n.ref,i=>(i.addEventListener("click",r),()=>{i.removeEventListener("click",r)}))}return{tag:t,props:n,type:t,ref:n.ref}},Ix=t=>ew("input",t),jx=t=>ew("button",t);Object.assign(Wl,{title:Sx,script:zx,style:Ax,link:Ex,meta:Cx,form:Nx,input:Ix,button:jx});__(null);new TextEncoder;const Un=t=>{const{i18nKey:e,values:n,components:r}=t,i=y.t(e,n),s=/<(\d+)>(.*?)<\/\d+>/g,a=[];let c=0,l;for(;(l=s.exec(i))!==null;){const[,d,u]=l,f=i.substring(c,l.index);f&&a.push(f);const g=parseInt(d,10);a.push(b2(r[g],{},u)),c=s.lastIndex}return c<i.length&&a.push(i.substring(c)),p(bo,{children:a})},S0=6,bu=({error:t,theme:e,branding:n,email:r,state:i,client:s,hasPasswordLogin:a})=>{const c=new URLSearchParams({state:i}),d=s.connections.map(({name:u})=>u).includes("auth2");return p(Se,{title:y.t("verify_your_email"),theme:e,branding:n,client:s,children:[p("div",{className:"mb-4 text-2xl font-medium",children:y.t("verify_your_email")}),p("div",{className:"mb-8 text-gray-300",children:p(Un,{i18nKey:"code_sent_template",components:[p("span",{className:"text-black dark:text-white"},"span")],values:{username:r}})}),p("div",{className:"flex flex-1 flex-col justify-center",children:[p(Bt,{className:"pt-2",children:[p("input",{autoFocus:!0,type:"text",pattern:"[0-9]*",maxLength:S0,inputMode:"numeric",name:"code",placeholder:"******",className:Q("mb-2 w-full rounded-lg border bg-gray-100 px-4 pb-2 pt-2.5 text-center indent-[5px] font-mono text-3xl placeholder:text-gray-300 dark:bg-gray-600 md:text-3xl",{"border-red":t,"border-gray-100 dark:border-gray-500":!t}),minLength:S0,required:!0,id:"code-input"}),t&&p(Re,{children:t}),p(xe,{className:"sm:mt-4 !text-base",children:[p("span",{children:y.t("login")}),p(Ne,{className:"text-xs",name:"arrow-right"})]}),p("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[p(Ne,{className:"text-base",name:"info-bubble"}),p("div",{className:"text-sm text-gray-300 md:text-sm",children:y.t("sent_code_spam")})]}),d&&p("div",{className:"text-center mb-12",children:[p("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[p("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),p("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:y.t("or")})]}),p(xe,{Component:"a",href:`/u/${a?"enter-password":"pre-signup"}?${c.toString()}`,variant:"secondary",className:"block",children:y.t("enter_your_password_btn")})]})]}),p(lt,{state:i})]})]})},Px=({maxLength:t,value:e="",disabled:n=!1,className:r,containerClassName:i,name:s,id:a,required:c,autoFocus:l})=>p("div",{className:Q("flex items-center gap-2 has-[:disabled]:opacity-50",i),"data-input-otp-container":"",children:Array.from({length:t}).map((d,u)=>p("input",{type:"text",inputMode:"numeric",maxLength:1,value:e[u]||"",disabled:n,name:u===0?s:void 0,id:u===0?a:void 0,required:u===0?c:void 0,autoFocus:u===0?l:void 0,className:Q("relative flex h-9 w-9 items-center justify-center border-y border-r border-input text-sm shadow-sm transition-all first:rounded-l-md first:border-l last:rounded-r-md text-center font-mono","focus:z-10 focus:ring-1 focus:ring-ring","disabled:cursor-not-allowed disabled:opacity-50",r),"data-input-otp-slot":u},u))}),Ox=6,z0=({error:t,theme:e,branding:n,email:r,state:i,hasPasswordLogin:s,className:a})=>{const c=new URLSearchParams({state:i}),l=e?.colors?.primary_button||n?.colors?.primary||"#0066cc",d=e?.colors?.primary_button_label||"#ffffff",u=e?.colors?.body_text||"#333333",f=e?.colors?.input_border||"#d1d5db",g=e?.colors?.widget_background||"#ffffff",_=e?.colors?.widget_border||"#e5e7eb",w=e?.borders?.widget_corner_radius||8,k=e?.borders?.button_border_radius||4,z=e?.borders?.show_widget_shadow??!0,N=e?.fonts?.title?.size||24,I=e?.fonts?.title?.bold??!0,S=e?.fonts?.body_text?.size||14,E={backgroundColor:g,borderColor:_,borderRadius:`${w}px`,boxShadow:z?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:u},P={fontSize:`${N}px`,fontWeight:I?"700":"400",color:e?.colors?.header||u},G={fontSize:`${S}px`,color:e?.colors?.input_labels_placeholders||"#6b7280"},Z={backgroundColor:l,color:d,borderRadius:`${k}px`},W=e?.widget?.logo_position||"center",M=W==="left"?"text-left":W==="right"?"text-right":"text-center",ce=e?.widget?.logo_url||n?.logo_url,le=W!=="none"&&ce;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",a),children:[p(en,{style:E,className:"border",children:[p(tn,{children:[le&&p("div",{className:Q("mb-4",M),children:p(Rt,{theme:e,branding:n})}),p(nn,{style:P,children:y.t("verify_your_email","Verify your email")}),p(rn,{style:G,children:p(Un,{i18nKey:"code_sent_template",components:[p("span",{className:"font-medium"},"span")],values:{username:r}})})]}),p(on,{children:p("form",{method:"post",children:p("div",{className:"grid gap-6",children:[p("div",{className:"grid gap-4",children:[p(_t,{htmlFor:"code",style:G,children:y.t("verification_code","Verification Code")}),p("div",{className:"flex justify-center",children:p(Px,{maxLength:Ox,name:"code",id:"code",required:!0,autoFocus:!0,containerClassName:"gap-2",className:Q("w-12 h-12 text-center text-lg font-mono border rounded-md transition-colors",t?"border-red-500 focus:ring-red-500":"border-gray-300 focus:ring-blue-500 focus:border-blue-500")})}),t&&p(Re,{children:t})]}),p(Jt,{type:"submit",className:"w-full transition-colors hover:brightness-90",style:Z,children:y.t("login","Login")}),p("div",{className:"text-center text-xs text-gray-500",children:p("div",{className:"flex items-center justify-center gap-1",children:[p("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 20 20",children:p("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z",clipRule:"evenodd"})}),p("span",{children:y.t("sent_code_spam","Check your spam folder if you don't see the code")})]})}),s&&p("div",{className:"text-center",children:[p("div",{className:"relative mb-5 block text-center",style:G,children:[p("div",{className:"absolute left-0 right-0 top-1/2 border-b",style:{borderColor:_}}),p("div",{className:"relative inline-block px-2",style:{backgroundColor:g},children:y.t("or","Or")})]}),p("a",{href:`/u/${s?"enter-password":"pre-signup"}?${c.toString()}`,className:Q("w-full 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","border border-gray-300 bg-transparent hover:bg-gray-100 dark:border-gray-600 dark:hover:bg-gray-800","h-10 px-4 py-2"),style:{borderColor:f,borderRadius:`${k}px`,color:u},children:y.t("enter_your_password_btn","Enter your password instead")})]})]})})})]}),p(lt,{state:i})]})},wt=t=>{const{message:e,theme:n,branding:r,client:i,pageTitle:s,state:a}=t;return p(Se,{title:"Login",theme:n,branding:r,client:i,children:[s?p("div",{className:"mb-4 text-2xl font-medium",children:s}):"",p("div",{className:"text-gray-300 mb-12",children:e}),a?p(lt,{state:a}):""]})},Tx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state"}),style:o.z.enum(["classic","shadcn"]).optional().openapi({description:"UI style to use for the enter code page"})})},responses:{200:{description:"HTML page to enter verification code.",content:{"text/html":{schema:o.z.string()}}},400:{description:"Bad Request - HTML error page if username is missing in state.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{state:e,style:n}=t.req.valid("query");let r,i,s,a,c;n&&Og(t,"auth_ui_style",n,{path:"/",maxAge:3600*24*365,httpOnly:!0,secure:!0,sameSite:"Lax"});try{if({theme:r,branding:i,loginSession:s,client:a,useShadcn:c}=await he(t,e),!s.authParams.username)return t.html(p(wt,{theme:r,branding:i,client:a,state:e,pageTitle:y.t("error_page_title")||"Error",message:y.t("username_not_found_error")||"Username not found in session."}),400);const l=await yo({userAdapter:t.env.data.users,tenant_id:a.tenant.id,username:s.authParams.username,provider:"auth2"});return c?t.html(p(we,{title:y.t("verify_your_email","Verify your email"),theme:r,branding:i,client:a,children:p(z0,{theme:r,branding:i,email:s.authParams.username,state:e,hasPasswordLogin:!!l})})):t.html(p(bu,{theme:r,branding:i,email:s.authParams.username,state:e,client:a,hasPasswordLogin:!!l}))}catch(l){return console.error("Error in GET /u/enter-code:",l),i||(i=null),r||(r=null),a||(a=null),t.html(p(wt,{theme:r,branding:i,client:a,state:e,pageTitle:y.t("error_page_title")||"Error",message:y.t("unexpected_error_try_again")||"An unexpected error occurred. Please try again."}),500)}}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state"}),style:o.z.enum(["classic","shadcn"]).optional().openapi({description:"UI style to use for the enter code page"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({code:o.z.string()})}}}},responses:{302:{description:"Redirect to continue authentication flow.",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML page with an error message (e.g., invalid code, username missing).",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page for unexpected issues.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{state:e,style:n}=t.req.valid("query"),{code:r}=t.req.valid("form");n&&Og(t,"auth_ui_style",n,{path:"/",maxAge:3600*24*365,httpOnly:!0,secure:!0,sameSite:"Lax"});const{theme:i,branding:s,client:a,loginSession:c,useShadcn:l}=await he(t,e);if(!c.authParams.username)throw new v(400,{message:y.t("username_not_found_error")||"Username not found in session."});try{t.set("client_id",a.client_id);const d=await Fp(t,{client_id:a.client_id,authParams:c.authParams,username:c.authParams.username,otp:r});if(d instanceof Response)return d;throw new v(500,{message:y.t("unexpected_error_try_again")||"An unexpected error occurred. Please try again."})}catch(d){let u;try{u=await yo({userAdapter:t.env.data.users,tenant_id:a.tenant.id,username:c.authParams.username,provider:"auth2"})}catch{u=null}return l?t.html(p(we,{title:y.t("verify_your_email","Verify your email"),theme:i,branding:s,client:a,children:p(z0,{theme:i,branding:s,email:c.authParams?.username,state:e,error:d.message,hasPasswordLogin:!!u})}),400):t.html(p(bu,{theme:i,branding:s,email:c.authParams?.username,state:e,client:a,error:d.message,hasPasswordLogin:!!u}),400)}}),tw=t=>{const{theme:e,branding:n,client:r,state:i}=t;return p(Se,{title:y.t("unverified_email"),theme:e,branding:n,client:r,children:[p("div",{className:"flex flex-1 flex-col justify-center",children:[p("p",{className:"mb-8 text-gray-300 text-lg",children:y.t("unverified_email")}),p("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[p(Ne,{className:"text-base",name:"info-bubble"}),p("div",{className:"text-sm text-gray-300 md:text-sm",children:y.t("sent_code_spam")})]}),p(lt,{state:i})]}),p(lt,{state:i})]})},Rx=({width:t=22,height:e=17,className:n,...r})=>p("svg",{width:t,height:e,className:n,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 576 512",...r,children:p("path",{fill:"currentColor",d:"M288 32c-80.8 0-145.5 36.8-192.6 80.6C48.6 156 17.3 208 2.5 243.7c-3.3 7.9-3.3 16.7 0 24.6C17.3 304 48.6 356 95.4 399.4 142.5 443.2 207.2 480 288 480s145.5-36.8 192.6-80.6c46.8-43.5 78.1-95.4 93-131.1 3.3-7.9 3.3-16.7 0-24.6-14.9-35.7-46.2-87.7-93-131.1C433.5 68.8 368.8 32 288 32M144 256a144 144 0 1 1 288 0 144 144 0 1 1-288 0m144-64c0 35.3-28.7 64-64 64-7.1 0-13.9-1.2-20.3-3.3-5.5-1.8-11.9 1.6-11.7 7.4.3 6.9 1.3 13.8 3.2 20.7 13.7 51.2 66.4 81.6 117.6 67.9s81.6-66.4 67.9-117.6c-11.1-41.5-47.8-69.4-88.6-71.1-5.8-.2-9.2 6.1-7.4 11.7 2.1 6.4 3.3 13.2 3.3 20.3"})}),Bx=({width:t=23,height:e=18,className:n,...r})=>p("svg",{width:t,height:e,className:n,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 640 512",...r,children:p("path",{fill:"currentColor",d:"M38.8 5.1C28.4-3.1 13.3-1.2 5.1 9.2s-6.3 25.5 4.1 33.7l592 464c10.4 8.2 25.5 6.3 33.7-4.1s6.3-25.5-4.1-33.7l-105.2-82.4c39.6-40.6 66.4-86.1 79.9-118.4 3.3-7.9 3.3-16.7 0-24.6-14.9-35.7-46.2-87.7-93-131.1C465.5 68.8 400.8 32 320 32c-68.2 0-125 26.3-169.3 60.8zm184.3 144.4c25.5-23.3 59.6-37.5 96.9-37.5 79.5 0 144 64.5 144 144 0 24.9-6.3 48.3-17.4 68.7L408 294.5c8.4-19.3 10.6-41.4 4.8-63.3-11.1-41.5-47.8-69.4-88.6-71.1-5.8-.2-9.2 6.1-7.4 11.7 2.1 6.4 3.3 13.2 3.3 20.3 0 10.2-2.4 19.8-6.6 28.3l-90.3-70.8zM373 389.9c-16.4 6.5-34.3 10.1-53 10.1-79.5 0-144-64.5-144-144 0-6.9.5-13.6 1.4-20.2l-94.3-74.3c-22.8 29.7-39.1 59.3-48.6 82.2-3.3 7.9-3.3 16.7 0 24.6 14.9 35.7 46.2 87.7 93 131.1 47 43.8 111.7 80.6 192.5 80.6 47.8 0 89.9-12.9 126.2-32.5z"})}),vu=({name:t,placeholder:e=y.t("password")})=>p("div",{className:"password-input relative mb-2","data-password-toggle":!0,children:[p("input",{type:"password",name:t,placeholder:e,className:"w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",required:!0}),p("button",{type:"button","aria-label":y.t("show_password"),title:y.t("show_password"),className:"absolute right-0 top-0 w-10 h-full rounded-r-lg text-gray-400 column hover:bg-black/5","data-password-toggle-btn":!0,children:[p(Rx,{"data-show-icon":!0}),p(Bx,{"data-hide-icon":!0,className:"hidden"})]})]}),Us=t=>{const{error:e,theme:n,branding:r,email:i,state:s,client:a}=t,c=new URLSearchParams({state:s});return p(Se,{title:y.t("enter_password"),theme:n,branding:r,client:a,children:[p("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:y.t("enter_password")}),p("div",{className:"mb-6 text-gray-300",children:y.t("enter_password_description")}),p("div",{className:"flex flex-1 flex-col justify-center",children:[p(Bt,{className:"mb-7",children:[p("input",{type:"text",name:"username",placeholder:y.t("email_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",value:i}),p(vu,{name:"password"}),e&&p(Re,{children:e}),p(xe,{className:"sm:mt-4 !text-base",children:[p("span",{children:y.t("login")}),p(Ne,{className:"text-xs",name:"arrow-right"})]})]}),p("a",{href:`/u/forgot-password?${c.toString()}`,className:"text-primary hover:underline mb-4",children:y.t("forgot_password_link")}),p("div",{className:"text-center mb-12",children:[p("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[p("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),p("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:y.t("or")})]}),p("form",{method:"post",action:`/u/login/identifier?${c.toString()}`,children:[p("input",{type:"hidden",name:"login_selection",value:"code"}),p("input",{type:"hidden",name:"username",value:i}),p(xe,{variant:"secondary",className:"block",children:y.t("enter_a_code_btn")})]})]}),p(lt,{state:s})]})]})},Pl=({error:t,theme:e,branding:n,loginSession:r,email:i,className:s})=>{const a=e?.colors?.primary_button||n?.colors?.primary||"#0066cc",c=e?.colors?.primary_button_label||"#ffffff",l=e?.colors?.body_text||"#333333",d=e?.colors?.input_background||"#ffffff",u=e?.colors?.input_border||"#d1d5db",f=e?.colors?.input_filled_text||"#111827",g=e?.colors?.error||"#dc2626",_=e?.colors?.widget_background||"#ffffff",w=e?.colors?.widget_border||"#e5e7eb",k=e?.borders?.widget_corner_radius||8,z=e?.borders?.input_border_radius||4,N=e?.borders?.button_border_radius||4,I=e?.borders?.show_widget_shadow??!0,S=e?.fonts?.title?.size||24,E=e?.fonts?.title?.bold??!0,P=e?.fonts?.body_text?.size||14,G={backgroundColor:_,borderColor:w,borderRadius:`${k}px`,boxShadow:I?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:l},Z={fontSize:`${S}px`,fontWeight:E?"700":"400",color:e?.colors?.header||l},W={fontSize:`${P}px`,color:e?.colors?.input_labels_placeholders||"#6b7280"},M={backgroundColor:d,borderColor:t?g:u,borderRadius:`${z}px`,color:f},ce={backgroundColor:a,color:c,borderRadius:`${N}px`},le=e?.widget?.logo_position||"center",fe=le==="left"?"text-left":le==="right"?"text-right":"text-center",$e=e?.widget?.logo_url||n?.logo_url,be=le!=="none"&&$e;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",s),children:p(en,{style:G,className:"border",children:[p(tn,{children:[be&&p("div",{className:Q("mb-4",fe),children:p(Rt,{theme:e,branding:n})}),p(nn,{style:Z,children:y.t("enter_password","Enter your password")}),p(rn,{style:W,children:y.t("enter_password_description","Enter your password to continue")})]}),p(on,{children:p("form",{method:"post",children:p("div",{className:"grid gap-6",children:[p("div",{className:"grid gap-2",children:[p(_t,{htmlFor:"email",style:W,children:y.t("email","Email")}),p(Pt,{id:"email",name:"username",type:"email",value:i,disabled:!0,className:"border bg-gray-50",style:{...M,cursor:"not-allowed"}})]}),p("div",{className:"grid gap-2",children:[p("div",{className:"flex items-center justify-between",children:[p(_t,{htmlFor:"password",style:W,children:y.t("password","Password")}),p("a",{href:`/u/forgot-password?state=${r.id}`,className:"text-sm hover:underline",style:{color:a},children:y.t("forgot_password","Forgot password?")})]}),p("div",{className:"relative","data-password-toggle":!0,children:[p(Pt,{id:"password",name:"password",type:"password","data-password-input":"password",placeholder:y.t("password_placeholder","Enter your password"),required:!0,error:!!t,className:"border pr-8",style:M}),p("button",{type:"button","data-password-toggle-btn":!0,className:"absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 transition-colors","aria-label":y.t("toggle_password_visibility","Toggle password visibility"),children:[p("svg",{"data-show-icon":!0,xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),p("circle",{cx:"12",cy:"12",r:"3"})]}),p("svg",{"data-hide-icon":!0,className:"hidden",xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),p("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),p("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),p("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]})]})]}),t&&p(Re,{children:t})]}),p(Jt,{type:"submit",className:"w-full transition-colors hover:brightness-90",style:ce,children:y.t("continue","Continue")}),p("div",{className:"text-center",children:p("a",{href:`/u/login/identifier?state=${r.id}`,className:"text-sm hover:underline",style:W,children:["← ",y.t("back","Back")]})})]})})})]})})},Lx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,loginSession:s,useShadcn:a}=await he(t,e);if(!s.authParams.username)throw new v(400,{message:"Username required"});return a?t.html(p(we,{title:y.t("enter_your_password","Enter your password"),theme:n,branding:r,client:i,children:p(Pl,{theme:n,branding:r,loginSession:s,email:s.authParams.username,client:i})})):t.html(p(Us,{theme:n,branding:r,email:s.authParams.username,state:e,client:i}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({password:o.z.string()})}}}},responses:{200:{description:"HTML page indicating success or a next step (if not redirecting).",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to continue the authentication flow (e.g., to client, MFA, consent).",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML page with an error message (e.g., invalid password, username required).",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML page with an error message.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{state:e}=t.req.valid("query"),n=t.req.valid("form"),{password:r}=n,{theme:i,branding:s,client:a,loginSession:c,useShadcn:l}=await he(t,e),{username:d}=c.authParams;if(!d)throw new v(400,{message:"Username required"});try{return await M1(t,a,{...c.authParams,password:r},c)}catch(u){const f=u;return f.code==="INVALID_PASSWORD"||f.code==="USER_NOT_FOUND"?l?t.html(p(we,{title:y.t("enter_your_password","Enter your password"),theme:i,branding:s,client:a,children:p(Pl,{theme:i,branding:s,loginSession:c,email:d,error:y.t("invalid_password"),client:a})}),400):t.html(p(Us,{theme:i,branding:s,email:d,error:y.t("invalid_password"),state:e,client:a}),400):f.code==="EMAIL_NOT_VERIFIED"?t.html(p(tw,{theme:i,branding:s,client:a,state:e}),400):l?t.html(p(we,{title:y.t("enter_your_password","Enter your password"),theme:i,branding:s,client:a,children:p(Pl,{theme:i,branding:s,loginSession:c,email:d,error:f.message||"An unknown error occurred.",client:a})}),f.code?400:500):t.html(p(Us,{theme:i,branding:s,email:d,error:f.message||"An unknown error occurred.",state:e,client:a}),f.code?400:500)}}),Gn=t=>{const{error:e,theme:n,branding:r,client:i,email:s,state:a,code:c}=t;return p(Se,{title:y.t("sign_up"),theme:n,branding:r,client:i,children:[p("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:y.t("create_account_title")}),p("div",{className:"mb-6 text-gray-300",children:y.t("create_account_description")}),p("div",{className:"flex flex-1 flex-col justify-center",children:[p(Bt,{children:[p("input",{type:"hidden",name:"code",value:c}),p("input",{type:"email",name:"username",placeholder:y.t("email_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",required:!0,value:s,disabled:!!s}),p("input",{type:"password",name:"password",placeholder:y.t("enter_new_password_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base"}),p("input",{type:"password",name:"re-enter-password",placeholder:y.t("reenter_new_password_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base"}),e&&p(Re,{children:e}),p(xe,{className:"sm:mt-4 !text-base",children:y.t("continue")})]}),p(lt,{state:a})]})]})},ji=({error:t,theme:e,branding:n,loginSession:r,email:i,code:s,className:a})=>{const c=e?.colors?.primary_button||n?.colors?.primary||"#0066cc",l=e?.colors?.primary_button_label||"#ffffff",d=e?.colors?.body_text||"#333333",u=e?.colors?.input_background||"#ffffff",f=e?.colors?.input_border||"#d1d5db",g=e?.colors?.input_filled_text||"#111827",_=e?.colors?.error||"#dc2626",w=e?.colors?.widget_background||"#ffffff",k=e?.colors?.widget_border||"#e5e7eb",z=e?.borders?.widget_corner_radius||8,N=e?.borders?.input_border_radius||4,I=e?.borders?.button_border_radius||4,S=e?.borders?.show_widget_shadow??!0,E=e?.fonts?.title?.size||24,P=e?.fonts?.title?.bold??!0,G=e?.fonts?.body_text?.size||14,Z={backgroundColor:w,borderColor:k,borderRadius:`${z}px`,boxShadow:S?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:d},W={fontSize:`${E}px`,fontWeight:P?"700":"400",color:e?.colors?.header||d},M={fontSize:`${G}px`,color:e?.colors?.input_labels_placeholders||"#6b7280"},ce={backgroundColor:u,borderColor:t?_:f,borderRadius:`${N}px`,color:g},le={backgroundColor:c,color:l,borderRadius:`${I}px`},fe=e?.widget?.logo_position||"center",$e=fe==="left"?"text-left":fe==="right"?"text-right":"text-center",be=e?.widget?.logo_url||n?.logo_url,sn=fe!=="none"&&be;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",a),children:p(en,{style:Z,className:"border",children:[p(tn,{children:[sn&&p("div",{className:Q("mb-4",$e),children:p(Rt,{theme:e,branding:n})}),p(nn,{style:W,children:y.t("create_account_title","Create Account")}),p(rn,{style:M,children:y.t("create_account_description","Sign up to get started")})]}),p(on,{children:[p("form",{method:"post",className:"space-y-4",children:[p("input",{type:"hidden",name:"state",value:r.authParams.state}),s&&p("input",{type:"hidden",name:"code",value:s}),p("div",{className:"space-y-2",children:[p(_t,{htmlFor:"username",style:M,children:y.t("email_label","Email")}),p(Pt,{id:"username",type:"email",name:"username",placeholder:y.t("email_placeholder","Email Address"),value:i,disabled:!!i,style:ce,className:"w-full",required:!0})]}),p("div",{className:"space-y-2",children:[p(_t,{htmlFor:"password",style:M,children:y.t("password","Password")}),p("div",{className:"relative","data-password-toggle":!0,children:[p(Pt,{id:"password",name:"password",type:"password","data-password-input":"password",placeholder:y.t("enter_new_password_placeholder","Enter new password"),required:!0,error:!!t,className:"border pr-8",style:ce}),p("button",{type:"button","data-password-toggle-btn":!0,className:"absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 transition-colors","aria-label":y.t("toggle_password_visibility","Toggle password visibility"),children:[p("svg",{"data-show-icon":!0,xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),p("circle",{cx:"12",cy:"12",r:"3"})]}),p("svg",{"data-hide-icon":!0,className:"hidden",xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),p("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),p("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),p("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]})]})]})]}),p("div",{className:"space-y-2",children:[p(_t,{htmlFor:"re-enter-password",style:M,children:y.t("confirm_password","Confirm Password")}),p("div",{className:"relative","data-password-toggle":!0,children:[p(Pt,{id:"re-enter-password",name:"re-enter-password",type:"password","data-password-input":"re-enter-password",placeholder:y.t("reenter_new_password_placeholder","Re-enter new password"),required:!0,error:!!t,className:"border pr-8",style:ce}),p("button",{type:"button","data-password-toggle-btn":!0,className:"absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 transition-colors","aria-label":y.t("toggle_password_visibility","Toggle password visibility"),children:[p("svg",{"data-show-icon":!0,xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),p("circle",{cx:"12",cy:"12",r:"3"})]}),p("svg",{"data-hide-icon":!0,className:"hidden",xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),p("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),p("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),p("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]})]})]})]}),t&&p(Re,{children:t}),p(Jt,{type:"submit",className:"w-full",style:le,disabled:!1,children:y.t("continue","Continue")})]}),p("div",{className:"mt-4 text-center",children:p("a",{href:`/u/login/identifier?state=${encodeURIComponent(r.authParams.state||"")}`,className:"text-sm",style:{color:c},children:y.t("back_to_login","Back to Login")})})]})]})})},Ux=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.z.string().optional().openapi({description:"The code parameter from an email verification link"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e,code:n}=t.req.valid("query"),{theme:r,branding:i,client:s,loginSession:a,useShadcn:c}=await he(t,e),{username:l}=a.authParams;if(!l)throw new v(400,{message:"Username required"});return c?t.html(p(we,{title:y.t("sign_up","Sign Up"),theme:r,branding:i,client:s,children:p(ji,{theme:r,branding:i,loginSession:a,email:l,code:n,client:s})})):n?t.html(p(Gn,{state:e,theme:r,branding:i,client:s,email:l,code:n})):t.html(p(Gn,{state:e,theme:r,branding:i,client:s,email:l}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({password:o.z.string(),"re-enter-password":o.z.string(),code:o.z.string().optional()})}}}},responses:{200:{description:"HTML page indicating success (e.g., email verification sent) or a next step.",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to continue the authentication flow (e.g., to client, MFA, consent) after successful login.",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML page with an error message (e.g., passwords don't match, weak password, user exists).",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML page with an error message.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{state:e}=t.req.valid("query"),n=t.req.valid("form"),{env:r}=t,{theme:i,branding:s,client:a,loginSession:c,useShadcn:l}=await he(t,e);try{if(!c.authParams.username)throw new v(400,{message:"Username required"});const u=a.connections.find(S=>S.strategy==="Username-Password-Authentication")?.name||"Username-Password-Authentication";if(t.set("connection",u),n.password!==n["re-enter-password"])return l?t.html(p(we,{title:y.t("sign_up","Sign Up"),theme:i,branding:s,client:a,children:p(ji,{theme:i,branding:s,loginSession:c,email:c.authParams.username,code:n.code,error:y.t("create_account_passwords_didnt_match"),client:a})}),400):t.html(p(Gn,{state:e,code:n.code,theme:i,branding:s,client:a,error:y.t("create_account_passwords_didnt_match"),email:c.authParams.username}),400);const f=await Vp(r.data,a.tenant.id,u);try{await Hp(f,{tenantId:a.tenant.id,userId:"",newPassword:n.password,data:r.data})}catch(S){let E;return S instanceof Ht?E=y.t(S.code,{defaultValue:S.message,...S.params}):E=S?.message||y.t("create_account_weak_password"),l?t.html(p(we,{title:y.t("sign_up","Sign Up"),theme:i,branding:s,client:a,children:p(ji,{theme:i,branding:s,loginSession:c,email:c.authParams.username,code:n.code,error:E,client:a})}),400):t.html(p(Gn,{state:e,code:n.code,theme:i,branding:s,client:a,error:E,email:c.authParams.username}),400)}const g=n.code?await r.data.codes.get(a.tenant.id,n.code,"email_verification"):void 0,_=g?await r.data.loginSessions.get(a.tenant.id,g.login_id):void 0;if(await pi({userAdapter:t.env.data.users,tenant_id:a.tenant.id,username:c.authParams.username,provider:"auth2"}))return l?t.html(p(we,{title:y.t("sign_up","Sign Up"),theme:i,branding:s,client:a,children:p(ji,{theme:i,branding:s,loginSession:c,email:c.authParams.username,code:n.code,error:y.t("user_exists_error"),client:a})}),400):t.html(p(Gn,{state:e,code:n.code,theme:i,branding:s,client:a,error:y.t("user_exists_error"),email:c.authParams.username}),400);const k=_?.authParams.username===c.authParams.username,z=`auth2|${Xa()}`,N=await r.data.users.create(a.tenant.id,{user_id:z,email:c.authParams.username,email_verified:k,provider:"auth2",connection:u,is_social:!1});if(await r.data.passwords.create(a.tenant.id,{user_id:z,password:await Pn.hash(n.password,10),algorithm:"bcrypt",is_current:!0}),!k){const S=c.authParams?.ui_locales?.split(" ")?.map(E=>E.split("-")[0])[0];return await Wp(t,N,S),t.html(p(wt,{message:y.t("validate_email_body"),pageTitle:y.t("validate_email_title"),theme:i,branding:s,client:a,state:e}))}const I=await D1(t,a,{...c.authParams,password:n.password},c);return Gt(t,I)}catch(d){let u=y.t("unknown_error_message"),f=400;return d instanceof v?(u=d.message||u,f=d.status===400?400:500):d instanceof Tr?u=d.message||u:d instanceof Error&&(u=d.message||u,f=500),l?t.html(p(we,{title:y.t("sign_up","Sign Up"),theme:i,branding:s,client:a,children:p(ji,{theme:i,branding:s,loginSession:c,email:c.authParams.username,code:n.code,error:u,client:a})}),f):t.html(p(Gn,{state:e,theme:i,branding:s,client:a,error:u,email:c.authParams.username,code:n.code}),f)}}),Rr=t=>{const{error:e,theme:n,branding:r,client:i,email:s}=t;return p(Se,{title:y.t("reset_password_title"),theme:n,branding:r,client:i,children:[p("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:y.t("reset_password_title")}),p("div",{className:"mb-6 text-gray-300",children:`${y.t("reset_password_description")} ${s}`}),p("div",{className:"flex flex-1 flex-col justify-center",children:p(Bt,{children:[p(vu,{name:"password",placeholder:y.t("enter_new_password_placeholder")}),p(vu,{name:"re-enter-password",placeholder:y.t("reenter_new_password_placeholder")}),e&&p(Re,{children:e}),p(xe,{className:"sm:mt-4 !text-base",children:y.t("reset_password_cta")})]})})]})},Pi=({error:t,theme:e,branding:n,loginSession:r,email:i,className:s})=>{const a=e?.colors?.primary_button||n?.colors?.primary||"#0066cc",c=e?.colors?.primary_button_label||"#ffffff",l=e?.colors?.body_text||"#333333",d=e?.colors?.input_background||"#ffffff",u=e?.colors?.input_border||"#d1d5db",f=e?.colors?.input_filled_text||"#111827",g=e?.colors?.error||"#dc2626",_=e?.colors?.widget_background||"#ffffff",w=e?.colors?.widget_border||"#e5e7eb",k=e?.borders?.widget_corner_radius||8,z=e?.borders?.input_border_radius||4,N=e?.borders?.button_border_radius||4,I=e?.borders?.show_widget_shadow??!0,S=e?.fonts?.title?.size||24,E=e?.fonts?.title?.bold??!0,P=e?.fonts?.body_text?.size||14,G={backgroundColor:_,borderColor:w,borderRadius:`${k}px`,boxShadow:I?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:l},Z={fontSize:`${S}px`,fontWeight:E?"700":"400",color:e?.colors?.header||l},W={fontSize:`${P}px`,color:e?.colors?.input_labels_placeholders||"#6b7280"},M={backgroundColor:d,borderColor:t?g:u,borderRadius:`${z}px`,color:f},ce={backgroundColor:a,color:c,borderRadius:`${N}px`},le=e?.widget?.logo_position||"center",fe=le==="left"?"text-left":le==="right"?"text-right":"text-center",$e=e?.widget?.logo_url||n?.logo_url,be=le!=="none"&&$e;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",s),children:p(en,{style:G,className:"border",children:[p(tn,{children:[be&&p("div",{className:Q("mb-4",fe),children:p(Rt,{theme:e,branding:n})}),p(nn,{style:Z,children:y.t("reset_password_title","Reset Password")}),p(rn,{style:W,children:`${y.t("reset_password_description","Set a new password for")} ${i}`})]}),p(on,{children:p("form",{method:"post",className:"space-y-4",children:[p("input",{type:"hidden",name:"state",value:r.authParams.state}),p("div",{className:"space-y-2",children:[p(_t,{htmlFor:"password",style:W,children:y.t("new_password","New Password")}),p("div",{className:"relative","data-password-toggle":!0,children:[p(Pt,{id:"password",name:"password",type:"password","data-password-input":"password",placeholder:y.t("enter_new_password_placeholder","Enter new password"),required:!0,error:!!t,className:"border pr-8",style:M}),p("button",{type:"button","data-password-toggle-btn":!0,className:"absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 transition-colors","aria-label":y.t("toggle_password_visibility","Toggle password visibility"),children:[p("svg",{"data-show-icon":!0,xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),p("circle",{cx:"12",cy:"12",r:"3"})]}),p("svg",{"data-hide-icon":!0,className:"hidden",xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),p("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),p("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),p("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]})]})]})]}),p("div",{className:"space-y-2",children:[p(_t,{htmlFor:"re-enter-password",style:W,children:y.t("confirm_password","Confirm Password")}),p("div",{className:"relative","data-password-toggle":!0,children:[p(Pt,{id:"re-enter-password",name:"re-enter-password",type:"password","data-password-input":"re-enter-password",placeholder:y.t("reenter_new_password_placeholder","Re-enter new password"),required:!0,error:!!t,className:"border pr-8",style:M}),p("button",{type:"button","data-password-toggle-btn":!0,className:"absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 transition-colors","aria-label":y.t("toggle_password_visibility","Toggle password visibility"),children:[p("svg",{"data-show-icon":!0,xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),p("circle",{cx:"12",cy:"12",r:"3"})]}),p("svg",{"data-hide-icon":!0,className:"hidden",xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),p("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),p("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),p("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]})]})]})]}),t&&p(Re,{children:t}),p(Jt,{type:"submit",className:"w-full",style:ce,disabled:!1,children:y.t("reset_password_cta","Reset Password")})]})})]})})},Dx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.z.string().openapi({description:"The code parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,loginSession:s,useShadcn:a}=await he(t,e);if(!s.authParams.username)throw new v(400,{message:"Username required"});return a?t.html(p(we,{title:y.t("reset_password_title","Reset Password"),theme:n,branding:r,client:i,children:p(Pi,{theme:n,branding:r,loginSession:s,email:s.authParams.username,client:i})})):t.html(p(Rr,{theme:n,branding:r,client:i,email:s.authParams.username}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.z.string().openapi({description:"The code parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({password:o.z.string(),"re-enter-password":o.z.string()})}}}},responses:{200:{description:"Response"}}}),async t=>{const{state:e,code:n}=t.req.valid("query"),{password:r,"re-enter-password":i}=t.req.valid("form"),{env:s}=t,{theme:a,branding:c,client:l,loginSession:d,useShadcn:u}=await he(t,e);if(!d.authParams.username)throw new v(400,{message:"Username required"});if(r!==i)return u?t.html(p(we,{title:y.t("reset_password_title","Reset Password"),theme:a,branding:c,client:l,children:p(Pi,{error:y.t("create_account_passwords_didnt_match"),theme:a,branding:c,loginSession:d,email:d.authParams.username,client:l})}),400):t.html(p(Rr,{error:y.t("create_account_passwords_didnt_match"),theme:a,branding:c,client:l,email:d.authParams.username}),400);const f=await pi({userAdapter:s.data.users,tenant_id:l.tenant.id,username:d.authParams.username,provider:"auth2"});if(!f)throw new v(400,{message:"User not found"});const g=await Vp(s.data,l.tenant.id,f.connection);try{await Hp(g,{tenantId:l.tenant.id,userId:f.user_id,newPassword:r,userData:f,data:s.data})}catch(_){const w=_?.message||y.t("create_account_weak_password");return u?t.html(p(we,{title:y.t("reset_password_title","Reset Password"),theme:a,branding:c,client:l,children:p(Pi,{error:w,theme:a,branding:c,loginSession:d,email:d.authParams.username,client:l})}),400):t.html(p(Rr,{error:w,theme:a,branding:c,client:l,email:d.authParams.username}),400)}try{if(!await s.data.codes.get(l.tenant.id,n,"password_reset")){const k=y.t("password_reset_code_expired","Code not found or expired");return u?t.html(p(we,{title:y.t("reset_password_title","Reset Password"),theme:a,branding:c,client:l,children:p(Pi,{error:k,theme:a,branding:c,loginSession:d,email:d.authParams.username,client:l})}),400):t.html(p(Rr,{error:k,theme:a,branding:c,client:l,email:d.authParams.username}),400)}const w=await s.data.passwords.get(l.tenant.id,f.user_id);w&&await s.data.passwords.update(l.tenant.id,{id:w.id,user_id:f.user_id,password:w.password,algorithm:w.algorithm,is_current:!1}),await s.data.passwords.create(l.tenant.id,{user_id:f.user_id,password:await Pn.hash(r,10),algorithm:"bcrypt",is_current:!0}),f.email_verified||await s.data.users.update(l.tenant.id,f.user_id,{email_verified:!0}),await ie(t,l.tenant.id,{type:te.SUCCESS_CHANGE_PASSWORD,description:`Password changed for ${f.email}`,userId:f.user_id})}catch(_){console.error("Password reset failed:",_);const w=_ instanceof Error?_.message:JSON.stringify(_);await ie(t,l.tenant.id,{type:te.FAILED_CHANGE_PASSWORD,description:`Password reset failed for ${f.email}: ${w}`,userId:f.user_id});let k;return _ instanceof Ht?k=y.t(_.code,{defaultValue:_.message,..._.params}):k=y.t("password_reset_failed","The password could not be reset"),u?t.html(p(we,{title:y.t("reset_password_title","Reset Password"),theme:a,branding:c,client:l,children:p(Pi,{error:k,theme:a,branding:c,loginSession:d,email:d.authParams.username,client:l})}),400):t.html(p(Rr,{error:k,theme:a,branding:c,client:l,email:d.authParams.username}),400)}return t.html(p(wt,{message:y.t("password_has_been_reset"),theme:a,branding:c,client:l,state:e}))}),nw=t=>{const{error:e,theme:n,branding:r,client:i,email:s,state:a}=t;return p(Se,{title:y.t("forgot_password_title"),theme:n,branding:r,client:i,children:[p("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:y.t("forgot_password_title")}),p("div",{className:"mb-6 text-gray-300",children:y.t("forgot_password_description")}),p("div",{className:"flex flex-1 flex-col justify-center",children:[p(Bt,{className:"pt-2",children:[p("input",{type:"email",name:"username",placeholder:y.t("email_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",value:s,disabled:!!s}),e&&p(Re,{children:e}),p(xe,{className:"sm:mt-4 !text-base",children:y.t("forgot_password_cta")})]}),p(lt,{state:a})]})]})},Mx=({error:t,theme:e,branding:n,loginSession:r,email:i,className:s})=>{const a=e?.colors?.primary_button||n?.colors?.primary||"#0066cc",c=e?.colors?.primary_button_label||"#ffffff",l=e?.colors?.body_text||"#333333",d=e?.colors?.input_background||"#ffffff",u=e?.colors?.input_border||"#d1d5db",f=e?.colors?.input_filled_text||"#111827",g=e?.colors?.error||"#dc2626",_=e?.colors?.widget_background||"#ffffff",w=e?.colors?.widget_border||"#e5e7eb",k=e?.borders?.widget_corner_radius||8,z=e?.borders?.input_border_radius||4,N=e?.borders?.button_border_radius||4,I=e?.borders?.show_widget_shadow??!0,S=e?.fonts?.title?.size||24,E=e?.fonts?.title?.bold??!0,P=e?.fonts?.body_text?.size||14,G={backgroundColor:_,borderColor:w,borderRadius:`${k}px`,boxShadow:I?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:l},Z={fontSize:`${S}px`,fontWeight:E?"700":"400",color:e?.colors?.header||l},W={fontSize:`${P}px`,color:e?.colors?.input_labels_placeholders||"#6b7280"},M={backgroundColor:d,borderColor:t?g:u,borderRadius:`${z}px`,color:f},ce={backgroundColor:a,color:c,borderRadius:`${N}px`},le=e?.widget?.logo_position||"center",fe=le==="left"?"text-left":le==="right"?"text-right":"text-center",$e=e?.widget?.logo_url||n?.logo_url,be=le!=="none"&&$e;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",s),children:p(en,{style:G,className:"border",children:[p(tn,{children:[be&&p("div",{className:Q("mb-4",fe),children:p(Rt,{theme:e,branding:n})}),p(nn,{style:Z,children:y.t("forgot_password_title","Forgot Password")}),p(rn,{style:W,children:y.t("forgot_password_description","Enter your email address and we'll send you a link to reset your password.")})]}),p(on,{children:[p("form",{method:"post",className:"space-y-4",children:[p("input",{type:"hidden",name:"state",value:r.authParams.state}),p("div",{className:"space-y-2",children:[p(_t,{htmlFor:"username",style:W,className:"text-sm font-medium",children:y.t("email_label","Email")}),p(Pt,{id:"username",type:"email",name:"username",placeholder:y.t("email_placeholder","Email Address"),value:i,disabled:!!i,style:M,className:"w-full",required:!0})]}),t&&p(Re,{children:t}),p(Jt,{type:"submit",className:"w-full",style:ce,disabled:!1,children:y.t("forgot_password_cta","Send Reset Link")})]}),p("div",{className:"mt-4 text-center",children:p("a",{href:`/u/login/identifier?state=${encodeURIComponent(r.authParams.state||"")}`,className:"text-sm",style:{color:a},children:y.t("back_to_login","Back to Login")})})]})]})})},rw=t=>{const{theme:e,branding:n,client:r,state:i}=t;return p(Se,{title:"Login",theme:e,branding:n,client:r,children:[p("div",{className:"flex flex-1 flex-col justify-center",children:[p("div",{children:y.t("forgot_password_email_sent")}),p("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[p(Ne,{className:"text-base",name:"info-bubble"}),p("div",{className:"text-sm text-gray-300 md:text-sm",children:y.t("sent_code_spam")})]})]}),p(lt,{state:i})]})},qx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,loginSession:s,useShadcn:a}=await he(t,e);return a?t.html(p(we,{title:y.t("forgot_password_title","Forgot Password"),theme:n,branding:r,client:i,children:p(Mx,{theme:n,branding:r,loginSession:s,email:s.authParams.username,client:i})})):t.html(p(nw,{theme:n,branding:r,client:i,state:e,email:s.authParams.username}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,loginSession:s}=await he(t,e);return await D8(t,i,s.authParams.username,s.id),t.html(p(rw,{theme:n,branding:r,client:i,state:e}))}),iw=({theme:t,branding:e,client:n,state:r,user:i})=>p(Se,{title:X("check_email_title"),theme:t,branding:e,client:n,children:p("div",{className:"flex flex-1 flex-col justify-center",children:[p("div",{className:"mb-8 text-gray-700 dark:text-gray-300",children:[p(Un,{i18nKey:"currently_logged_in_as",components:[p("span",{className:"font-semibold text-gray-900 dark:text-white"},"span")],values:{email:i.email||""}}),p("br",{}),X("continue_with_sso_provider_headline")]}),p("div",{className:"space-y-6",children:[p(Bt,{children:p(xe,{className:"!text-base",children:p("span",{children:y.t("yes_continue_with_existing_account")})})}),p("a",{className:"block text-center text-primary hover:text-primaryHover focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 dark:focus:ring-offset-gray-900",href:`/u/login/identifier?state=${encodeURIComponent(r)}`,children:y.t("no_use_another")})]})]})}),Fx=({theme:t,branding:e,state:n,user:r,className:i})=>{const s=t?.colors?.primary_button||e?.colors?.primary||"#0066cc",a=t?.colors?.primary_button_label||"#ffffff",c=t?.colors?.body_text||"#333333",l=t?.colors?.widget_background||"#ffffff",d=t?.colors?.widget_border||"#e5e7eb",u=t?.borders?.widget_corner_radius||8,f=t?.borders?.button_border_radius||4,g=t?.borders?.show_widget_shadow??!0,_=t?.fonts?.title?.size||24,w=t?.fonts?.title?.bold??!0,k=t?.fonts?.body_text?.size||14,z={backgroundColor:l,borderColor:d,borderRadius:`${u}px`,boxShadow:g?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:c},N={fontSize:`${_}px`,fontWeight:w?"700":"400",color:t?.colors?.header||c},I={fontSize:`${k}px`,color:t?.colors?.input_labels_placeholders||"#6b7280"},S={backgroundColor:s,color:a,borderRadius:`${f}px`},E={color:t?.colors?.links_focused_components||s,fontSize:`${k}px`},P=t?.widget?.logo_position||"center",G=P==="left"?"text-left":P==="right"?"text-right":"text-center",Z=t?.widget?.logo_url||e?.logo_url,W=P!=="none"&&Z;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",i),children:p(en,{style:z,className:"border",children:[p(tn,{children:[W&&p("div",{className:Q("mb-4",G),children:p(Rt,{theme:t,branding:e})}),p(nn,{style:N,children:y.t("continue_with_account","Continue with account")}),p(rn,{style:I,children:[p(Un,{i18nKey:"currently_logged_in_as",components:[p("span",{className:"font-semibold"},"span")],values:{email:r.email||""}}),p("br",{}),p("br",{}),y.t("continue_with_sso_provider_headline","Do you want to continue with this account?")]})]}),p(on,{children:p("form",{method:"post",children:p("div",{className:"grid gap-4",children:[p(Jt,{type:"submit",className:"w-full transition-colors hover:brightness-90",style:S,children:y.t("yes_continue_with_existing_account","Yes, continue")}),p("div",{className:"text-center",children:p("a",{href:`/u/login/identifier?state=${encodeURIComponent(n)}`,className:"text-sm hover:underline focus:outline-none focus:ring-2 focus:ring-offset-2 transition-colors",style:E,children:y.t("no_use_another","No, use another account")})})]})})})]})})},Hx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"HTML page to check account status or verify email.",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to login identifier page if no valid session.",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{env:e}=t,{state:n}=t.req.valid("query"),{theme:r,branding:i,client:s,useShadcn:a}=await he(t,n);if(!s||!s.tenant?.id)return console.error("Client or tenant ID missing in GET /u/check-account after initJSXRoute"),t.html(p(wt,{theme:r,branding:i,client:s,state:n,pageTitle:y.t("error_page_title")||"Error",message:y.t("configuration_error_message")||"A configuration error occurred."}),500);const c=Wr(s.tenant.id,t.req.header("cookie")),l=c?await e.data.sessions.get(s.tenant.id,c):null;if(!l)return t.redirect(`/u/login/identifier?state=${n}`);const d=await e.data.users.get(s.tenant.id,l.user_id);return d?a?t.html(p(we,{title:y.t("continue_with_account","Continue with account"),theme:r,branding:i,client:s,children:p(Fx,{theme:r,branding:i,client:s,state:n,user:d})})):t.html(p(iw,{theme:r,branding:i,client:s,state:n,user:d})):t.redirect(`/u/login/identifier?state=${n}`)}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{302:{description:"Redirect to continue authentication flow or to login identifier.",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page for unexpected issues or if TokenResponse is returned.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{env:e}=t,{state:n}=t.req.valid("query"),{theme:r,branding:i,client:s,loginSession:a}=await he(t,n);if(!s||!s.tenant?.id)return console.error("Client or tenant ID missing in POST /u/check-account after initJSXRoute"),t.html(p(wt,{theme:r,branding:i,client:s,state:n,pageTitle:y.t("error_page_title")||"Error",message:y.t("configuration_error_message")}),500);const c=Wr(s.tenant.id,t.req.header("cookie")),l=c?await e.data.sessions.get(s.tenant.id,c):null;if(!l)return t.redirect(`/u/login/identifier?state=${n}`);const d=await e.data.users.get(s.tenant.id,l.user_id);if(!d)return t.redirect(`/u/login/identifier?state=${n}`);await e.data.loginSessions.update(s.tenant.id,a.id,{session_id:l.id});const u=await Gt(t,{user:d,authParams:a.authParams,client:s,loginSession:{...a,session_id:l.id},sessionId:l.id});if(!(u instanceof Response))throw new v(500,{message:y.t("unexpected_error_try_again")});return u}),Vx=({width:t=18,height:e=18,className:n})=>p("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:e,viewBox:"0 0 640 640",className:n,fill:"currentColor",role:"img",focusable:"false",children:p("path",{d:"M416.9 85.2 372 130.1 509.9 268l44.9-44.9c13.6-13.5 21.2-31.9 21.2-51.1s-7.6-37.6-21.2-51.1l-35.7-35.7C505.6 71.6 487.2 64 468 64s-37.6 7.6-51.1 21.2M338.1 164 122.9 379.1c-10.7 10.7-18.5 24.1-22.6 38.7L64.9 545.6c-2.3 8.3 0 17.3 6.2 23.4s15.1 8.5 23.4 6.2l127.8-35.5c14.6-4.1 27.9-11.8 38.7-22.6l215-215.2z"})}),Kx=!1,A0=t=>{const{theme:e,branding:n,user:r,client:i,error:s,success:a,state:c,csrfToken:l}=t;return r.identities?.filter(d=>!(d.provider===r.provider&&d.user_id===r.user_id.split("|")[1])),p(Se,{title:y.t("account_title")||"Account Settings",theme:e,branding:n,client:i,children:[p("div",{className:"mb-4 text-2xl font-medium",children:y.t("account_title")}),p("div",{className:"mb-8 text-gray-300",children:y.t("account_page_description")}),s&&p(Re,{className:"mb-8",children:s}),a&&p("div",{className:"mb-8 text-green",children:a}),p("div",{className:"column-left gap-6 border-y border-gray-200/50 py-6 mb-8",children:[p("div",{className:"row-left w-full !justify-between !flex-nowrap gap-4",children:[p("div",{className:"column-left gap-1.5",children:[p("div",{className:"text-gray-300",children:y.t("email_placeholder")}),p("div",{className:"font-medium text-base text-gray-800 line-clamp-1 break-all",children:r.email||y.t("no_email_address")})]}),p("a",{className:"bg-gray-200/40 p-2 rounded-md hover:bg-gray-200/75",title:y.t("edit"),"aria-label":y.t("edit"),href:c?`/u/account/change-email?state=${encodeURIComponent(c)}`:`/u/account/change-email?client_id=${encodeURIComponent(i.client_id)}`,children:p(Vx,{})})]}),Kx]})]})},Gx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"HTML page showing account management interface.",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to login if no session",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{env:e}=t,{state:n}=t.req.valid("query"),{theme:r,branding:i,client:s,user:a,loginSession:c}=await $r(t,n);if(!s||!s.tenant?.id)return console.error("Client or tenant ID missing in GET /u/account after initJSXRoute"),t.html(p(wt,{theme:r,branding:i,client:s,state:n,pageTitle:y.t("error_page_title")||"Error",message:y.t("configuration_error_message")||"A configuration error occurred."}),500);const l=pe();return await e.data.loginSessions.update(s.tenant.id,c.id,{csrf_token:l}),t.html(p(A0,{theme:r,branding:i,user:a,client:s,state:n,csrfToken:l}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({action:o.z.enum(["unlink_account"]),provider:o.z.string().optional(),user_id:o.z.string().optional(),csrf_token:o.z.string().optional()})}}}},responses:{200:{description:"HTML response with form results",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to login if no session",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{env:e}=t,{state:n}=t.req.valid("query"),r=t.req.valid("form"),{theme:i,branding:s,client:a,user:c,loginSession:l}=await $r(t,n);let d,u;try{if(r.action==="unlink_account"&&r.provider&&r.user_id){if(!r.csrf_token||r.csrf_token!==l.csrf_token)throw new Error("Invalid CSRF token");await e.data.users.unlink(a.tenant.id,c.user_id,r.provider,r.user_id),u=y.t("account_unlinked_successfully")||"Account unlinked successfully"}}catch{d=y.t("operation_failed")||"Operation failed"}const f=await e.data.users.get(a.tenant.id,c.user_id),g=pe();return await e.data.loginSessions.update(a.tenant.id,l.id,{csrf_token:g}),t.html(p(A0,{theme:i,branding:s,user:f||c,client:a,error:d,success:u,state:n,csrfToken:g}))}),E0=t=>{const{theme:e,branding:n,user:r,client:i,state:s,error:a}=t;return p(Se,{title:y.t("change_email"),theme:e,branding:n,client:i,children:[p("div",{className:"mb-4 text-2xl font-medium",children:y.t("change_email")}),p("div",{className:"column-left gap-1 mb-8",children:[p("div",{className:"text-gray-300",children:y.t("current_email")}),p("div",{className:"font-medium text-base text-gray-800",children:r.email||y.t("no_email_address")})]}),p("div",{className:"flex flex-1 flex-col justify-center",children:[p(Bt,{children:[p("input",{type:"email",id:"email",name:"email",placeholder:y.t("new_email"),className:Q("mb-2 w-full rounded-lg border bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",{"border-red":a,"border-gray-100 dark:border-gray-500":!a}),required:!0}),a&&p(Re,{children:a}),p(xe,{className:"sm:mt-4 !text-base",children:[p("span",{children:y.t("continue")}),p(Ne,{className:"text-xs",name:"arrow-right"})]}),p("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[p("span",{className:"uicon-info-bubble text-base"}),p("div",{className:"text-sm text-gray-300 md:text-sm",children:y.t("new_email_code_info")})]})]}),p("a",{className:"block text-primary hover:text-primaryHover text-center",href:`/u/account?state=${encodeURIComponent(s)}`,children:y.t("go_back")})]})]})},Wx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"HTML page showing email change interface.",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to login if no session",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,user:s}=await $r(t,e);return t.html(p(E0,{theme:n,branding:r,user:s,client:i,state:e}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({email:o.z.string().toLowerCase()})}}}},responses:{200:{description:"HTML response with form results",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to change-email verification page",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{env:e}=t,{state:n}=t.req.valid("query"),{email:r}=t.req.valid("form"),{theme:i,branding:s,client:a,user:c,loginSession:l}=await $r(t,n),d=await e.data.users.list(a.tenant.id,{page:1,per_page:1,include_totals:!1,q:`email:"${r}"`});if(d.users.length>0&&d.users[0]?.user_id!==c.user_id)return t.html(p(E0,{theme:i,branding:s,user:c,client:a,state:n,error:y.t("email_already_taken")||"Email is already taken"}));const u=Ln(),f=pe();await e.data.codes.create(a.tenant.id,{code_id:f,login_id:"",code_type:"email_verification",expires_at:new Date(Date.now()+Hl).toISOString(),user_id:c.user_id}),await e.data.codes.create(a.tenant.id,{code_id:u,login_id:"",code_type:"email_verification",expires_at:new Date(Date.now()+Hl).toISOString(),user_id:c.user_id});const g=l.authParams?.ui_locales?.split(" ")?.map(_=>_.split("-")[0])[0];return await Kp(t,{to:r,code:u,language:g}),t.redirect(`/u/account/change-email-verify?state=${encodeURIComponent(n)}&email=${encodeURIComponent(r)}&change_id=${f}`)}),C0=6,$u=({error:t,theme:e,branding:n,client:r,email:i,success:s,state:a,redirectUrl:c})=>s?p(Se,{title:y.t("success"),theme:e,branding:n,client:r,children:[p("div",{className:"mb-4 text-2xl font-medium",children:y.t("success")}),p("div",{className:"mb-8 text-gray-300",children:p(Un,{i18nKey:"email_changed_to_template",components:[p("span",{className:"text-black dark:text-white"},"span")],values:{email:i}})}),p("div",{className:"flex flex-1 flex-col justify-center",children:p(xe,{Component:"a",href:c||(a?`/u/account?state=${encodeURIComponent(a)}`:`/u/account?client_id=${encodeURIComponent(r.client_id)}`),className:"sm:mt-4 !text-base",children:[p("span",{children:y.t("continue")}),p(Ne,{className:"text-xs",name:"arrow-right"})]})})]}):p(Se,{title:y.t("verify_email_verify"),theme:e,branding:n,client:r,children:[p("div",{className:"mb-4 text-2xl font-medium",children:y.t("verify_email_verify")}),p("div",{className:"mb-8 text-gray-300",children:p(Un,{i18nKey:"code_sent_template",components:[p("span",{className:"text-black dark:text-white"},"span")],values:{username:i}})}),p("div",{className:"flex flex-1 flex-col justify-center",children:[p(Bt,{className:"pt-2",children:[p("input",{autoFocus:!0,type:"text",pattern:"[0-9]*",maxLength:C0,inputMode:"numeric",name:"code",placeholder:"******",className:Q("mb-2 w-full rounded-lg border bg-gray-100 px-4 pb-2 pt-2.5 text-center indent-[5px] font-mono text-3xl placeholder:text-gray-300 dark:bg-gray-600 md:text-3xl",{"border-red":t,"border-gray-100 dark:border-gray-500":!t}),minLength:C0,required:!0,id:"code-input"}),t&&p(Re,{children:t}),p(xe,{className:"sm:mt-4 !text-base",children:[p("span",{children:y.t("continue")}),p(Ne,{className:"text-xs",name:"arrow-right"})]}),p("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[p(Ne,{className:"text-base",name:"info-bubble"}),p("div",{className:"text-sm text-gray-300 md:text-sm",children:y.t("sent_code_spam")})]})]}),p("a",{className:"block text-primary hover:text-primaryHover text-center",href:a?`/u/account?state=${encodeURIComponent(a)}`:`/u/account?client_id=${encodeURIComponent(r.client_id)}`,children:y.t("go_back")})]})]}),Jx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),email:o.z.string().email(),change_id:o.z.string()})},responses:{200:{description:"HTML page for email change verification",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to account or login if no session",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{state:e,email:n,change_id:r}=t.req.valid("query"),{theme:i,branding:s,client:a,user:c}=await $r(t,e),l=await t.env.data.codes.get(a.tenant.id,r,"email_verification");return!l||l.user_id!==c.user_id?t.redirect(`/u/account?state=${e}`):t.html(p($u,{theme:i,branding:s,client:a,email:n,state:e}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),email:o.z.string().toLowerCase(),change_id:o.z.string()}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({code:o.z.string()})}}}},responses:{200:{description:"HTML response with verification result",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to confirmation page on success",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{env:e}=t,{state:n,email:r,change_id:i}=t.req.valid("query"),{code:s}=t.req.valid("form"),{theme:a,branding:c,client:l,user:d}=await $r(t,n);let u;try{const f=await e.data.codes.get(l.tenant.id,i,"email_verification");if(!f)u=y.t("invalid_request");else if(f.user_id!==d.user_id)u=y.t("invalid_request");else if(f.used_at)u=y.t("code_already_used");else if(new Date(f.expires_at)<new Date)u=y.t("code_expired");else{const g=await e.data.codes.get(l.tenant.id,s,"email_verification");if(!g)u=y.t("invalid_code");else if(g.used_at)u=y.t("code_already_used");else if(new Date(g.expires_at)<new Date)u=y.t("code_expired");else if(g.user_id!==d.user_id)u=y.t("invalid_code");else return await e.data.codes.used(l.tenant.id,i),await e.data.codes.used(l.tenant.id,s),await e.data.users.update(l.tenant.id,d.user_id,{email:r,email_verified:!0}),t.redirect(`/u/account/change-email-confirmation?state=${encodeURIComponent(n)}&email=${encodeURIComponent(r)}`)}}catch{u=y.t("operation_failed")}return t.html(p($u,{theme:a,branding:c,client:l,email:r,error:u,state:n}))}),Xx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),email:o.z.string().email()})},responses:{200:{description:"HTML page showing email change confirmation",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to login if no session",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{state:e,email:n}=t.req.valid("query"),{theme:r,branding:i,client:s,loginSession:a}=await $r(t,e);if(!s||!s.tenant?.id)return console.error("Client or tenant ID missing in GET /u/change-email-confirmation after initJSXRoute"),t.html(p(wt,{theme:r,branding:i,client:s,state:e,pageTitle:y.t("error_page_title")||"Error",message:y.t("configuration_error_message")||"A configuration error occurred."}),500);let c=`/u/account?state=${encodeURIComponent(e)}`;return a?.authorization_url&&new URL(a.authorization_url).searchParams.get("screen_hint")==="change-email"&&(c=a.authParams?.redirect_uri||c),t.html(p($u,{theme:r,branding:i,client:s,email:n,success:!0,state:e,redirectUrl:c}))}),ow=t=>{const{theme:e,branding:n,client:r,email:i,state:s}=t;return p(Se,{title:y.t("create_password_account_title"),theme:e,branding:n,client:r,children:[p("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:y.t("create_password_account_title")}),p("div",{className:"mb-6 text-gray-300",children:y.t("enter_email_for_verification_description")}),p("div",{className:"flex flex-1 flex-col justify-center",children:p(Bt,{className:"pt-2",children:[p("input",{type:"email",name:"username",placeholder:y.t("email_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",required:!0,value:i,disabled:!0}),p(xe,{className:"sm:mt-4 !text-base",children:y.t("send")})]})}),p(lt,{state:s})]})},Zx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,loginSession:s}=await he(t,e),{username:a}=s.authParams;if(!a)throw new v(400,{message:"Username required"});return t.html(p(ow,{state:e,theme:n,branding:r,client:i,email:a}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{loginSession:n,client:r}=await he(t,e),{username:i}=n.authParams;if(!i)throw new v(400,{message:"Username required"});const s=await t.env.data.codes.create(r.tenant.id,{code_id:Ln(),code_type:"email_verification",login_id:n.id,expires_at:new Date(Date.now()+Hl).toISOString()});return await T8(t,i,s.code_id,n.id),t.redirect(`/u/pre-signup-sent?state=${e}`)}),sw=t=>{const{redirectUrl:e,theme:n,branding:r,client:i}=t;return p(Se,{title:y.t("invalid_session_title"),theme:n,branding:r,client:i,children:[p("div",{className:"flex flex-1 flex-col justify-center",children:y.t("invalid_session_body")}),p("div",{className:"flex flex-1 flex-col justify-center",children:e&&p("a",{className:"block text-primary hover:text-primaryHover text-center",href:e,children:y.t("go_back")})})]})},Yx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string()})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,loginSession:s}=await he(t,e);let a;return s.authParams.redirect_uri&&s.authParams.state&&(a=new URL(s.authParams.redirect_uri),a.searchParams.set("state",s.authParams.state),a.searchParams.set("error","invalid_session"),a.searchParams.set("error_description",s.authParams.username||"")),t.html(p(sw,{redirectUrl:a?.href,theme:n,branding:r,client:i}))}),Qx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.z.string().openapi({description:"The code parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i}=await he(t,e);return t.html(p(wt,{message:"Not implemented",pageTitle:"User info",theme:n,branding:r,client:i,state:e}))}),aw=({theme:t,branding:e,client:n,state:r})=>{const i=new URLSearchParams({state:r});return p(Se,{title:y.t("email_validated"),theme:t,branding:e,client:n,children:[p("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:y.t("email_validated")}),p("div",{className:"flex flex-1 flex-col justify-center mb-7",children:p(xe,{Component:"a",href:`/u/enter-password?${i}`,className:"text-base sm:mt-4 md:text-base",children:p("div",{className:"flex items-center space-x-2",children:[p("span",{children:y.t("email_validated_cta")}),p(Ne,{className:"text-xs",name:"arrow-right"})]})})})]})},eS=({theme:t,branding:e,loginSession:n,className:r})=>{const i=t?.colors?.primary_button||e?.colors?.primary||"#0066cc",s=t?.colors?.primary_button_label||"#ffffff",a=t?.colors?.body_text||"#333333",c=t?.colors?.widget_background||"#ffffff",l=t?.colors?.widget_border||"#e5e7eb",d=t?.colors?.success||"#10b981",u=t?.borders?.widget_corner_radius||8,f=t?.borders?.button_border_radius||4,g=t?.borders?.show_widget_shadow??!0,_=t?.fonts?.title?.size||24,w=t?.fonts?.title?.bold??!0,k=t?.fonts?.body_text?.size||14,z={backgroundColor:c,borderColor:l,borderRadius:`${u}px`,boxShadow:g?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:a},N={fontSize:`${_}px`,fontWeight:w?"700":"400",color:t?.colors?.header||a},I={fontSize:`${k}px`,color:t?.colors?.input_labels_placeholders||"#6b7280"},S={backgroundColor:i,color:s,borderRadius:`${f}px`},E=t?.widget?.logo_position||"center",P=E==="left"?"text-left":E==="right"?"text-right":"text-center",G=t?.widget?.logo_url||e?.logo_url,Z=E!=="none"&&G;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",r),children:p(en,{style:z,className:"border",children:[p(tn,{children:[Z&&p("div",{className:Q("mb-4",P),children:p(Rt,{theme:t,branding:e})}),p("div",{className:"flex justify-center mb-4",children:p("div",{className:"rounded-full p-3",style:{backgroundColor:`${d}15`},children:p("svg",{xmlns:"http://www.w3.org/2000/svg",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:d,"stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),p("polyline",{points:"22 4 12 14.01 9 11.01"})]})})}),p(nn,{style:N,className:"text-center",children:y.t("email_validated","Email Verified")}),p(rn,{style:I,className:"text-center",children:y.t("email_validated_description","Your email has been successfully verified. You can now continue to login.")})]}),p(on,{children:p("a",{href:`/u/enter-password?state=${encodeURIComponent(n.authParams.state||"")}`,className:"w-full flex items-center justify-center gap-2 h-10 px-4 py-2 rounded-md font-medium transition-colors",style:S,children:[p("span",{children:y.t("email_validated_cta","Continue to Login")}),p("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),p("polyline",{points:"12 5 19 12 12 19"})]})]})})]})})},tS=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.z.string().openapi({description:"The code parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e,code:n}=t.req.valid("query"),{env:r}=t,{client:i,loginSession:s,theme:a,branding:c,useShadcn:l}=await he(t,e),{username:d}=s.authParams;if(!d)throw new v(400,{message:"Username not found in state"});const u=await pi({userAdapter:r.data.users,tenant_id:i.tenant.id,username:d,provider:"auth2"});if(!u)throw new v(500,{message:"No user found"});if(!await r.data.codes.get(i.tenant.id,n,"email_verification"))throw new v(400,{message:"Code not found or expired"});await r.data.users.update(i.tenant.id,u.user_id,{email_verified:!0});const _=(await Ru(r.data.users,i.tenant.id,d)).filter(w=>w.provider!=="auth2");if(_.length>0){const w=_.filter(k=>!k.linked_to);w.length>1&&console.error("More than one primary user found for email",d),w.length===0&&console.error("No primary user found for email",d),w.length===1&&await r.data.users.update(i.tenant.id,u.user_id,{linked_to:w[0]?.user_id})}return l?t.html(p(we,{title:y.t("email_validated","Email Verified"),theme:a,branding:c,client:i,children:p(eS,{theme:a,branding:c,loginSession:s,client:i})})):t.html(p(aw,{theme:a,branding:c,client:i,state:e}))}),cw=t=>{const{theme:e,branding:n,client:r,email:i,state:s}=t;return p(Se,{title:y.t("sign_up_success"),theme:e,branding:n,client:r,children:[p("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:y.t("email_verification_for_signup_sent_title")}),p("div",{className:"flex flex-1 flex-col justify-center",children:[p("div",{className:"mb-6 text-gray-300",children:p(Un,{i18nKey:"email_verification_for_signup_sent_description",components:[p("span",{className:"text-black dark:text-white"},"span")],values:{email:i}})}),p("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[p(Ne,{className:"text-base",name:"info-bubble"}),p("div",{className:"text-sm text-gray-300 md:text-sm",children:y.t("sent_code_spam")})]})]}),p(lt,{state:s})]})},nS=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,loginSession:s}=await he(t,e),{username:a}=s.authParams;if(!a)throw new v(400,{message:"Username required"});return t.html(p(cw,{theme:n,branding:r,client:i,state:e,email:a}))}),Zp=`
92
+ `},nx="https://assets.sesamy.com/images/login-bg.jpg",Se=({title:t,children:e,theme:n,branding:r,client:i})=>{const s={backgroundImage:`url(${n?.page_background?.background_image_url||nx})`};return p("html",{lang:y.language||"en",children:[p("head",{children:[p("title",{children:t}),p("meta",{charset:"UTF-8"}),p("meta",{name:"robots",content:"noindex, follow"}),p("link",{rel:"preload",href:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Regular.woff2",as:"font",type:"font/woff2",crossOrigin:"anonymous"}),p("link",{rel:"preload",href:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Medium.woff2",as:"font",type:"font/woff2",crossOrigin:"anonymous"}),p("link",{rel:"preload",href:"https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Bold.woff2",as:"font",type:"font/woff2",crossOrigin:"anonymous"}),p("link",{rel:"stylesheet",href:"/u/css/tailwind.css"}),p("meta",{name:"viewport",content:"width=device-width, initial-scale=1, maximum-scale=1"}),p("style",{children:tx(n,r)}),p("meta",{name:"theme-color",content:"#000000"})]}),p("body",{children:[p("div",{className:"row min-h-full w-full overflow-hidden bg-cover bg-center text-sm sm:bg-fixed sm:bg-left-top sm:pt-16 py-2",style:s,children:p("div",{className:"row-up-left w-[calc(100%-theme(space.2)-theme(space.2))] max-w-[1295px] !flex-nowrap sm:w-[calc(100%-theme(space.16)-theme(space.16))]",children:p("div",{className:"column-left w-full sm:w-auto",children:[p("div",{className:"relative flex w-full flex-col rounded-2xl bg-white px-5 py-10 dark:bg-gray-800 dark:text-white sm:min-h-[700px] sm:max-w-md sm:px-14 sm:py-14 md:min-w-[448px] short:min-h-[558px] min-h-[calc(100vh-83px)]",children:[p("div",{className:"mb-16",children:p(Rt,{theme:n,branding:r})}),p("div",{className:"flex flex-1 flex-col",children:[e,p(H1,{theme:n,branding:r,client:i})]})]}),p("div",{className:"flex w-full items-center px-6 pb-8 pt-4 justify-between",children:[p("div",{className:"flex justify-center leading-[0]",children:p("a",{href:"https://sesamy.com",target:"_blank",rel:"noreferrer",children:p(Ne,{name:"sesamy",className:"text-xl text-white"})})}),p("div",{className:"flex justify-center space-x-2 text-xs text-white sm:justify-normal md:text-xs"})]})]})})}),p("div",{id:"client-root"})]}),p("script",{type:"module",src:"/u/js/client.js"})]})},rx=t=>t==="small"?"text-base":t==="medium"?"text-2xl":t==="large"?"text-3xl":"",V1=({size:t})=>{const e=rx(t);return p("div",{className:"relative inline-block leading-[0]",children:[p(Ne,{className:Q("text-gray-200 dark:text-[#201a41]",{[e]:e}),name:"spinner-circle"}),p(Ne,{className:Q("absolute inset-0 animate-spin text-primary",{[e]:e}),name:"spinner-inner"})]})},xe=({children:t,className:e,Component:n="button",variant:r="primary",href:i,disabled:s,isLoading:a,id:c})=>{const l=n==="a"?{href:i}:{};return p(n,{class:Q("btn relative w-full rounded-lg text-center",{"px-4 py-5":r!=="custom","bg-primary text-textOnPrimary hover:bg-primaryHover":r==="primary","border border-gray-300 bg-white text-black":r==="secondary","pointer-events-none cursor-not-allowed opacity-40":s,"is-loading":a},"focus:outline-none focus:ring",e),type:"submit",disabled:s,id:c,...l,children:[p("span",{className:"btn-label flex items-center justify-center space-x-2",children:t}),p("div",{className:"btn-spinner absolute left-0 top-0 flex h-full w-full items-center justify-center",children:p(V1,{size:"medium"})})]})},K1=({connection:t,text:e,icon:n=null,canResize:r=!1,loginSession:i})=>{const s=new URLSearchParams({client_id:i.authParams.client_id,connection:t});i.authParams.response_type&&s.set("response_type",i.authParams.response_type),i.authParams.redirect_uri&&s.set("redirect_uri",i.authParams.redirect_uri),i.authParams.scope&&s.set("scope",i.authParams.scope),i.authParams.nonce&&s.set("nonce",i.authParams.nonce),i.authParams.response_type&&s.set("response_type",i.authParams.response_type),i.authParams.state&&s.set("state",i.id);const a=`/authorize?${s.toString()}`;return p(xe,{className:Q("border border-gray-200 bg-white hover:bg-gray-100 dark:border-gray-400 dark:bg-black dark:hover:bg-black/90",{"px-0 py-3 sm:px-10 sm:py-4 short:px-0 short:py-3":r,"px-10 py-3":!r}),variant:"custom","aria-label":e,Component:"a",href:a,children:[n||"",p("div",{className:Q("text-left text-black dark:text-white sm:text-base",{"hidden sm:inline short:hidden":r}),children:e})]})},Bt=({children:t,className:e})=>p("form",{id:"form",method:"post",className:e,children:t}),Rs=({error:t,theme:e,branding:n,loginSession:r,email:i,client:s,isEmbedded:a,browserName:c})=>{const l=s.connections.map(({strategy:S})=>S),d=l.includes("email")||l.includes("Username-Password-Authentication"),u=l.includes("sms"),f=new Set(["email","sms","Username-Password-Authentication","auth0"]),g=s.connections.filter(S=>!f.has(S.strategy)).filter(S=>S.show_as_button!==!1).map(S=>{const E=Fu[S.strategy];return E?{...E,connectionName:S.name,displayName:S.display_name||E.displayName||S.name,iconUrl:S.options.icon_url}:null}).filter(S=>S!==null).filter(S=>!(a&&S.disableEmbeddedBrowsers)),_=d||u;let w="text",k="username";const z=d&&u?"email_or_phone_placeholder":d?"email_placeholder":"phone_placeholder";let N=y.t(z,d&&u?"Email or Phone Number":d?"Email Address":"Phone Number");return p(Se,{title:y.t("welcome"),theme:e,branding:n,client:s,children:[p("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:p("div",{className:"flex items-start gap-3",children:[p("span",{className:"text-lg leading-none",children:"⚠️"}),p("div",{children:[p("strong",{children:y.t("incognito_mode_detected","Incognito Mode Detected")}),p("p",{className:"mt-1 text-xs opacity-90",children:y.t("incognito_mode_warning","You are in incognito/private mode. Session data may not persist across page refreshes. Some features might not work as expected.")})]})]})}),a&&p("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:p("div",{className:"flex items-start gap-3",children:[p("span",{className:"text-lg leading-none",children:"⚠️"}),p("div",{children:[p("strong",{children:y.t("embedded_browser_detected")}),p("p",{className:"mt-1 text-xs opacity-90",children:y.t("embedded_browser_warning",{browserName:c||"app"})})]})]})}),p("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:y.t("welcome")}),p("div",{className:"mb-8 text-gray-300",children:_?y.t("login_description_template",{authMethod:y.t(z,{defaultValue:d&&u?"email or phone number":d?"email address":"phone number"}).toLocaleLowerCase(),defaultValue:"Sign in with your {{authMethod}}"}):y.t("login_description_social_only","Choose how to login")}),p("div",{className:"flex flex-1 flex-col justify-center",children:[_&&p(Bt,{className:"mb-7",children:[p("input",{type:w,name:k,placeholder:N,className:Q("mb-2 w-full rounded-lg border bg-gray-100 px-4 py-5 text-base lowercase placeholder:normal-case placeholder:text-gray-300 dark:bg-gray-600 md:text-base",{"border-red":t,"border-gray-100 dark:border-gray-500":!t}),required:!0,value:i||""}),t&&p(Re,{children:t}),p(xe,{className:"sm:mt-4 !text-base",children:[p("span",{children:y.t("continue")}),p(Ne,{className:"text-xs",name:"arrow-right"})]})]}),_&&g.length>0&&p("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[p("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),p("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:y.t("continue_social_login")})]}),p("div",{className:"flex space-x-4 sm:flex-col sm:space-x-0 sm:space-y-4 short:flex-row short:space-x-4 short:space-y-0",children:g.map(S=>{const E=S.logo;return p(K1,{connection:S.connectionName,text:y.t("continue_with",{provider:S.displayName}),canResize:!0,icon:p(E,{className:"h-5 w-5 sm:absolute sm:left-4 sm:top-1/2 sm:h-6 sm:w-6 sm:-translate-y-1/2 short:static short:left-auto short:top-auto short:h-5 short:w-5 short:translate-y-0",iconUrl:S.iconUrl}),loginSession:r},S.connectionName)})})]})]})},ix="https://assets.sesamy.com/images/login-bg.jpg",we=({title:t,children:e,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??ix,l=c?.startsWith("linear-gradient")||c?.startsWith("radial-gradient")||c?.startsWith("conic-gradient"),d=c?l?c:`url(${c})`:void 0;let u="justify-center",f="p-6 md:p-10";i==="left"?(u="justify-start",f="pl-12 pr-6 py-6 md:pl-20 md:pr-10 md:py-10"):i==="right"&&(u="justify-end",f="pr-12 pl-6 py-6 md:pr-20 md:pl-10 md:py-10");const g=Q("min-h-screen w-full flex bg-cover bg-center",u,f),_={...d&&{backgroundImage:d},backgroundColor:s,display:"flex",alignItems:"stretch",justifyContent:i==="left"?"flex-start":i==="right"?"flex-end":"center",minHeight:"100vh",width:"100%"},w=Q("w-full max-w-sm","flex flex-col justify-center");return p("html",{lang:y.language||"en",children:[p("head",{children:[p("title",{children:t}),p("meta",{charset:"UTF-8"}),p("meta",{name:"robots",content:"noindex, follow"}),p("link",{rel:"stylesheet",href:"/u/css/tailwind.css"}),p("link",{rel:"stylesheet",href:"/u/css/shadcn-ui.css"}),p("meta",{name:"viewport",content:"width=device-width, initial-scale=1, maximum-scale=1"}),p("meta",{name:"theme-color",content:"#000000"}),r?.favicon_url&&p("link",{rel:"icon",type:"image/x-icon",href:r.favicon_url}),n?.fonts?.font_url&&p("link",{rel:"stylesheet",href:n.fonts.font_url})]}),p("body",{children:[p("div",{className:g,style:_,children:p("div",{className:w,children:[e,r?.powered_by_logo_url&&p("div",{className:"mt-5 text-left",children:p("a",{href:"https://authhero.com",target:"_blank",rel:"noopener noreferrer",className:"inline-block",children:p("img",{src:r.powered_by_logo_url,alt:"Powered by",className:"h-9 opacity-60 hover:opacity-100 transition-opacity"})})})]})}),p("div",{id:"client-root"}),p("script",{type:"module",src:"/u/js/client.js"})]})]})};class ox{parse(e){const n=this.detectEmbedded(e);return{browser:n.browser,isEmbedded:n.isEmbedded}}detectEmbedded(e){const n=[[/wv\)/i,"WebView"],[/GSA\//i,"Google Search App"],[/FBAN\//i,"Facebook"],[/FBAV\//i,"Facebook"],[/Instagram/i,"Instagram"],[/Snapchat/i,"Snapchat"],[/TikTok/i,"TikTok"],[/Twitter/i,"Twitter/X"],[/LinkedIn/i,"LinkedIn"],[/UC Browser/i,"UC Browser"],[/SamsungBrowser/i,"Samsung Internet"],[/Electron/i,"Electron"],[/Tauri/i,"Tauri"]];for(const[r,i]of n)if(r.test(e))return{isEmbedded:!0,browser:{name:i}};return{isEmbedded:!1}}}function h0(t){const n=new ox().parse(t);return{isEmbedded:n.isEmbedded??!1,browserName:n.browser?.name}}const sx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),impersonation:o.z.string().optional()})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,loginSession:i,client:s,useShadcn:a}=await he(t,e),c=t.req.header("user-agent")||"",{isEmbedded:l,browserName:d}=h0(c);return a?t.html(p(we,{title:y.t("welcome","Login"),theme:n,branding:r,client:s,children:p(Ts,{theme:n,branding:r,loginSession:i,client:s,email:i.authParams.username,isEmbedded:l,browserName:d})})):t.html(p(Rs,{theme:n,branding:r,loginSession:i,client:s,email:i.authParams.username,isEmbedded:l,browserName:d}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),style:o.z.enum(["classic","shadcn"]).optional().openapi({description:"UI style to use for the login page"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({username:o.z.string().transform(t=>t.toLowerCase()),login_selection:o.z.enum(["code","password"]).optional()})}}}},responses:{400:{description:"Error response"},302:{description:"Redirect to enter code or password"}}}),async t=>{const{env:e}=t,{state:n}=t.req.valid("query"),r=t.req.valid("form");t.set("body",r),t.set("username",r.username);const{client:i,loginSession:s,theme:a,branding:c,useShadcn:l}=await he(t,n);t.set("client_id",i.client_id);const d=t.req.header("user-agent")||"",{isEmbedded:u,browserName:f}=h0(d),g=t.get("countryCode"),{normalized:_,connectionType:w,provider:k}=nl(r.username,g),z=_?w==="email"?await tc({userAdapter:e.data.users,tenant_id:i.tenant.id,email:_}):await Jr({userAdapter:e.data.users,tenant_id:i.tenant.id,username:_,provider:k}):null;if(!(i.connections.find(W=>W.strategy===w)||z)||!_)return l?t.html(p(we,{title:y.t("welcome","Login"),theme:a,branding:c,client:i,children:p(Ts,{theme:a,branding:c,loginSession:s,error:y.t("invalid_identifier"),email:r.username,client:i,isEmbedded:u,browserName:f})}),400):t.html(p(Rs,{theme:a,branding:c,loginSession:s,error:y.t("invalid_identifier"),email:r.username,client:i}),400);if(z&&t.set("user_id",z.user_id),!z){const W=await p_(t,i,t.env.data,_,w);if(!W.allowed)return await ie(t,i.tenant.id,{type:te.FAILED_SIGNUP,description:W.reason||"Public signup is disabled"}),l?t.html(p(we,{title:y.t("welcome","Login"),theme:a,branding:c,client:i,children:p(Ts,{theme:a,branding:c,loginSession:s,error:y.t("user_account_does_not_exist"),email:r.username,client:i,isEmbedded:u,browserName:f})}),400):t.html(p(Rs,{theme:a,branding:c,loginSession:s,error:y.t("user_account_does_not_exist"),email:r.username,client:i,isEmbedded:u,browserName:f}),400)}if(s.authParams.username=_,await e.data.loginSessions.update(i.tenant.id,s.id,s),await X8(t,i,r.username,w,r.login_selection)==="password")return t.redirect(`/u/enter-password?state=${n}`);let S=Ln(),E=await e.data.codes.get(i.tenant.id,S,"otp");for(;E;)S=Ln(),E=await e.data.codes.get(i.tenant.id,S,"otp");const P=await t.env.data.codes.create(i.tenant.id,{code_id:S,code_type:"otp",login_id:s.id,expires_at:new Date(Date.now()+As).toISOString(),redirect_uri:s.authParams.redirect_uri}),G=i.connections.find(W=>W.strategy===w);if(!G)throw new v(400,{message:y.t("connection_not_found",{connection:w})});const Z=s.authParams?.ui_locales?.split(" ")?.map(W=>W.split("-")[0])[0];return w==="email"&&G.options.authentication_method==="magic_link"?await Gp(t,{to:_,code:P.code_id,authParams:s.authParams,language:Z}):await Kp(t,{to:_,code:P.code_id,language:Z}),t.redirect(`/u/enter-code?state=${n}`)}),lt=t=>p("a",{className:"block text-primary hover:text-primaryHover text-center",href:`/u/login/identifier?state=${t.state}`,children:y.t("go_back")});var Uo="_hp",ax={Change:"Input",DoubleClick:"DblClick"},cx={svg:"2000/svg",math:"1998/Math/MathML"},Do=[],yu=new WeakMap,di=void 0,lx=()=>di,cn=t=>"t"in t,Il={onClick:["click",!1]},g0=t=>{if(!t.startsWith("on"))return;if(Il[t])return Il[t];const e=t.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(e){const[,n,r]=e;return Il[t]=[(ax[n]||n).toLowerCase(),!!r]}},m0=(t,e)=>di&&t instanceof SVGElement&&/[A-Z]/.test(e)&&(e in t.style||e.match(/^(?:o|pai|str|u|ve)/))?e.replace(/([A-Z])/g,"-$1").toLowerCase():e,dx=(t,e,n)=>{e||={};for(let r in e){const i=e[r];if(r!=="children"&&(!n||n[r]!==i)){r=ia(r);const s=g0(r);if(s){if(n?.[r]!==i&&(n&&t.removeEventListener(s[0],n[r],s[1]),i!=null)){if(typeof i!="function")throw new Error(`Event handler for "${r}" is not a function`);t.addEventListener(s[0],i,s[1])}}else if(r==="dangerouslySetInnerHTML"&&i)t.innerHTML=i.__html;else if(r==="ref"){let a;typeof i=="function"?a=i(t)||(()=>i(null)):i&&"current"in i&&(i.current=t,a=()=>i.current=null),yu.set(t,a)}else if(r==="style"){const a=t.style;typeof i=="string"?a.cssText=i:(a.cssText="",i!=null&&b_(i,a.setProperty.bind(a)))}else{if(r==="value"){const c=t.nodeName;if(c==="INPUT"||c==="TEXTAREA"||c==="SELECT"){if(t.value=i==null||i===!1?null:i,c==="TEXTAREA"){t.textContent=i;continue}else if(c==="SELECT"){t.selectedIndex===-1&&(t.selectedIndex=0);continue}}}else(r==="checked"&&t.nodeName==="INPUT"||r==="selected"&&t.nodeName==="OPTION")&&(t[r]=i);const a=m0(t,r);i==null||i===!1?t.removeAttribute(a):i===!0?t.setAttribute(a,""):typeof i=="string"||typeof i=="number"?t.setAttribute(a,i):t.setAttribute(a,i.toString())}}}if(n)for(let r in n){const i=n[r];if(r!=="children"&&!(r in e)){r=ia(r);const s=g0(r);s?t.removeEventListener(s[0],i,s[1]):r==="ref"?yu.get(t)?.():t.removeAttribute(m0(t,r))}}},ux=(t,e)=>{e[ke][0]=0,Do.push([t,e]);const n=e.tag[Bu]||e.tag,r=n.defaultProps?{...n.defaultProps,...e.props}:e.props;try{return[n.call(null,r)]}finally{Do.pop()}},G1=(t,e,n,r,i)=>{t.vR?.length&&(r.push(...t.vR),delete t.vR),typeof t.tag=="function"&&t[ke][1][Z1]?.forEach(s=>i.push(s)),t.vC.forEach(s=>{if(cn(s))n.push(s);else if(typeof s.tag=="function"||s.tag===""){s.c=e;const a=n.length;if(G1(s,e,n,r,i),s.s){for(let c=a;c<n.length;c++)n[c].s=!0;s.s=!1}}else n.push(s),s.vR?.length&&(r.push(...s.vR),delete s.vR)})},px=t=>{for(;;t=t.tag===Uo||!t.vC||!t.pP?t.nN:t.vC[0]){if(!t)return null;if(t.tag!==Uo&&t.e)return t.e}},W1=t=>{cn(t)||(t[ke]?.[1][Z1]?.forEach(e=>e[2]?.()),yu.get(t.e)?.(),t.p===2&&t.vC?.forEach(e=>e.p=2),t.vC?.forEach(W1)),t.p||(t.e?.remove(),delete t.e),typeof t.tag=="function"&&(to.delete(t),Bs.delete(t),delete t[ke][3],t.a=!0)},J1=(t,e,n)=>{t.c=e,X1(t,e,n)},_0=(t,e)=>{if(e){for(let n=0,r=t.length;n<r;n++)if(t[n]===e)return n}},y0=Symbol(),X1=(t,e,n)=>{const r=[],i=[],s=[];G1(t,e,r,i,s),i.forEach(W1);const a=n?void 0:e.childNodes;let c,l=null;if(n)c=-1;else if(!a.length)c=0;else{const d=_0(a,px(t.nN));d!==void 0?(l=a[d],c=d):c=_0(a,r.find(u=>u.tag!==Uo&&u.e)?.e)??-1,c===-1&&(n=!0)}for(let d=0,u=r.length;d<u;d++,c++){const f=r[d];let g;if(f.s&&f.e)g=f.e,f.s=!1;else{const _=n||!f.e;cn(f)?(f.e&&f.d&&(f.e.textContent=f.t),f.d=!1,g=f.e||=document.createTextNode(f.t)):(g=f.e||=f.n?document.createElementNS(f.n,f.tag):document.createElement(f.tag),dx(g,f.props,f.pP),X1(f,g,_))}f.tag===Uo?c--:n?g.parentNode||e.appendChild(g):a[c]!==g&&a[c-1]!==g&&(a[c+1]===g?e.appendChild(a[c]):e.insertBefore(g,l||a[c]||null))}if(t.pP&&delete t.pP,s.length){const d=[],u=[];s.forEach(([,f,,g,_])=>{f&&d.push(f),g&&u.push(g),_?.()}),d.forEach(f=>f()),u.length&&requestAnimationFrame(()=>{u.forEach(f=>f())})}},fx=(t,e)=>!!(t&&t.length===e.length&&t.every((n,r)=>n[1]===e[r][1])),Bs=new WeakMap,wu=(t,e,n)=>{const r=!n&&e.pC;n&&(e.pC||=e.vC);let i;try{n||=typeof e.tag=="function"?ux(t,e):Fo(e.props.children),n[0]?.tag===""&&n[0][Gl]&&(i=n[0][Gl],t[5].push([t,i,e]));const s=r?[...e.pC]:e.vC?[...e.vC]:void 0,a=[];let c;for(let l=0;l<n.length;l++){Array.isArray(n[l])&&n.splice(l,1,...n[l].flat());let d=hx(n[l]);if(d){typeof d.tag=="function"&&!d.tag[h_]&&(Xr.length>0&&(d[ke][2]=Xr.map(f=>[f,f.values.at(-1)])),t[5]?.length&&(d[ke][3]=t[5].at(-1)));let u;if(s&&s.length){const f=s.findIndex(cn(d)?g=>cn(g):d.key!==void 0?g=>g.key===d.key&&g.tag===d.tag:g=>g.tag===d.tag);f!==-1&&(u=s[f],s.splice(f,1))}if(u)if(cn(d))u.t!==d.t&&(u.t=d.t,u.d=!0),d=u;else{const f=u.pP=u.props;if(u.props=d.props,u.f||=d.f||e.f,typeof d.tag=="function"){const g=u[ke][2];u[ke][2]=d[ke][2]||[],u[ke][3]=d[ke][3],!u.f&&((u.o||u)===d.o||u.tag[s2]?.(f,u.props))&&fx(g,u[ke][2])&&(u.s=!0)}d=u}else if(!cn(d)&&di){const f=hi(di);f&&(d.n=f)}if(!cn(d)&&!d.s&&(wu(t,d),delete d.f),a.push(d),c&&!c.s&&!d.s)for(let f=c;f&&!cn(f);f=f.vC?.at(-1))f.nN=d;c=d}}e.vR=r?[...e.vC,...s||[]]:s||[],e.vC=a,r&&delete e.pC}catch(s){if(e.f=!0,s===y0){if(i)return;throw s}const[a,c,l]=e[ke]?.[3]||[];if(c){const d=()=>Ls([0,!1,t[2]],l),u=Bs.get(l)||[];u.push(d),Bs.set(l,u);const f=c(s,()=>{const g=Bs.get(l);if(g){const _=g.indexOf(d);if(_!==-1)return g.splice(_,1),d()}});if(f){if(t[0]===1)t[1]=!0;else if(wu(t,l,[f]),(c.length===1||t!==a)&&l.c){J1(l,l.c,!1);return}throw y0}}throw s}finally{i&&t[5].pop()}},hx=t=>{if(!(t==null||typeof t=="boolean")){if(typeof t=="string"||typeof t=="number")return{t:t.toString(),d:!0};if("vR"in t&&(t={tag:t.tag,props:t.props,key:t.key,f:t.f,type:t.tag,ref:t.props.ref,o:t.o||t}),typeof t.tag=="function")t[ke]=[0,[]];else{const e=cx[t.tag];e&&(di||=m_(""),t.props.children=[{tag:di,props:{value:t.n=`http://www.w3.org/${e}`,children:t.props.children}}])}return t}},w0=(t,e)=>{e[ke][2]?.forEach(([n,r])=>{n.values.push(r)});try{wu(t,e,void 0)}catch{return}if(e.a){delete e.a;return}e[ke][2]?.forEach(([n])=>{n.values.pop()}),(t[0]!==1||!t[1])&&J1(e,e.c,!1)},to=new WeakMap,b0=[],Ls=async(t,e)=>{t[5]||=[];const n=to.get(e);n&&n[0](void 0);let r;const i=new Promise(s=>r=s);if(to.set(e,[r,()=>{t[2]?t[2](t,e,s=>{w0(s,e)}).then(()=>r(e)):(w0(t,e),r(e))}]),b0.length)b0.at(-1).add(e);else{await Promise.resolve();const s=to.get(e);s&&(to.delete(e),s[1]())}return i},gx=(t,e,n)=>({tag:Uo,props:{children:t},key:n,e,p:1}),mx=0,Z1=1,_x=2,yx=3,jl=new WeakMap,Y1=(t,e)=>!t||!e||t.length!==e.length||e.some((n,r)=>n!==t[r]),wx=void 0,v0=[],bx=t=>{const e=()=>typeof t=="function"?t():t,n=Do.at(-1);if(!n)return[e(),()=>{}];const[,r]=n,i=r[ke][1][mx]||=[],s=r[ke][0]++;return i[s]||=[e(),a=>{const c=wx,l=i[s];if(typeof a=="function"&&(a=a(l[0])),!Object.is(a,l[0]))if(l[0]=a,v0.length){const[d,u]=v0.at(-1);Promise.all([d===3?r:Ls([d,!1,c],r),u]).then(([f])=>{if(!f||!(d===2||d===3))return;const g=f.vC;requestAnimationFrame(()=>{setTimeout(()=>{g===f.vC&&Ls([d===3?1:0,!1,c],f)})})})}else Ls([0,!1,c],r)}]},Jp=(t,e)=>{const n=Do.at(-1);if(!n)return t;const[,r]=n,i=r[ke][1][_x]||=[],s=r[ke][0]++,a=i[s];return Y1(a?.[1],e)?i[s]=[t,e]:t=i[s][0],t},vx=t=>{const e=jl.get(t);if(e){if(e.length===2)throw e[1];return e[0]}throw t.then(n=>jl.set(t,[n]),n=>jl.set(t,[void 0,n])),t},$x=(t,e)=>{const n=Do.at(-1);if(!n)return t();const[,r]=n,i=r[ke][1][yx]||=[],s=r[ke][0]++,a=i[s];return Y1(a?.[1],e)&&(i[s]=[t(),e]),i[s][0]},kx=m_({pending:!1,data:null,method:null,action:null}),$0=new Set,xx=t=>{$0.add(t),t.finally(()=>$0.delete(t))},Xp=(t,e)=>$x(()=>n=>{let r;t&&(typeof t=="function"?r=t(n)||(()=>{t(null)}):t&&"current"in t&&(t.current=n,r=()=>{t.current=null}));const i=e(n);return()=>{i?.(),r?.()}},[t]),k0=Object.create(null),x0=Object.create(null),ps=(t,e,n,r,i)=>{if(e?.itemProp)return{tag:t,props:e,type:t,ref:e.ref};const s=document.head;let{onLoad:a,onError:c,precedence:l,blocking:d,...u}=e,f=null,g=!1;const _=Es[t];let w;if(_.length>0){const I=s.querySelectorAll(t);e:for(const S of I)for(const E of Es[t])if(S.getAttribute(E)===e[E]){f=S;break e}if(!f){const S=_.reduce((E,P)=>e[P]===void 0?E:`${E}-${P}-${e[P]}`,t);g=!x0[S],f=x0[S]||=(()=>{const E=document.createElement(t);for(const P of _)e[P]!==void 0&&E.setAttribute(P,e[P]),e.rel&&E.setAttribute("rel",e.rel);return E})()}}else w=s.querySelectorAll(t);l=r?l??"":void 0,r&&(u[Cs]=l);const k=Jp(I=>{if(_.length>0){let S=!1;for(const E of s.querySelectorAll(t)){if(S&&E.getAttribute(Cs)!==l){s.insertBefore(I,E);return}E.getAttribute(Cs)===l&&(S=!0)}s.appendChild(I)}else if(w){let S=!1;for(const E of w)if(E===I){S=!0;break}S||s.insertBefore(I,s.contains(w[0])?w[0]:s.querySelector(t)),w=void 0}},[l]),z=Xp(e.ref,I=>{const S=_[0];if(n===2&&(I.innerHTML=""),(g||w)&&k(I),!c&&!a)return;let E=k0[I.getAttribute(S)]||=new Promise((P,G)=>{I.addEventListener("load",P),I.addEventListener("error",G)});a&&(E=E.then(a)),c&&(E=E.catch(c)),E.catch(()=>{})});if(i&&d==="render"){const I=Es[t][0];if(e[I]){const S=e[I],E=k0[S]||=new Promise((P,G)=>{k(f),f.addEventListener("load",P),f.addEventListener("error",G)});vx(E)}}const N={tag:t,type:t,props:{...u,ref:z},ref:z};return N.p=n,f&&(N.e=f),gx(N,s)},Sx=t=>{const e=lx();return(e&&hi(e))?.endsWith("svg")?{tag:"title",props:t,type:"title",ref:t.ref}:ps("title",t,void 0,!1,!1)},zx=t=>!t||["src","async"].some(e=>!t[e])?{tag:"script",props:t,type:"script",ref:t.ref}:ps("script",t,1,!1,!0),Ax=t=>!t||!["href","precedence"].every(e=>e in t)?{tag:"style",props:t,type:"style",ref:t.ref}:(t["data-href"]=t.href,delete t.href,ps("style",t,2,!0,!0)),Ex=t=>!t||["onLoad","onError"].some(e=>e in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?{tag:"link",props:t,type:"link",ref:t.ref}:ps("link",t,1,"precedence"in t,!0),Cx=t=>ps("meta",t,void 0,!1,!1),Q1=Symbol(),Nx=t=>{const{action:e,...n}=t;typeof e!="function"&&(n.action=e);const[r,i]=bx([null,!1]),s=Jp(async d=>{const u=d.isTrusted?e:d.detail[Q1];if(typeof u!="function")return;d.preventDefault();const f=new FormData(d.target);i([f,!0]);const g=u(f);g instanceof Promise&&(xx(g),await g),i([null,!0])},[]),a=Xp(t.ref,d=>(d.addEventListener("submit",s),()=>{d.removeEventListener("submit",s)})),[c,l]=r;return r[1]=!1,{tag:kx,props:{value:{pending:c!==null,data:c,method:c?"post":null,action:c?e:null},children:{tag:"form",props:{...n,ref:a},type:"form",ref:a}},f:l}},ew=(t,{formAction:e,...n})=>{if(typeof e=="function"){const r=Jp(i=>{i.preventDefault(),i.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[Q1]:e}}))},[]);n.ref=Xp(n.ref,i=>(i.addEventListener("click",r),()=>{i.removeEventListener("click",r)}))}return{tag:t,props:n,type:t,ref:n.ref}},Ix=t=>ew("input",t),jx=t=>ew("button",t);Object.assign(Wl,{title:Sx,script:zx,style:Ax,link:Ex,meta:Cx,form:Nx,input:Ix,button:jx});__(null);new TextEncoder;const Un=t=>{const{i18nKey:e,values:n,components:r}=t,i=y.t(e,n),s=/<(\d+)>(.*?)<\/\d+>/g,a=[];let c=0,l;for(;(l=s.exec(i))!==null;){const[,d,u]=l,f=i.substring(c,l.index);f&&a.push(f);const g=parseInt(d,10);a.push(b2(r[g],{},u)),c=s.lastIndex}return c<i.length&&a.push(i.substring(c)),p(bo,{children:a})},S0=6,bu=({error:t,theme:e,branding:n,email:r,state:i,client:s,hasPasswordLogin:a})=>{const c=new URLSearchParams({state:i}),d=s.connections.map(({name:u})=>u).includes("auth2");return p(Se,{title:y.t("verify_your_email"),theme:e,branding:n,client:s,children:[p("div",{className:"mb-4 text-2xl font-medium",children:y.t("verify_your_email")}),p("div",{className:"mb-8 text-gray-300",children:p(Un,{i18nKey:"code_sent_template",components:[p("span",{className:"text-black dark:text-white"},"span")],values:{username:r}})}),p("div",{className:"flex flex-1 flex-col justify-center",children:[p(Bt,{className:"pt-2",children:[p("input",{autoFocus:!0,type:"text",pattern:"[0-9]*",maxLength:S0,inputMode:"numeric",name:"code",placeholder:"******",className:Q("mb-2 w-full rounded-lg border bg-gray-100 px-4 pb-2 pt-2.5 text-center indent-[5px] font-mono text-3xl placeholder:text-gray-300 dark:bg-gray-600 md:text-3xl",{"border-red":t,"border-gray-100 dark:border-gray-500":!t}),minLength:S0,required:!0,id:"code-input"}),t&&p(Re,{children:t}),p(xe,{className:"sm:mt-4 !text-base",children:[p("span",{children:y.t("login")}),p(Ne,{className:"text-xs",name:"arrow-right"})]}),p("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[p(Ne,{className:"text-base",name:"info-bubble"}),p("div",{className:"text-sm text-gray-300 md:text-sm",children:y.t("sent_code_spam")})]}),d&&p("div",{className:"text-center mb-12",children:[p("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[p("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),p("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:y.t("or")})]}),p(xe,{Component:"a",href:`/u/${a?"enter-password":"pre-signup"}?${c.toString()}`,variant:"secondary",className:"block",children:y.t("enter_your_password_btn")})]})]}),p(lt,{state:i})]})]})},Px=({maxLength:t,value:e="",disabled:n=!1,className:r,containerClassName:i,name:s,id:a,required:c,autoFocus:l})=>p("div",{className:Q("flex items-center gap-2 has-[:disabled]:opacity-50",i),"data-input-otp-container":"",children:Array.from({length:t}).map((d,u)=>p("input",{type:"text",inputMode:"numeric",maxLength:1,value:e[u]||"",disabled:n,name:u===0?s:void 0,id:u===0?a:void 0,required:u===0?c:void 0,autoFocus:u===0?l:void 0,className:Q("relative flex h-9 w-9 items-center justify-center border-y border-r border-input text-sm shadow-sm transition-all first:rounded-l-md first:border-l last:rounded-r-md text-center font-mono","focus:z-10 focus:ring-1 focus:ring-ring","disabled:cursor-not-allowed disabled:opacity-50",r),"data-input-otp-slot":u},u))}),Ox=6,z0=({error:t,theme:e,branding:n,email:r,state:i,hasPasswordLogin:s,className:a})=>{const c=new URLSearchParams({state:i}),l=e?.colors?.primary_button||n?.colors?.primary||"#0066cc",d=e?.colors?.primary_button_label||"#ffffff",u=e?.colors?.body_text||"#333333",f=e?.colors?.input_border||"#d1d5db",g=e?.colors?.widget_background||"#ffffff",_=e?.colors?.widget_border||"#e5e7eb",w=e?.borders?.widget_corner_radius||8,k=e?.borders?.button_border_radius||4,z=e?.borders?.show_widget_shadow??!0,N=e?.fonts?.title?.size||24,I=e?.fonts?.title?.bold??!0,S=e?.fonts?.body_text?.size||14,E={backgroundColor:g,borderColor:_,borderRadius:`${w}px`,boxShadow:z?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:u},P={fontSize:`${N}px`,fontWeight:I?"700":"400",color:e?.colors?.header||u},G={fontSize:`${S}px`,color:e?.colors?.input_labels_placeholders||"#6b7280"},Z={backgroundColor:l,color:d,borderRadius:`${k}px`},W=e?.widget?.logo_position||"center",M=W==="left"?"text-left":W==="right"?"text-right":"text-center",ce=e?.widget?.logo_url||n?.logo_url,le=W!=="none"&&ce;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",a),children:[p(en,{style:E,className:"border",children:[p(tn,{children:[le&&p("div",{className:Q("mb-4",M),children:p(Rt,{theme:e,branding:n})}),p(nn,{style:P,children:y.t("verify_your_email","Verify your email")}),p(rn,{style:G,children:p(Un,{i18nKey:"code_sent_template",components:[p("span",{className:"font-medium"},"span")],values:{username:r}})})]}),p(on,{children:p("form",{method:"post",children:p("div",{className:"grid gap-6",children:[p("div",{className:"grid gap-4",children:[p(_t,{htmlFor:"code",style:G,children:y.t("verification_code","Verification Code")}),p("div",{className:"flex justify-center",children:p(Px,{maxLength:Ox,name:"code",id:"code",required:!0,autoFocus:!0,containerClassName:"gap-2",className:Q("w-12 h-12 text-center text-lg font-mono border rounded-md transition-colors",t?"border-red-500 focus:ring-red-500":"border-gray-300 focus:ring-blue-500 focus:border-blue-500")})}),t&&p(Re,{children:t})]}),p(Jt,{type:"submit",className:"w-full transition-colors hover:brightness-90",style:Z,children:y.t("login","Login")}),p("div",{className:"text-center text-xs text-gray-500",children:p("div",{className:"flex items-center justify-center gap-1",children:[p("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 20 20",children:p("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z",clipRule:"evenodd"})}),p("span",{children:y.t("sent_code_spam","Check your spam folder if you don't see the code")})]})}),s&&p("div",{className:"text-center",children:[p("div",{className:"relative mb-5 block text-center",style:G,children:[p("div",{className:"absolute left-0 right-0 top-1/2 border-b",style:{borderColor:_}}),p("div",{className:"relative inline-block px-2",style:{backgroundColor:g},children:y.t("or","Or")})]}),p("a",{href:`/u/${s?"enter-password":"pre-signup"}?${c.toString()}`,className:Q("w-full 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","border border-gray-300 bg-transparent hover:bg-gray-100 dark:border-gray-600 dark:hover:bg-gray-800","h-10 px-4 py-2"),style:{borderColor:f,borderRadius:`${k}px`,color:u},children:y.t("enter_your_password_btn","Enter your password instead")})]})]})})})]}),p(lt,{state:i})]})},wt=t=>{const{message:e,theme:n,branding:r,client:i,pageTitle:s,state:a}=t;return p(Se,{title:"Login",theme:n,branding:r,client:i,children:[s?p("div",{className:"mb-4 text-2xl font-medium",children:s}):"",p("div",{className:"text-gray-300 mb-12",children:e}),a?p(lt,{state:a}):""]})},Tx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state"}),style:o.z.enum(["classic","shadcn"]).optional().openapi({description:"UI style to use for the enter code page"})})},responses:{200:{description:"HTML page to enter verification code.",content:{"text/html":{schema:o.z.string()}}},400:{description:"Bad Request - HTML error page if username is missing in state.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{state:e,style:n}=t.req.valid("query");let r,i,s,a,c;n&&Og(t,"auth_ui_style",n,{path:"/",maxAge:3600*24*365,httpOnly:!0,secure:!0,sameSite:"Lax"});try{if({theme:r,branding:i,loginSession:s,client:a,useShadcn:c}=await he(t,e),!s.authParams.username)return t.html(p(wt,{theme:r,branding:i,client:a,state:e,pageTitle:y.t("error_page_title")||"Error",message:y.t("username_not_found_error")||"Username not found in session."}),400);const l=await Jr({userAdapter:t.env.data.users,tenant_id:a.tenant.id,username:s.authParams.username,provider:"auth2"});return c?t.html(p(we,{title:y.t("verify_your_email","Verify your email"),theme:r,branding:i,client:a,children:p(z0,{theme:r,branding:i,email:s.authParams.username,state:e,hasPasswordLogin:!!l})})):t.html(p(bu,{theme:r,branding:i,email:s.authParams.username,state:e,client:a,hasPasswordLogin:!!l}))}catch(l){return console.error("Error in GET /u/enter-code:",l),i||(i=null),r||(r=null),a||(a=null),t.html(p(wt,{theme:r,branding:i,client:a,state:e,pageTitle:y.t("error_page_title")||"Error",message:y.t("unexpected_error_try_again")||"An unexpected error occurred. Please try again."}),500)}}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state"}),style:o.z.enum(["classic","shadcn"]).optional().openapi({description:"UI style to use for the enter code page"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({code:o.z.string()})}}}},responses:{302:{description:"Redirect to continue authentication flow.",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML page with an error message (e.g., invalid code, username missing).",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page for unexpected issues.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{state:e,style:n}=t.req.valid("query"),{code:r}=t.req.valid("form");n&&Og(t,"auth_ui_style",n,{path:"/",maxAge:3600*24*365,httpOnly:!0,secure:!0,sameSite:"Lax"});const{theme:i,branding:s,client:a,loginSession:c,useShadcn:l}=await he(t,e);if(!c.authParams.username)throw new v(400,{message:y.t("username_not_found_error")||"Username not found in session."});try{t.set("client_id",a.client_id);const d=await Fp(t,{client_id:a.client_id,authParams:c.authParams,username:c.authParams.username,otp:r});if(d instanceof Response)return d;throw new v(500,{message:y.t("unexpected_error_try_again")||"An unexpected error occurred. Please try again."})}catch(d){let u;try{u=await Jr({userAdapter:t.env.data.users,tenant_id:a.tenant.id,username:c.authParams.username,provider:"auth2"})}catch{u=null}return l?t.html(p(we,{title:y.t("verify_your_email","Verify your email"),theme:i,branding:s,client:a,children:p(z0,{theme:i,branding:s,email:c.authParams?.username,state:e,error:d.message,hasPasswordLogin:!!u})}),400):t.html(p(bu,{theme:i,branding:s,email:c.authParams?.username,state:e,client:a,error:d.message,hasPasswordLogin:!!u}),400)}}),tw=t=>{const{theme:e,branding:n,client:r,state:i}=t;return p(Se,{title:y.t("unverified_email"),theme:e,branding:n,client:r,children:[p("div",{className:"flex flex-1 flex-col justify-center",children:[p("p",{className:"mb-8 text-gray-300 text-lg",children:y.t("unverified_email")}),p("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[p(Ne,{className:"text-base",name:"info-bubble"}),p("div",{className:"text-sm text-gray-300 md:text-sm",children:y.t("sent_code_spam")})]}),p(lt,{state:i})]}),p(lt,{state:i})]})},Rx=({width:t=22,height:e=17,className:n,...r})=>p("svg",{width:t,height:e,className:n,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 576 512",...r,children:p("path",{fill:"currentColor",d:"M288 32c-80.8 0-145.5 36.8-192.6 80.6C48.6 156 17.3 208 2.5 243.7c-3.3 7.9-3.3 16.7 0 24.6C17.3 304 48.6 356 95.4 399.4 142.5 443.2 207.2 480 288 480s145.5-36.8 192.6-80.6c46.8-43.5 78.1-95.4 93-131.1 3.3-7.9 3.3-16.7 0-24.6-14.9-35.7-46.2-87.7-93-131.1C433.5 68.8 368.8 32 288 32M144 256a144 144 0 1 1 288 0 144 144 0 1 1-288 0m144-64c0 35.3-28.7 64-64 64-7.1 0-13.9-1.2-20.3-3.3-5.5-1.8-11.9 1.6-11.7 7.4.3 6.9 1.3 13.8 3.2 20.7 13.7 51.2 66.4 81.6 117.6 67.9s81.6-66.4 67.9-117.6c-11.1-41.5-47.8-69.4-88.6-71.1-5.8-.2-9.2 6.1-7.4 11.7 2.1 6.4 3.3 13.2 3.3 20.3"})}),Bx=({width:t=23,height:e=18,className:n,...r})=>p("svg",{width:t,height:e,className:n,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 640 512",...r,children:p("path",{fill:"currentColor",d:"M38.8 5.1C28.4-3.1 13.3-1.2 5.1 9.2s-6.3 25.5 4.1 33.7l592 464c10.4 8.2 25.5 6.3 33.7-4.1s6.3-25.5-4.1-33.7l-105.2-82.4c39.6-40.6 66.4-86.1 79.9-118.4 3.3-7.9 3.3-16.7 0-24.6-14.9-35.7-46.2-87.7-93-131.1C465.5 68.8 400.8 32 320 32c-68.2 0-125 26.3-169.3 60.8zm184.3 144.4c25.5-23.3 59.6-37.5 96.9-37.5 79.5 0 144 64.5 144 144 0 24.9-6.3 48.3-17.4 68.7L408 294.5c8.4-19.3 10.6-41.4 4.8-63.3-11.1-41.5-47.8-69.4-88.6-71.1-5.8-.2-9.2 6.1-7.4 11.7 2.1 6.4 3.3 13.2 3.3 20.3 0 10.2-2.4 19.8-6.6 28.3l-90.3-70.8zM373 389.9c-16.4 6.5-34.3 10.1-53 10.1-79.5 0-144-64.5-144-144 0-6.9.5-13.6 1.4-20.2l-94.3-74.3c-22.8 29.7-39.1 59.3-48.6 82.2-3.3 7.9-3.3 16.7 0 24.6 14.9 35.7 46.2 87.7 93 131.1 47 43.8 111.7 80.6 192.5 80.6 47.8 0 89.9-12.9 126.2-32.5z"})}),vu=({name:t,placeholder:e=y.t("password")})=>p("div",{className:"password-input relative mb-2","data-password-toggle":!0,children:[p("input",{type:"password",name:t,placeholder:e,className:"w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",required:!0}),p("button",{type:"button","aria-label":y.t("show_password"),title:y.t("show_password"),className:"absolute right-0 top-0 w-10 h-full rounded-r-lg text-gray-400 column hover:bg-black/5","data-password-toggle-btn":!0,children:[p(Rx,{"data-show-icon":!0}),p(Bx,{"data-hide-icon":!0,className:"hidden"})]})]}),Us=t=>{const{error:e,theme:n,branding:r,email:i,state:s,client:a}=t,c=new URLSearchParams({state:s});return p(Se,{title:y.t("enter_password"),theme:n,branding:r,client:a,children:[p("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:y.t("enter_password")}),p("div",{className:"mb-6 text-gray-300",children:y.t("enter_password_description")}),p("div",{className:"flex flex-1 flex-col justify-center",children:[p(Bt,{className:"mb-7",children:[p("input",{type:"text",name:"username",placeholder:y.t("email_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",value:i}),p(vu,{name:"password"}),e&&p(Re,{children:e}),p(xe,{className:"sm:mt-4 !text-base",children:[p("span",{children:y.t("login")}),p(Ne,{className:"text-xs",name:"arrow-right"})]})]}),p("a",{href:`/u/forgot-password?${c.toString()}`,className:"text-primary hover:underline mb-4",children:y.t("forgot_password_link")}),p("div",{className:"text-center mb-12",children:[p("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[p("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),p("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:y.t("or")})]}),p("form",{method:"post",action:`/u/login/identifier?${c.toString()}`,children:[p("input",{type:"hidden",name:"login_selection",value:"code"}),p("input",{type:"hidden",name:"username",value:i}),p(xe,{variant:"secondary",className:"block",children:y.t("enter_a_code_btn")})]})]}),p(lt,{state:s})]})]})},Pl=({error:t,theme:e,branding:n,loginSession:r,email:i,className:s})=>{const a=e?.colors?.primary_button||n?.colors?.primary||"#0066cc",c=e?.colors?.primary_button_label||"#ffffff",l=e?.colors?.body_text||"#333333",d=e?.colors?.input_background||"#ffffff",u=e?.colors?.input_border||"#d1d5db",f=e?.colors?.input_filled_text||"#111827",g=e?.colors?.error||"#dc2626",_=e?.colors?.widget_background||"#ffffff",w=e?.colors?.widget_border||"#e5e7eb",k=e?.borders?.widget_corner_radius||8,z=e?.borders?.input_border_radius||4,N=e?.borders?.button_border_radius||4,I=e?.borders?.show_widget_shadow??!0,S=e?.fonts?.title?.size||24,E=e?.fonts?.title?.bold??!0,P=e?.fonts?.body_text?.size||14,G={backgroundColor:_,borderColor:w,borderRadius:`${k}px`,boxShadow:I?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:l},Z={fontSize:`${S}px`,fontWeight:E?"700":"400",color:e?.colors?.header||l},W={fontSize:`${P}px`,color:e?.colors?.input_labels_placeholders||"#6b7280"},M={backgroundColor:d,borderColor:t?g:u,borderRadius:`${z}px`,color:f},ce={backgroundColor:a,color:c,borderRadius:`${N}px`},le=e?.widget?.logo_position||"center",fe=le==="left"?"text-left":le==="right"?"text-right":"text-center",$e=e?.widget?.logo_url||n?.logo_url,be=le!=="none"&&$e;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",s),children:p(en,{style:G,className:"border",children:[p(tn,{children:[be&&p("div",{className:Q("mb-4",fe),children:p(Rt,{theme:e,branding:n})}),p(nn,{style:Z,children:y.t("enter_password","Enter your password")}),p(rn,{style:W,children:y.t("enter_password_description","Enter your password to continue")})]}),p(on,{children:p("form",{method:"post",children:p("div",{className:"grid gap-6",children:[p("div",{className:"grid gap-2",children:[p(_t,{htmlFor:"email",style:W,children:y.t("email","Email")}),p(Pt,{id:"email",name:"username",type:"email",value:i,disabled:!0,className:"border bg-gray-50",style:{...M,cursor:"not-allowed"}})]}),p("div",{className:"grid gap-2",children:[p("div",{className:"flex items-center justify-between",children:[p(_t,{htmlFor:"password",style:W,children:y.t("password","Password")}),p("a",{href:`/u/forgot-password?state=${r.id}`,className:"text-sm hover:underline",style:{color:a},children:y.t("forgot_password","Forgot password?")})]}),p("div",{className:"relative","data-password-toggle":!0,children:[p(Pt,{id:"password",name:"password",type:"password","data-password-input":"password",placeholder:y.t("password_placeholder","Enter your password"),required:!0,error:!!t,className:"border pr-8",style:M}),p("button",{type:"button","data-password-toggle-btn":!0,className:"absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 transition-colors","aria-label":y.t("toggle_password_visibility","Toggle password visibility"),children:[p("svg",{"data-show-icon":!0,xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),p("circle",{cx:"12",cy:"12",r:"3"})]}),p("svg",{"data-hide-icon":!0,className:"hidden",xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),p("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),p("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),p("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]})]})]}),t&&p(Re,{children:t})]}),p(Jt,{type:"submit",className:"w-full transition-colors hover:brightness-90",style:ce,children:y.t("continue","Continue")}),p("div",{className:"text-center",children:p("a",{href:`/u/login/identifier?state=${r.id}`,className:"text-sm hover:underline",style:W,children:["← ",y.t("back","Back")]})})]})})})]})})},Lx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,loginSession:s,useShadcn:a}=await he(t,e);if(!s.authParams.username)throw new v(400,{message:"Username required"});return a?t.html(p(we,{title:y.t("enter_your_password","Enter your password"),theme:n,branding:r,client:i,children:p(Pl,{theme:n,branding:r,loginSession:s,email:s.authParams.username,client:i})})):t.html(p(Us,{theme:n,branding:r,email:s.authParams.username,state:e,client:i}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({password:o.z.string()})}}}},responses:{200:{description:"HTML page indicating success or a next step (if not redirecting).",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to continue the authentication flow (e.g., to client, MFA, consent).",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML page with an error message (e.g., invalid password, username required).",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML page with an error message.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{state:e}=t.req.valid("query"),n=t.req.valid("form"),{password:r}=n,{theme:i,branding:s,client:a,loginSession:c,useShadcn:l}=await he(t,e),{username:d}=c.authParams;if(!d)throw new v(400,{message:"Username required"});try{return await M1(t,a,{...c.authParams,password:r},c)}catch(u){const f=u;return f.code==="INVALID_PASSWORD"||f.code==="USER_NOT_FOUND"?l?t.html(p(we,{title:y.t("enter_your_password","Enter your password"),theme:i,branding:s,client:a,children:p(Pl,{theme:i,branding:s,loginSession:c,email:d,error:y.t("invalid_password"),client:a})}),400):t.html(p(Us,{theme:i,branding:s,email:d,error:y.t("invalid_password"),state:e,client:a}),400):f.code==="EMAIL_NOT_VERIFIED"?t.html(p(tw,{theme:i,branding:s,client:a,state:e}),400):l?t.html(p(we,{title:y.t("enter_your_password","Enter your password"),theme:i,branding:s,client:a,children:p(Pl,{theme:i,branding:s,loginSession:c,email:d,error:f.message||"An unknown error occurred.",client:a})}),f.code?400:500):t.html(p(Us,{theme:i,branding:s,email:d,error:f.message||"An unknown error occurred.",state:e,client:a}),f.code?400:500)}}),Gn=t=>{const{error:e,theme:n,branding:r,client:i,email:s,state:a,code:c}=t;return p(Se,{title:y.t("sign_up"),theme:n,branding:r,client:i,children:[p("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:y.t("create_account_title")}),p("div",{className:"mb-6 text-gray-300",children:y.t("create_account_description")}),p("div",{className:"flex flex-1 flex-col justify-center",children:[p(Bt,{children:[p("input",{type:"hidden",name:"code",value:c}),p("input",{type:"email",name:"username",placeholder:y.t("email_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",required:!0,value:s,disabled:!!s}),p("input",{type:"password",name:"password",placeholder:y.t("enter_new_password_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base"}),p("input",{type:"password",name:"re-enter-password",placeholder:y.t("reenter_new_password_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base"}),e&&p(Re,{children:e}),p(xe,{className:"sm:mt-4 !text-base",children:y.t("continue")})]}),p(lt,{state:a})]})]})},Pi=({error:t,theme:e,branding:n,loginSession:r,email:i,code:s,className:a})=>{const c=e?.colors?.primary_button||n?.colors?.primary||"#0066cc",l=e?.colors?.primary_button_label||"#ffffff",d=e?.colors?.body_text||"#333333",u=e?.colors?.input_background||"#ffffff",f=e?.colors?.input_border||"#d1d5db",g=e?.colors?.input_filled_text||"#111827",_=e?.colors?.error||"#dc2626",w=e?.colors?.widget_background||"#ffffff",k=e?.colors?.widget_border||"#e5e7eb",z=e?.borders?.widget_corner_radius||8,N=e?.borders?.input_border_radius||4,I=e?.borders?.button_border_radius||4,S=e?.borders?.show_widget_shadow??!0,E=e?.fonts?.title?.size||24,P=e?.fonts?.title?.bold??!0,G=e?.fonts?.body_text?.size||14,Z={backgroundColor:w,borderColor:k,borderRadius:`${z}px`,boxShadow:S?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:d},W={fontSize:`${E}px`,fontWeight:P?"700":"400",color:e?.colors?.header||d},M={fontSize:`${G}px`,color:e?.colors?.input_labels_placeholders||"#6b7280"},ce={backgroundColor:u,borderColor:t?_:f,borderRadius:`${N}px`,color:g},le={backgroundColor:c,color:l,borderRadius:`${I}px`},fe=e?.widget?.logo_position||"center",$e=fe==="left"?"text-left":fe==="right"?"text-right":"text-center",be=e?.widget?.logo_url||n?.logo_url,sn=fe!=="none"&&be;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",a),children:p(en,{style:Z,className:"border",children:[p(tn,{children:[sn&&p("div",{className:Q("mb-4",$e),children:p(Rt,{theme:e,branding:n})}),p(nn,{style:W,children:y.t("create_account_title","Create Account")}),p(rn,{style:M,children:y.t("create_account_description","Sign up to get started")})]}),p(on,{children:[p("form",{method:"post",className:"space-y-4",children:[p("input",{type:"hidden",name:"state",value:r.authParams.state}),s&&p("input",{type:"hidden",name:"code",value:s}),p("div",{className:"space-y-2",children:[p(_t,{htmlFor:"username",style:M,children:y.t("email_label","Email")}),p(Pt,{id:"username",type:"email",name:"username",placeholder:y.t("email_placeholder","Email Address"),value:i,disabled:!!i,style:ce,className:"w-full",required:!0})]}),p("div",{className:"space-y-2",children:[p(_t,{htmlFor:"password",style:M,children:y.t("password","Password")}),p("div",{className:"relative","data-password-toggle":!0,children:[p(Pt,{id:"password",name:"password",type:"password","data-password-input":"password",placeholder:y.t("enter_new_password_placeholder","Enter new password"),required:!0,error:!!t,className:"border pr-8",style:ce}),p("button",{type:"button","data-password-toggle-btn":!0,className:"absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 transition-colors","aria-label":y.t("toggle_password_visibility","Toggle password visibility"),children:[p("svg",{"data-show-icon":!0,xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),p("circle",{cx:"12",cy:"12",r:"3"})]}),p("svg",{"data-hide-icon":!0,className:"hidden",xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),p("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),p("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),p("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]})]})]})]}),p("div",{className:"space-y-2",children:[p(_t,{htmlFor:"re-enter-password",style:M,children:y.t("confirm_password","Confirm Password")}),p("div",{className:"relative","data-password-toggle":!0,children:[p(Pt,{id:"re-enter-password",name:"re-enter-password",type:"password","data-password-input":"re-enter-password",placeholder:y.t("reenter_new_password_placeholder","Re-enter new password"),required:!0,error:!!t,className:"border pr-8",style:ce}),p("button",{type:"button","data-password-toggle-btn":!0,className:"absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 transition-colors","aria-label":y.t("toggle_password_visibility","Toggle password visibility"),children:[p("svg",{"data-show-icon":!0,xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),p("circle",{cx:"12",cy:"12",r:"3"})]}),p("svg",{"data-hide-icon":!0,className:"hidden",xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),p("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),p("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),p("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]})]})]})]}),t&&p(Re,{children:t}),p(Jt,{type:"submit",className:"w-full",style:le,disabled:!1,children:y.t("continue","Continue")})]}),p("div",{className:"mt-4 text-center",children:p("a",{href:`/u/login/identifier?state=${encodeURIComponent(r.authParams.state||"")}`,className:"text-sm",style:{color:c},children:y.t("back_to_login","Back to Login")})})]})]})})},Ux=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.z.string().optional().openapi({description:"The code parameter from an email verification link"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e,code:n}=t.req.valid("query"),{theme:r,branding:i,client:s,loginSession:a,useShadcn:c}=await he(t,e),{username:l}=a.authParams;if(!l)throw new v(400,{message:"Username required"});return c?t.html(p(we,{title:y.t("sign_up","Sign Up"),theme:r,branding:i,client:s,children:p(Pi,{theme:r,branding:i,loginSession:a,email:l,code:n,client:s})})):n?t.html(p(Gn,{state:e,theme:r,branding:i,client:s,email:l,code:n})):t.html(p(Gn,{state:e,theme:r,branding:i,client:s,email:l}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({password:o.z.string(),"re-enter-password":o.z.string(),code:o.z.string().optional()})}}}},responses:{200:{description:"HTML page indicating success (e.g., email verification sent) or a next step.",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to continue the authentication flow (e.g., to client, MFA, consent) after successful login.",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML page with an error message (e.g., passwords don't match, weak password, user exists).",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML page with an error message.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{state:e}=t.req.valid("query"),n=t.req.valid("form"),{env:r}=t,{theme:i,branding:s,client:a,loginSession:c,useShadcn:l}=await he(t,e);try{if(!c.authParams.username)throw new v(400,{message:"Username required"});const u=a.connections.find(S=>S.strategy==="Username-Password-Authentication")?.name||"Username-Password-Authentication";if(t.set("connection",u),n.password!==n["re-enter-password"])return l?t.html(p(we,{title:y.t("sign_up","Sign Up"),theme:i,branding:s,client:a,children:p(Pi,{theme:i,branding:s,loginSession:c,email:c.authParams.username,code:n.code,error:y.t("create_account_passwords_didnt_match"),client:a})}),400):t.html(p(Gn,{state:e,code:n.code,theme:i,branding:s,client:a,error:y.t("create_account_passwords_didnt_match"),email:c.authParams.username}),400);const f=await Vp(r.data,a.tenant.id,u);try{await Hp(f,{tenantId:a.tenant.id,userId:"",newPassword:n.password,data:r.data})}catch(S){let E;return S instanceof Ht?E=y.t(S.code,{defaultValue:S.message,...S.params}):E=S?.message||y.t("create_account_weak_password"),l?t.html(p(we,{title:y.t("sign_up","Sign Up"),theme:i,branding:s,client:a,children:p(Pi,{theme:i,branding:s,loginSession:c,email:c.authParams.username,code:n.code,error:E,client:a})}),400):t.html(p(Gn,{state:e,code:n.code,theme:i,branding:s,client:a,error:E,email:c.authParams.username}),400)}const g=n.code?await r.data.codes.get(a.tenant.id,n.code,"email_verification"):void 0,_=g?await r.data.loginSessions.get(a.tenant.id,g.login_id):void 0;if(await fi({userAdapter:t.env.data.users,tenant_id:a.tenant.id,username:c.authParams.username,provider:"auth2"}))return l?t.html(p(we,{title:y.t("sign_up","Sign Up"),theme:i,branding:s,client:a,children:p(Pi,{theme:i,branding:s,loginSession:c,email:c.authParams.username,code:n.code,error:y.t("user_exists_error"),client:a})}),400):t.html(p(Gn,{state:e,code:n.code,theme:i,branding:s,client:a,error:y.t("user_exists_error"),email:c.authParams.username}),400);const k=_?.authParams.username===c.authParams.username,z=`auth2|${Xa()}`,N=await r.data.users.create(a.tenant.id,{user_id:z,email:c.authParams.username,email_verified:k,provider:"auth2",connection:u,is_social:!1});if(await r.data.passwords.create(a.tenant.id,{user_id:z,password:await Pn.hash(n.password,10),algorithm:"bcrypt",is_current:!0}),!k){const S=c.authParams?.ui_locales?.split(" ")?.map(E=>E.split("-")[0])[0];return await Wp(t,N,S),t.html(p(wt,{message:y.t("validate_email_body"),pageTitle:y.t("validate_email_title"),theme:i,branding:s,client:a,state:e}))}const I=await D1(t,a,{...c.authParams,password:n.password},c);return Gt(t,I)}catch(d){let u=y.t("unknown_error_message"),f=400;return d instanceof v?(u=d.message||u,f=d.status===400?400:500):d instanceof Tr?u=d.message||u:d instanceof Error&&(u=d.message||u,f=500),l?t.html(p(we,{title:y.t("sign_up","Sign Up"),theme:i,branding:s,client:a,children:p(Pi,{theme:i,branding:s,loginSession:c,email:c.authParams.username,code:n.code,error:u,client:a})}),f):t.html(p(Gn,{state:e,theme:i,branding:s,client:a,error:u,email:c.authParams.username,code:n.code}),f)}}),Rr=t=>{const{error:e,theme:n,branding:r,client:i,email:s}=t;return p(Se,{title:y.t("reset_password_title"),theme:n,branding:r,client:i,children:[p("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:y.t("reset_password_title")}),p("div",{className:"mb-6 text-gray-300",children:`${y.t("reset_password_description")} ${s}`}),p("div",{className:"flex flex-1 flex-col justify-center",children:p(Bt,{children:[p(vu,{name:"password",placeholder:y.t("enter_new_password_placeholder")}),p(vu,{name:"re-enter-password",placeholder:y.t("reenter_new_password_placeholder")}),e&&p(Re,{children:e}),p(xe,{className:"sm:mt-4 !text-base",children:y.t("reset_password_cta")})]})})]})},Oi=({error:t,theme:e,branding:n,loginSession:r,email:i,className:s})=>{const a=e?.colors?.primary_button||n?.colors?.primary||"#0066cc",c=e?.colors?.primary_button_label||"#ffffff",l=e?.colors?.body_text||"#333333",d=e?.colors?.input_background||"#ffffff",u=e?.colors?.input_border||"#d1d5db",f=e?.colors?.input_filled_text||"#111827",g=e?.colors?.error||"#dc2626",_=e?.colors?.widget_background||"#ffffff",w=e?.colors?.widget_border||"#e5e7eb",k=e?.borders?.widget_corner_radius||8,z=e?.borders?.input_border_radius||4,N=e?.borders?.button_border_radius||4,I=e?.borders?.show_widget_shadow??!0,S=e?.fonts?.title?.size||24,E=e?.fonts?.title?.bold??!0,P=e?.fonts?.body_text?.size||14,G={backgroundColor:_,borderColor:w,borderRadius:`${k}px`,boxShadow:I?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:l},Z={fontSize:`${S}px`,fontWeight:E?"700":"400",color:e?.colors?.header||l},W={fontSize:`${P}px`,color:e?.colors?.input_labels_placeholders||"#6b7280"},M={backgroundColor:d,borderColor:t?g:u,borderRadius:`${z}px`,color:f},ce={backgroundColor:a,color:c,borderRadius:`${N}px`},le=e?.widget?.logo_position||"center",fe=le==="left"?"text-left":le==="right"?"text-right":"text-center",$e=e?.widget?.logo_url||n?.logo_url,be=le!=="none"&&$e;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",s),children:p(en,{style:G,className:"border",children:[p(tn,{children:[be&&p("div",{className:Q("mb-4",fe),children:p(Rt,{theme:e,branding:n})}),p(nn,{style:Z,children:y.t("reset_password_title","Reset Password")}),p(rn,{style:W,children:`${y.t("reset_password_description","Set a new password for")} ${i}`})]}),p(on,{children:p("form",{method:"post",className:"space-y-4",children:[p("input",{type:"hidden",name:"state",value:r.authParams.state}),p("div",{className:"space-y-2",children:[p(_t,{htmlFor:"password",style:W,children:y.t("new_password","New Password")}),p("div",{className:"relative","data-password-toggle":!0,children:[p(Pt,{id:"password",name:"password",type:"password","data-password-input":"password",placeholder:y.t("enter_new_password_placeholder","Enter new password"),required:!0,error:!!t,className:"border pr-8",style:M}),p("button",{type:"button","data-password-toggle-btn":!0,className:"absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 transition-colors","aria-label":y.t("toggle_password_visibility","Toggle password visibility"),children:[p("svg",{"data-show-icon":!0,xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),p("circle",{cx:"12",cy:"12",r:"3"})]}),p("svg",{"data-hide-icon":!0,className:"hidden",xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),p("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),p("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),p("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]})]})]})]}),p("div",{className:"space-y-2",children:[p(_t,{htmlFor:"re-enter-password",style:W,children:y.t("confirm_password","Confirm Password")}),p("div",{className:"relative","data-password-toggle":!0,children:[p(Pt,{id:"re-enter-password",name:"re-enter-password",type:"password","data-password-input":"re-enter-password",placeholder:y.t("reenter_new_password_placeholder","Re-enter new password"),required:!0,error:!!t,className:"border pr-8",style:M}),p("button",{type:"button","data-password-toggle-btn":!0,className:"absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700 transition-colors","aria-label":y.t("toggle_password_visibility","Toggle password visibility"),children:[p("svg",{"data-show-icon":!0,xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"}),p("circle",{cx:"12",cy:"12",r:"3"})]}),p("svg",{"data-hide-icon":!0,className:"hidden",xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24"}),p("path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"}),p("path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"}),p("line",{x1:"2",x2:"22",y1:"2",y2:"22"})]})]})]})]}),t&&p(Re,{children:t}),p(Jt,{type:"submit",className:"w-full",style:ce,disabled:!1,children:y.t("reset_password_cta","Reset Password")})]})})]})})},Dx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.z.string().openapi({description:"The code parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,loginSession:s,useShadcn:a}=await he(t,e);if(!s.authParams.username)throw new v(400,{message:"Username required"});return a?t.html(p(we,{title:y.t("reset_password_title","Reset Password"),theme:n,branding:r,client:i,children:p(Oi,{theme:n,branding:r,loginSession:s,email:s.authParams.username,client:i})})):t.html(p(Rr,{theme:n,branding:r,client:i,email:s.authParams.username}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.z.string().openapi({description:"The code parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({password:o.z.string(),"re-enter-password":o.z.string()})}}}},responses:{200:{description:"Response"}}}),async t=>{const{state:e,code:n}=t.req.valid("query"),{password:r,"re-enter-password":i}=t.req.valid("form"),{env:s}=t,{theme:a,branding:c,client:l,loginSession:d,useShadcn:u}=await he(t,e);if(!d.authParams.username)throw new v(400,{message:"Username required"});if(r!==i)return u?t.html(p(we,{title:y.t("reset_password_title","Reset Password"),theme:a,branding:c,client:l,children:p(Oi,{error:y.t("create_account_passwords_didnt_match"),theme:a,branding:c,loginSession:d,email:d.authParams.username,client:l})}),400):t.html(p(Rr,{error:y.t("create_account_passwords_didnt_match"),theme:a,branding:c,client:l,email:d.authParams.username}),400);const f=await fi({userAdapter:s.data.users,tenant_id:l.tenant.id,username:d.authParams.username,provider:"auth2"});if(!f)throw new v(400,{message:"User not found"});const g=await Vp(s.data,l.tenant.id,f.connection);try{await Hp(g,{tenantId:l.tenant.id,userId:f.user_id,newPassword:r,userData:f,data:s.data})}catch(_){const w=_?.message||y.t("create_account_weak_password");return u?t.html(p(we,{title:y.t("reset_password_title","Reset Password"),theme:a,branding:c,client:l,children:p(Oi,{error:w,theme:a,branding:c,loginSession:d,email:d.authParams.username,client:l})}),400):t.html(p(Rr,{error:w,theme:a,branding:c,client:l,email:d.authParams.username}),400)}try{if(!await s.data.codes.get(l.tenant.id,n,"password_reset")){const k=y.t("password_reset_code_expired","Code not found or expired");return u?t.html(p(we,{title:y.t("reset_password_title","Reset Password"),theme:a,branding:c,client:l,children:p(Oi,{error:k,theme:a,branding:c,loginSession:d,email:d.authParams.username,client:l})}),400):t.html(p(Rr,{error:k,theme:a,branding:c,client:l,email:d.authParams.username}),400)}const w=await s.data.passwords.get(l.tenant.id,f.user_id);w&&await s.data.passwords.update(l.tenant.id,{id:w.id,user_id:f.user_id,password:w.password,algorithm:w.algorithm,is_current:!1}),await s.data.passwords.create(l.tenant.id,{user_id:f.user_id,password:await Pn.hash(r,10),algorithm:"bcrypt",is_current:!0}),f.email_verified||await s.data.users.update(l.tenant.id,f.user_id,{email_verified:!0}),await ie(t,l.tenant.id,{type:te.SUCCESS_CHANGE_PASSWORD,description:`Password changed for ${f.email}`,userId:f.user_id})}catch(_){console.error("Password reset failed:",_);const w=_ instanceof Error?_.message:JSON.stringify(_);await ie(t,l.tenant.id,{type:te.FAILED_CHANGE_PASSWORD,description:`Password reset failed for ${f.email}: ${w}`,userId:f.user_id});let k;return _ instanceof Ht?k=y.t(_.code,{defaultValue:_.message,..._.params}):k=y.t("password_reset_failed","The password could not be reset"),u?t.html(p(we,{title:y.t("reset_password_title","Reset Password"),theme:a,branding:c,client:l,children:p(Oi,{error:k,theme:a,branding:c,loginSession:d,email:d.authParams.username,client:l})}),400):t.html(p(Rr,{error:k,theme:a,branding:c,client:l,email:d.authParams.username}),400)}return t.html(p(wt,{message:y.t("password_has_been_reset"),theme:a,branding:c,client:l,state:e}))}),nw=t=>{const{error:e,theme:n,branding:r,client:i,email:s,state:a}=t;return p(Se,{title:y.t("forgot_password_title"),theme:n,branding:r,client:i,children:[p("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:y.t("forgot_password_title")}),p("div",{className:"mb-6 text-gray-300",children:y.t("forgot_password_description")}),p("div",{className:"flex flex-1 flex-col justify-center",children:[p(Bt,{className:"pt-2",children:[p("input",{type:"email",name:"username",placeholder:y.t("email_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",value:s,disabled:!!s}),e&&p(Re,{children:e}),p(xe,{className:"sm:mt-4 !text-base",children:y.t("forgot_password_cta")})]}),p(lt,{state:a})]})]})},Mx=({error:t,theme:e,branding:n,loginSession:r,email:i,className:s})=>{const a=e?.colors?.primary_button||n?.colors?.primary||"#0066cc",c=e?.colors?.primary_button_label||"#ffffff",l=e?.colors?.body_text||"#333333",d=e?.colors?.input_background||"#ffffff",u=e?.colors?.input_border||"#d1d5db",f=e?.colors?.input_filled_text||"#111827",g=e?.colors?.error||"#dc2626",_=e?.colors?.widget_background||"#ffffff",w=e?.colors?.widget_border||"#e5e7eb",k=e?.borders?.widget_corner_radius||8,z=e?.borders?.input_border_radius||4,N=e?.borders?.button_border_radius||4,I=e?.borders?.show_widget_shadow??!0,S=e?.fonts?.title?.size||24,E=e?.fonts?.title?.bold??!0,P=e?.fonts?.body_text?.size||14,G={backgroundColor:_,borderColor:w,borderRadius:`${k}px`,boxShadow:I?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:l},Z={fontSize:`${S}px`,fontWeight:E?"700":"400",color:e?.colors?.header||l},W={fontSize:`${P}px`,color:e?.colors?.input_labels_placeholders||"#6b7280"},M={backgroundColor:d,borderColor:t?g:u,borderRadius:`${z}px`,color:f},ce={backgroundColor:a,color:c,borderRadius:`${N}px`},le=e?.widget?.logo_position||"center",fe=le==="left"?"text-left":le==="right"?"text-right":"text-center",$e=e?.widget?.logo_url||n?.logo_url,be=le!=="none"&&$e;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",s),children:p(en,{style:G,className:"border",children:[p(tn,{children:[be&&p("div",{className:Q("mb-4",fe),children:p(Rt,{theme:e,branding:n})}),p(nn,{style:Z,children:y.t("forgot_password_title","Forgot Password")}),p(rn,{style:W,children:y.t("forgot_password_description","Enter your email address and we'll send you a link to reset your password.")})]}),p(on,{children:[p("form",{method:"post",className:"space-y-4",children:[p("input",{type:"hidden",name:"state",value:r.authParams.state}),p("div",{className:"space-y-2",children:[p(_t,{htmlFor:"username",style:W,className:"text-sm font-medium",children:y.t("email_label","Email")}),p(Pt,{id:"username",type:"email",name:"username",placeholder:y.t("email_placeholder","Email Address"),value:i,disabled:!!i,style:M,className:"w-full",required:!0})]}),t&&p(Re,{children:t}),p(Jt,{type:"submit",className:"w-full",style:ce,disabled:!1,children:y.t("forgot_password_cta","Send Reset Link")})]}),p("div",{className:"mt-4 text-center",children:p("a",{href:`/u/login/identifier?state=${encodeURIComponent(r.authParams.state||"")}`,className:"text-sm",style:{color:a},children:y.t("back_to_login","Back to Login")})})]})]})})},rw=t=>{const{theme:e,branding:n,client:r,state:i}=t;return p(Se,{title:"Login",theme:e,branding:n,client:r,children:[p("div",{className:"flex flex-1 flex-col justify-center",children:[p("div",{children:y.t("forgot_password_email_sent")}),p("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[p(Ne,{className:"text-base",name:"info-bubble"}),p("div",{className:"text-sm text-gray-300 md:text-sm",children:y.t("sent_code_spam")})]})]}),p(lt,{state:i})]})},qx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,loginSession:s,useShadcn:a}=await he(t,e);return a?t.html(p(we,{title:y.t("forgot_password_title","Forgot Password"),theme:n,branding:r,client:i,children:p(Mx,{theme:n,branding:r,loginSession:s,email:s.authParams.username,client:i})})):t.html(p(nw,{theme:n,branding:r,client:i,state:e,email:s.authParams.username}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,loginSession:s}=await he(t,e);return await D8(t,i,s.authParams.username,s.id),t.html(p(rw,{theme:n,branding:r,client:i,state:e}))}),iw=({theme:t,branding:e,client:n,state:r,user:i})=>p(Se,{title:X("check_email_title"),theme:t,branding:e,client:n,children:p("div",{className:"flex flex-1 flex-col justify-center",children:[p("div",{className:"mb-8 text-gray-700 dark:text-gray-300",children:[p(Un,{i18nKey:"currently_logged_in_as",components:[p("span",{className:"font-semibold text-gray-900 dark:text-white"},"span")],values:{email:i.email||""}}),p("br",{}),X("continue_with_sso_provider_headline")]}),p("div",{className:"space-y-6",children:[p(Bt,{children:p(xe,{className:"!text-base",children:p("span",{children:y.t("yes_continue_with_existing_account")})})}),p("a",{className:"block text-center text-primary hover:text-primaryHover focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 dark:focus:ring-offset-gray-900",href:`/u/login/identifier?state=${encodeURIComponent(r)}`,children:y.t("no_use_another")})]})]})}),Fx=({theme:t,branding:e,state:n,user:r,className:i})=>{const s=t?.colors?.primary_button||e?.colors?.primary||"#0066cc",a=t?.colors?.primary_button_label||"#ffffff",c=t?.colors?.body_text||"#333333",l=t?.colors?.widget_background||"#ffffff",d=t?.colors?.widget_border||"#e5e7eb",u=t?.borders?.widget_corner_radius||8,f=t?.borders?.button_border_radius||4,g=t?.borders?.show_widget_shadow??!0,_=t?.fonts?.title?.size||24,w=t?.fonts?.title?.bold??!0,k=t?.fonts?.body_text?.size||14,z={backgroundColor:l,borderColor:d,borderRadius:`${u}px`,boxShadow:g?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:c},N={fontSize:`${_}px`,fontWeight:w?"700":"400",color:t?.colors?.header||c},I={fontSize:`${k}px`,color:t?.colors?.input_labels_placeholders||"#6b7280"},S={backgroundColor:s,color:a,borderRadius:`${f}px`},E={color:t?.colors?.links_focused_components||s,fontSize:`${k}px`},P=t?.widget?.logo_position||"center",G=P==="left"?"text-left":P==="right"?"text-right":"text-center",Z=t?.widget?.logo_url||e?.logo_url,W=P!=="none"&&Z;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",i),children:p(en,{style:z,className:"border",children:[p(tn,{children:[W&&p("div",{className:Q("mb-4",G),children:p(Rt,{theme:t,branding:e})}),p(nn,{style:N,children:y.t("continue_with_account","Continue with account")}),p(rn,{style:I,children:[p(Un,{i18nKey:"currently_logged_in_as",components:[p("span",{className:"font-semibold"},"span")],values:{email:r.email||""}}),p("br",{}),p("br",{}),y.t("continue_with_sso_provider_headline","Do you want to continue with this account?")]})]}),p(on,{children:p("form",{method:"post",children:p("div",{className:"grid gap-4",children:[p(Jt,{type:"submit",className:"w-full transition-colors hover:brightness-90",style:S,children:y.t("yes_continue_with_existing_account","Yes, continue")}),p("div",{className:"text-center",children:p("a",{href:`/u/login/identifier?state=${encodeURIComponent(n)}`,className:"text-sm hover:underline focus:outline-none focus:ring-2 focus:ring-offset-2 transition-colors",style:E,children:y.t("no_use_another","No, use another account")})})]})})})]})})},Hx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"HTML page to check account status or verify email.",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to login identifier page if no valid session.",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{env:e}=t,{state:n}=t.req.valid("query"),{theme:r,branding:i,client:s,useShadcn:a}=await he(t,n);if(!s||!s.tenant?.id)return console.error("Client or tenant ID missing in GET /u/check-account after initJSXRoute"),t.html(p(wt,{theme:r,branding:i,client:s,state:n,pageTitle:y.t("error_page_title")||"Error",message:y.t("configuration_error_message")||"A configuration error occurred."}),500);const c=Wr(s.tenant.id,t.req.header("cookie")),l=c?await e.data.sessions.get(s.tenant.id,c):null;if(!l)return t.redirect(`/u/login/identifier?state=${n}`);const d=await e.data.users.get(s.tenant.id,l.user_id);return d?a?t.html(p(we,{title:y.t("continue_with_account","Continue with account"),theme:r,branding:i,client:s,children:p(Fx,{theme:r,branding:i,client:s,state:n,user:d})})):t.html(p(iw,{theme:r,branding:i,client:s,state:n,user:d})):t.redirect(`/u/login/identifier?state=${n}`)}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{302:{description:"Redirect to continue authentication flow or to login identifier.",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page for unexpected issues or if TokenResponse is returned.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{env:e}=t,{state:n}=t.req.valid("query"),{theme:r,branding:i,client:s,loginSession:a}=await he(t,n);if(!s||!s.tenant?.id)return console.error("Client or tenant ID missing in POST /u/check-account after initJSXRoute"),t.html(p(wt,{theme:r,branding:i,client:s,state:n,pageTitle:y.t("error_page_title")||"Error",message:y.t("configuration_error_message")}),500);const c=Wr(s.tenant.id,t.req.header("cookie")),l=c?await e.data.sessions.get(s.tenant.id,c):null;if(!l)return t.redirect(`/u/login/identifier?state=${n}`);const d=await e.data.users.get(s.tenant.id,l.user_id);if(!d)return t.redirect(`/u/login/identifier?state=${n}`);await e.data.loginSessions.update(s.tenant.id,a.id,{session_id:l.id});const u=await Gt(t,{user:d,authParams:a.authParams,client:s,loginSession:{...a,session_id:l.id},sessionId:l.id});if(!(u instanceof Response))throw new v(500,{message:y.t("unexpected_error_try_again")});return u}),Vx=({width:t=18,height:e=18,className:n})=>p("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:e,viewBox:"0 0 640 640",className:n,fill:"currentColor",role:"img",focusable:"false",children:p("path",{d:"M416.9 85.2 372 130.1 509.9 268l44.9-44.9c13.6-13.5 21.2-31.9 21.2-51.1s-7.6-37.6-21.2-51.1l-35.7-35.7C505.6 71.6 487.2 64 468 64s-37.6 7.6-51.1 21.2M338.1 164 122.9 379.1c-10.7 10.7-18.5 24.1-22.6 38.7L64.9 545.6c-2.3 8.3 0 17.3 6.2 23.4s15.1 8.5 23.4 6.2l127.8-35.5c14.6-4.1 27.9-11.8 38.7-22.6l215-215.2z"})}),Kx=!1,A0=t=>{const{theme:e,branding:n,user:r,client:i,error:s,success:a,state:c,csrfToken:l}=t;return r.identities?.filter(d=>!(d.provider===r.provider&&d.user_id===r.user_id.split("|")[1])),p(Se,{title:y.t("account_title")||"Account Settings",theme:e,branding:n,client:i,children:[p("div",{className:"mb-4 text-2xl font-medium",children:y.t("account_title")}),p("div",{className:"mb-8 text-gray-300",children:y.t("account_page_description")}),s&&p(Re,{className:"mb-8",children:s}),a&&p("div",{className:"mb-8 text-green",children:a}),p("div",{className:"column-left gap-6 border-y border-gray-200/50 py-6 mb-8",children:[p("div",{className:"row-left w-full !justify-between !flex-nowrap gap-4",children:[p("div",{className:"column-left gap-1.5",children:[p("div",{className:"text-gray-300",children:y.t("email_placeholder")}),p("div",{className:"font-medium text-base text-gray-800 line-clamp-1 break-all",children:r.email||y.t("no_email_address")})]}),p("a",{className:"bg-gray-200/40 p-2 rounded-md hover:bg-gray-200/75",title:y.t("edit"),"aria-label":y.t("edit"),href:c?`/u/account/change-email?state=${encodeURIComponent(c)}`:`/u/account/change-email?client_id=${encodeURIComponent(i.client_id)}`,children:p(Vx,{})})]}),Kx]})]})},Gx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"HTML page showing account management interface.",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to login if no session",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{env:e}=t,{state:n}=t.req.valid("query"),{theme:r,branding:i,client:s,user:a,loginSession:c}=await $r(t,n);if(!s||!s.tenant?.id)return console.error("Client or tenant ID missing in GET /u/account after initJSXRoute"),t.html(p(wt,{theme:r,branding:i,client:s,state:n,pageTitle:y.t("error_page_title")||"Error",message:y.t("configuration_error_message")||"A configuration error occurred."}),500);const l=pe();return await e.data.loginSessions.update(s.tenant.id,c.id,{csrf_token:l}),t.html(p(A0,{theme:r,branding:i,user:a,client:s,state:n,csrfToken:l}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({action:o.z.enum(["unlink_account"]),provider:o.z.string().optional(),user_id:o.z.string().optional(),csrf_token:o.z.string().optional()})}}}},responses:{200:{description:"HTML response with form results",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to login if no session",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{env:e}=t,{state:n}=t.req.valid("query"),r=t.req.valid("form"),{theme:i,branding:s,client:a,user:c,loginSession:l}=await $r(t,n);let d,u;try{if(r.action==="unlink_account"&&r.provider&&r.user_id){if(!r.csrf_token||r.csrf_token!==l.csrf_token)throw new Error("Invalid CSRF token");await e.data.users.unlink(a.tenant.id,c.user_id,r.provider,r.user_id),u=y.t("account_unlinked_successfully")||"Account unlinked successfully"}}catch{d=y.t("operation_failed")||"Operation failed"}const f=await e.data.users.get(a.tenant.id,c.user_id),g=pe();return await e.data.loginSessions.update(a.tenant.id,l.id,{csrf_token:g}),t.html(p(A0,{theme:i,branding:s,user:f||c,client:a,error:d,success:u,state:n,csrfToken:g}))}),E0=t=>{const{theme:e,branding:n,user:r,client:i,state:s,error:a}=t;return p(Se,{title:y.t("change_email"),theme:e,branding:n,client:i,children:[p("div",{className:"mb-4 text-2xl font-medium",children:y.t("change_email")}),p("div",{className:"column-left gap-1 mb-8",children:[p("div",{className:"text-gray-300",children:y.t("current_email")}),p("div",{className:"font-medium text-base text-gray-800",children:r.email||y.t("no_email_address")})]}),p("div",{className:"flex flex-1 flex-col justify-center",children:[p(Bt,{children:[p("input",{type:"email",id:"email",name:"email",placeholder:y.t("new_email"),className:Q("mb-2 w-full rounded-lg border bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",{"border-red":a,"border-gray-100 dark:border-gray-500":!a}),required:!0}),a&&p(Re,{children:a}),p(xe,{className:"sm:mt-4 !text-base",children:[p("span",{children:y.t("continue")}),p(Ne,{className:"text-xs",name:"arrow-right"})]}),p("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[p("span",{className:"uicon-info-bubble text-base"}),p("div",{className:"text-sm text-gray-300 md:text-sm",children:y.t("new_email_code_info")})]})]}),p("a",{className:"block text-primary hover:text-primaryHover text-center",href:`/u/account?state=${encodeURIComponent(s)}`,children:y.t("go_back")})]})]})},Wx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"HTML page showing email change interface.",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to login if no session",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,user:s}=await $r(t,e);return t.html(p(E0,{theme:n,branding:r,user:s,client:i,state:e}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({email:o.z.string().toLowerCase()})}}}},responses:{200:{description:"HTML response with form results",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to change-email verification page",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{env:e}=t,{state:n}=t.req.valid("query"),{email:r}=t.req.valid("form"),{theme:i,branding:s,client:a,user:c,loginSession:l}=await $r(t,n),d=await e.data.users.list(a.tenant.id,{page:1,per_page:1,include_totals:!1,q:`email:"${r}"`});if(d.users.length>0&&d.users[0]?.user_id!==c.user_id)return t.html(p(E0,{theme:i,branding:s,user:c,client:a,state:n,error:y.t("email_already_taken")||"Email is already taken"}));const u=Ln(),f=pe();await e.data.codes.create(a.tenant.id,{code_id:f,login_id:"",code_type:"email_verification",expires_at:new Date(Date.now()+Hl).toISOString(),user_id:c.user_id}),await e.data.codes.create(a.tenant.id,{code_id:u,login_id:"",code_type:"email_verification",expires_at:new Date(Date.now()+Hl).toISOString(),user_id:c.user_id});const g=l.authParams?.ui_locales?.split(" ")?.map(_=>_.split("-")[0])[0];return await Kp(t,{to:r,code:u,language:g}),t.redirect(`/u/account/change-email-verify?state=${encodeURIComponent(n)}&email=${encodeURIComponent(r)}&change_id=${f}`)}),C0=6,$u=({error:t,theme:e,branding:n,client:r,email:i,success:s,state:a,redirectUrl:c})=>s?p(Se,{title:y.t("success"),theme:e,branding:n,client:r,children:[p("div",{className:"mb-4 text-2xl font-medium",children:y.t("success")}),p("div",{className:"mb-8 text-gray-300",children:p(Un,{i18nKey:"email_changed_to_template",components:[p("span",{className:"text-black dark:text-white"},"span")],values:{email:i}})}),p("div",{className:"flex flex-1 flex-col justify-center",children:p(xe,{Component:"a",href:c||(a?`/u/account?state=${encodeURIComponent(a)}`:`/u/account?client_id=${encodeURIComponent(r.client_id)}`),className:"sm:mt-4 !text-base",children:[p("span",{children:y.t("continue")}),p(Ne,{className:"text-xs",name:"arrow-right"})]})})]}):p(Se,{title:y.t("verify_email_verify"),theme:e,branding:n,client:r,children:[p("div",{className:"mb-4 text-2xl font-medium",children:y.t("verify_email_verify")}),p("div",{className:"mb-8 text-gray-300",children:p(Un,{i18nKey:"code_sent_template",components:[p("span",{className:"text-black dark:text-white"},"span")],values:{username:i}})}),p("div",{className:"flex flex-1 flex-col justify-center",children:[p(Bt,{className:"pt-2",children:[p("input",{autoFocus:!0,type:"text",pattern:"[0-9]*",maxLength:C0,inputMode:"numeric",name:"code",placeholder:"******",className:Q("mb-2 w-full rounded-lg border bg-gray-100 px-4 pb-2 pt-2.5 text-center indent-[5px] font-mono text-3xl placeholder:text-gray-300 dark:bg-gray-600 md:text-3xl",{"border-red":t,"border-gray-100 dark:border-gray-500":!t}),minLength:C0,required:!0,id:"code-input"}),t&&p(Re,{children:t}),p(xe,{className:"sm:mt-4 !text-base",children:[p("span",{children:y.t("continue")}),p(Ne,{className:"text-xs",name:"arrow-right"})]}),p("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[p(Ne,{className:"text-base",name:"info-bubble"}),p("div",{className:"text-sm text-gray-300 md:text-sm",children:y.t("sent_code_spam")})]})]}),p("a",{className:"block text-primary hover:text-primaryHover text-center",href:a?`/u/account?state=${encodeURIComponent(a)}`:`/u/account?client_id=${encodeURIComponent(r.client_id)}`,children:y.t("go_back")})]})]}),Jx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),email:o.z.string().email(),change_id:o.z.string()})},responses:{200:{description:"HTML page for email change verification",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to account or login if no session",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{state:e,email:n,change_id:r}=t.req.valid("query"),{theme:i,branding:s,client:a,user:c}=await $r(t,e),l=await t.env.data.codes.get(a.tenant.id,r,"email_verification");return!l||l.user_id!==c.user_id?t.redirect(`/u/account?state=${e}`):t.html(p($u,{theme:i,branding:s,client:a,email:n,state:e}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),email:o.z.string().toLowerCase(),change_id:o.z.string()}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({code:o.z.string()})}}}},responses:{200:{description:"HTML response with verification result",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to confirmation page on success",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{env:e}=t,{state:n,email:r,change_id:i}=t.req.valid("query"),{code:s}=t.req.valid("form"),{theme:a,branding:c,client:l,user:d}=await $r(t,n);let u;try{const f=await e.data.codes.get(l.tenant.id,i,"email_verification");if(!f)u=y.t("invalid_request");else if(f.user_id!==d.user_id)u=y.t("invalid_request");else if(f.used_at)u=y.t("code_already_used");else if(new Date(f.expires_at)<new Date)u=y.t("code_expired");else{const g=await e.data.codes.get(l.tenant.id,s,"email_verification");if(!g)u=y.t("invalid_code");else if(g.used_at)u=y.t("code_already_used");else if(new Date(g.expires_at)<new Date)u=y.t("code_expired");else if(g.user_id!==d.user_id)u=y.t("invalid_code");else return await e.data.codes.used(l.tenant.id,i),await e.data.codes.used(l.tenant.id,s),await e.data.users.update(l.tenant.id,d.user_id,{email:r,email_verified:!0}),t.redirect(`/u/account/change-email-confirmation?state=${encodeURIComponent(n)}&email=${encodeURIComponent(r)}`)}}catch{u=y.t("operation_failed")}return t.html(p($u,{theme:a,branding:c,client:l,email:r,error:u,state:n}))}),Xx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),email:o.z.string().email()})},responses:{200:{description:"HTML page showing email change confirmation",content:{"text/html":{schema:o.z.string()}}},302:{description:"Redirect to login if no session",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - HTML error page if state is missing or other input error.",content:{"text/html":{schema:o.z.string()}}},500:{description:"Internal Server Error - HTML error page.",content:{"text/html":{schema:o.z.string()}}}}}),async t=>{const{state:e,email:n}=t.req.valid("query"),{theme:r,branding:i,client:s,loginSession:a}=await $r(t,e);if(!s||!s.tenant?.id)return console.error("Client or tenant ID missing in GET /u/change-email-confirmation after initJSXRoute"),t.html(p(wt,{theme:r,branding:i,client:s,state:e,pageTitle:y.t("error_page_title")||"Error",message:y.t("configuration_error_message")||"A configuration error occurred."}),500);let c=`/u/account?state=${encodeURIComponent(e)}`;return a?.authorization_url&&new URL(a.authorization_url).searchParams.get("screen_hint")==="change-email"&&(c=a.authParams?.redirect_uri||c),t.html(p($u,{theme:r,branding:i,client:s,email:n,success:!0,state:e,redirectUrl:c}))}),ow=t=>{const{theme:e,branding:n,client:r,email:i,state:s}=t;return p(Se,{title:y.t("create_password_account_title"),theme:e,branding:n,client:r,children:[p("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:y.t("create_password_account_title")}),p("div",{className:"mb-6 text-gray-300",children:y.t("enter_email_for_verification_description")}),p("div",{className:"flex flex-1 flex-col justify-center",children:p(Bt,{className:"pt-2",children:[p("input",{type:"email",name:"username",placeholder:y.t("email_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",required:!0,value:i,disabled:!0}),p(xe,{className:"sm:mt-4 !text-base",children:y.t("send")})]})}),p(lt,{state:s})]})},Zx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,loginSession:s}=await he(t,e),{username:a}=s.authParams;if(!a)throw new v(400,{message:"Username required"});return t.html(p(ow,{state:e,theme:n,branding:r,client:i,email:a}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{loginSession:n,client:r}=await he(t,e),{username:i}=n.authParams;if(!i)throw new v(400,{message:"Username required"});const s=await t.env.data.codes.create(r.tenant.id,{code_id:Ln(),code_type:"email_verification",login_id:n.id,expires_at:new Date(Date.now()+Hl).toISOString()});return await T8(t,i,s.code_id,n.id),t.redirect(`/u/pre-signup-sent?state=${e}`)}),sw=t=>{const{redirectUrl:e,theme:n,branding:r,client:i}=t;return p(Se,{title:y.t("invalid_session_title"),theme:n,branding:r,client:i,children:[p("div",{className:"flex flex-1 flex-col justify-center",children:y.t("invalid_session_body")}),p("div",{className:"flex flex-1 flex-col justify-center",children:e&&p("a",{className:"block text-primary hover:text-primaryHover text-center",href:e,children:y.t("go_back")})})]})},Yx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string()})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,loginSession:s}=await he(t,e);let a;return s.authParams.redirect_uri&&s.authParams.state&&(a=new URL(s.authParams.redirect_uri),a.searchParams.set("state",s.authParams.state),a.searchParams.set("error","invalid_session"),a.searchParams.set("error_description",s.authParams.username||"")),t.html(p(sw,{redirectUrl:a?.href,theme:n,branding:r,client:i}))}),Qx=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.z.string().openapi({description:"The code parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i}=await he(t,e);return t.html(p(wt,{message:"Not implemented",pageTitle:"User info",theme:n,branding:r,client:i,state:e}))}),aw=({theme:t,branding:e,client:n,state:r})=>{const i=new URLSearchParams({state:r});return p(Se,{title:y.t("email_validated"),theme:t,branding:e,client:n,children:[p("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:y.t("email_validated")}),p("div",{className:"flex flex-1 flex-col justify-center mb-7",children:p(xe,{Component:"a",href:`/u/enter-password?${i}`,className:"text-base sm:mt-4 md:text-base",children:p("div",{className:"flex items-center space-x-2",children:[p("span",{children:y.t("email_validated_cta")}),p(Ne,{className:"text-xs",name:"arrow-right"})]})})})]})},eS=({theme:t,branding:e,loginSession:n,className:r})=>{const i=t?.colors?.primary_button||e?.colors?.primary||"#0066cc",s=t?.colors?.primary_button_label||"#ffffff",a=t?.colors?.body_text||"#333333",c=t?.colors?.widget_background||"#ffffff",l=t?.colors?.widget_border||"#e5e7eb",d=t?.colors?.success||"#10b981",u=t?.borders?.widget_corner_radius||8,f=t?.borders?.button_border_radius||4,g=t?.borders?.show_widget_shadow??!0,_=t?.fonts?.title?.size||24,w=t?.fonts?.title?.bold??!0,k=t?.fonts?.body_text?.size||14,z={backgroundColor:c,borderColor:l,borderRadius:`${u}px`,boxShadow:g?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:a},N={fontSize:`${_}px`,fontWeight:w?"700":"400",color:t?.colors?.header||a},I={fontSize:`${k}px`,color:t?.colors?.input_labels_placeholders||"#6b7280"},S={backgroundColor:i,color:s,borderRadius:`${f}px`},E=t?.widget?.logo_position||"center",P=E==="left"?"text-left":E==="right"?"text-right":"text-center",G=t?.widget?.logo_url||e?.logo_url,Z=E!=="none"&&G;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",r),children:p(en,{style:z,className:"border",children:[p(tn,{children:[Z&&p("div",{className:Q("mb-4",P),children:p(Rt,{theme:t,branding:e})}),p("div",{className:"flex justify-center mb-4",children:p("div",{className:"rounded-full p-3",style:{backgroundColor:`${d}15`},children:p("svg",{xmlns:"http://www.w3.org/2000/svg",width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:d,"stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),p("polyline",{points:"22 4 12 14.01 9 11.01"})]})})}),p(nn,{style:N,className:"text-center",children:y.t("email_validated","Email Verified")}),p(rn,{style:I,className:"text-center",children:y.t("email_validated_description","Your email has been successfully verified. You can now continue to login.")})]}),p(on,{children:p("a",{href:`/u/enter-password?state=${encodeURIComponent(n.authParams.state||"")}`,className:"w-full flex items-center justify-center gap-2 h-10 px-4 py-2 rounded-md font-medium transition-colors",style:S,children:[p("span",{children:y.t("email_validated_cta","Continue to Login")}),p("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:[p("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),p("polyline",{points:"12 5 19 12 12 19"})]})]})})]})})},tS=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.z.string().openapi({description:"The code parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e,code:n}=t.req.valid("query"),{env:r}=t,{client:i,loginSession:s,theme:a,branding:c,useShadcn:l}=await he(t,e),{username:d}=s.authParams;if(!d)throw new v(400,{message:"Username not found in state"});const u=await fi({userAdapter:r.data.users,tenant_id:i.tenant.id,username:d,provider:"auth2"});if(!u)throw new v(500,{message:"No user found"});if(!await r.data.codes.get(i.tenant.id,n,"email_verification"))throw new v(400,{message:"Code not found or expired"});await r.data.users.update(i.tenant.id,u.user_id,{email_verified:!0});const _=(await Ru(r.data.users,i.tenant.id,d)).filter(w=>w.provider!=="auth2");if(_.length>0){const w=_.filter(k=>!k.linked_to);w.length>1&&console.error("More than one primary user found for email",d),w.length===0&&console.error("No primary user found for email",d),w.length===1&&await r.data.users.update(i.tenant.id,u.user_id,{linked_to:w[0]?.user_id})}return l?t.html(p(we,{title:y.t("email_validated","Email Verified"),theme:a,branding:c,client:i,children:p(eS,{theme:a,branding:c,loginSession:s,client:i})})):t.html(p(aw,{theme:a,branding:c,client:i,state:e}))}),cw=t=>{const{theme:e,branding:n,client:r,email:i,state:s}=t;return p(Se,{title:y.t("sign_up_success"),theme:e,branding:n,client:r,children:[p("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:y.t("email_verification_for_signup_sent_title")}),p("div",{className:"flex flex-1 flex-col justify-center",children:[p("div",{className:"mb-6 text-gray-300",children:p(Un,{i18nKey:"email_verification_for_signup_sent_description",components:[p("span",{className:"text-black dark:text-white"},"span")],values:{email:i}})}),p("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[p(Ne,{className:"text-base",name:"info-bubble"}),p("div",{className:"text-sm text-gray-300 md:text-sm",children:y.t("sent_code_spam")})]})]}),p(lt,{state:s})]})},nS=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,loginSession:s}=await he(t,e),{username:a}=s.authParams;if(!a)throw new v(400,{message:"Username required"});return t.html(p(cw,{theme:n,branding:r,client:i,state:e,email:a}))}),Zp=`
93
93
  @font-face{font-display:swap;font-family:KHTeka;font-style:normal;font-weight:400;src:url(https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Regular.woff2) format("woff2")}@font-face{font-display:swap;font-family:KHTeka;font-style:normal;font-weight:500;src:url(https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Medium.woff2) format("woff2")}@font-face{font-display:swap;font-family:KHTeka;font-style:normal;font-weight:600;src:url(https://assets.sesamy.com/fonts/khteka/WOFF2/KHTeka-Bold.woff2) format("woff2")}@font-face{font-family:uicon;src:url(https://login2.sesamy.com/_next/static/media/uicon.0b00e08a.woff2)}[class*=" uicon-"],[class^=uicon-]{font-family:uicon!important;font-size:inherit;font-style:normal;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased}.uicon-apple:before{content:"\\ea01"}.uicon-arrow-down:before{content:"\\ea02"}.uicon-arrow-left:before{content:"\\ea03"}.uicon-arrow-right:before{content:"\\ea04"}.uicon-arrow-up:before{content:"\\ea05"}.uicon-facebook:before{content:"\\ea06"}.uicon-google:before{content:"\\ea07"}.uicon-info-bubble:before{content:"\\ea08"}.uicon-info:before{content:"\\ea09"}.uicon-sesamy:before{content:"\\ea0a"}.uicon-spinner-circle:before{content:"\\ea0b"}.uicon-spinner-inner:before{content:"\\ea0c"}*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }
94
94
 
95
95
  /*! tailwindcss v3.4.18 | MIT License | https://tailwindcss.com*/*,:after,:before{border:0 solid #bfbcd7;box-sizing:border-box}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;font-family:KHTeka,Helvetica Neue,HelveticaNeue,TeX Gyre Heros,TeXGyreHeros,FreeSans,Nimbus Sans L,Liberation Sans,Arimo,Helvetica,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-tap-highlight-color:transparent}body{line-height:inherit;margin:0}hr{border-top-width:1px;color:inherit;height:0}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-size:1em;font-variation-settings:normal}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{border-collapse:collapse;border-color:inherit;text-indent:0}button,input,optgroup,select,textarea{color:inherit;font-family:inherit;font-feature-settings:inherit;font-size:100%;font-variation-settings:inherit;font-weight:inherit;letter-spacing:inherit;line-height:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{color:#4b4a58;opacity:1}input::placeholder,textarea::placeholder{color:#4b4a58;opacity:1}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{height:auto;max-width:100%}[hidden]:where(:not([hidden=until-found])){display:none}body,html{height:100%}body{--tw-bg-opacity:1;background-color:rgb(248 249 251/var(--tw-bg-opacity,1));font-size:1rem;letter-spacing:.0125rem;line-height:120%;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}@media (min-width:1280px){body{font-size:1.125rem;line-height:120%}}body:is(.dark *){--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}button,input,optgroup,select,textarea{font-size:.875rem;letter-spacing:.0125rem;line-height:120%}@media (min-width:1280px){button,input,optgroup,select,textarea{font-size:1rem;line-height:120%}}h1{font-size:1.5rem;font-weight:500;line-height:120%}@media (min-width:1280px){h1{font-size:2rem;line-height:120%}}@media (min-width:640px){h1{font-size:3rem;letter-spacing:-.0625rem;line-height:100%}}@media (min-width:1280px){h1{font-size:3.5rem;letter-spacing:-.0625rem;line-height:100%}}h2{font-size:1.25rem;font-weight:500;line-height:120%}@media (min-width:1280px){h2{font-size:1.5rem;line-height:120%}}@media (min-width:640px){h2{font-size:2rem;letter-spacing:0;line-height:120%}}@media (min-width:1280px){h2{font-size:3rem;letter-spacing:-.0625rem;line-height:100%}}h3{font-size:1.125rem;font-weight:500;line-height:120%}@media (min-width:1280px){h3{font-size:1.25rem;line-height:120%}}@media (min-width:640px){h3{font-size:1.5rem;line-height:120%}}@media (min-width:1280px){h3{font-size:2rem;line-height:120%}}h4{font-size:1rem;font-weight:500;line-height:120%}@media (min-width:1280px){h4{font-size:1.125rem;line-height:120%}}@media (min-width:640px){h4{font-size:1.125rem;line-height:120%}}@media (min-width:1280px){h4{font-size:1.5rem;line-height:120%}}h5{font-size:.875rem;font-weight:500;line-height:120%}@media (min-width:1280px){h5{font-size:1rem;line-height:120%}}@media (min-width:640px){h5{font-size:1rem;line-height:120%}}@media (min-width:1280px){h5{font-size:1.125rem;line-height:120%}}h6{font-size:.75rem;font-weight:500;line-height:135%}@media (min-width:1280px){h6{font-size:.875rem;line-height:120%}}@media (min-width:640px){h6{font-size:.875rem;line-height:120%}}@media (min-width:1280px){h6{font-size:1rem;line-height:120%}}.container{width:100%}@media (min-width:640px){.container{max-width:640px}}@media (min-width:1280px){.container{max-width:1280px}}@media (min-width:1920px){.container{max-width:1920px}}.pointer-events-none{pointer-events:none}.absolute{position:absolute}.relative{position:relative}.inset-0{inset:0}.left-0{left:0}.right-0{right:0}.right-2{right:.5rem}.top-0{top:0}.top-1\\/2{top:50%}.my-4{margin-bottom:1rem;margin-top:1rem}.mb-1{margin-bottom:.25rem}.mb-12{margin-bottom:3rem}.mb-16{margin-bottom:4rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-6{margin-bottom:1.5rem}.mb-7{margin-bottom:1.75rem}.mb-8{margin-bottom:2rem}.mr-2{margin-right:.5rem}.mr-4{margin-right:1rem}.mt-0\\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-5{margin-top:1.25rem}.mt-8{margin-top:2rem}.line-clamp-1{display:-webkit-box;overflow:hidden;-webkit-box-orient:vertical;-webkit-line-clamp:1}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.hidden{display:none}.h-10{height:2.5rem}.h-11{height:2.75rem}.h-12{height:3rem}.h-5{height:1.25rem}.h-9{height:2.25rem}.h-full{height:100%}.min-h-\\[calc\\(100vh-83px\\)\\]{min-height:calc(100vh - 83px)}.min-h-full{min-height:100%}.min-h-screen{min-height:100vh}.w-10{width:2.5rem}.w-12{width:3rem}.w-5{width:1.25rem}.w-9{width:2.25rem}.w-\\[calc\\(100\\%-theme\\(space\\.2\\)-theme\\(space\\.2\\)\\)\\]{width:calc(100% - 1rem)}.w-auto{width:auto}.w-full{width:100%}.min-w-0{min-width:0}.max-w-\\[1295px\\]{max-width:1295px}.max-w-md{max-width:28rem}.max-w-none{max-width:none}.max-w-sm{max-width:24rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.grow{flex-grow:1}.-translate-y-1\\/2{--tw-translate-y:-50%}.-translate-y-1\\/2,.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes spin{to{transform:rotate(1turn)}}.animate-spin{animation:spin 1s linear infinite}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.flex-col{flex-direction:column}.\\!flex-nowrap{flex-wrap:nowrap!important}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.\\!justify-between{justify-content:space-between!important}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(.5rem*(1 - var(--tw-space-x-reverse)));margin-right:calc(.5rem*var(--tw-space-x-reverse))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(1rem*(1 - var(--tw-space-x-reverse)));margin-right:calc(1rem*var(--tw-space-x-reverse))}.space-y-1\\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.375rem*var(--tw-space-y-reverse));margin-top:calc(.375rem*(1 - var(--tw-space-y-reverse)))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.5rem*var(--tw-space-y-reverse));margin-top:calc(.5rem*(1 - var(--tw-space-y-reverse)))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.75rem*var(--tw-space-y-reverse));margin-top:calc(.75rem*(1 - var(--tw-space-y-reverse)))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(1rem*var(--tw-space-y-reverse));margin-top:calc(1rem*(1 - var(--tw-space-y-reverse)))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(1.5rem*var(--tw-space-y-reverse));margin-top:calc(1.5rem*(1 - var(--tw-space-y-reverse)))}.overflow-hidden,.truncate{overflow:hidden}.truncate{text-overflow:ellipsis;white-space:nowrap}.break-all{word-break:break-all}.rounded-2xl{border-radius:1.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.625rem}.rounded-md{border-radius:.375rem}.rounded-r-lg{border-bottom-right-radius:.625rem;border-top-right-radius:.625rem}.border{border-width:1px}.border-y{border-top-width:1px}.border-b,.border-y{border-bottom-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-gray-100{--tw-border-opacity:1;border-color:rgb(248 249 251/var(--tw-border-opacity,1))}.border-gray-200{--tw-border-opacity:1;border-color:rgb(191 188 215/var(--tw-border-opacity,1))}.border-gray-200\\/50{border-color:rgba(191,188,215,.5)}.border-gray-300{--tw-border-opacity:1;border-color:rgb(136 134 159/var(--tw-border-opacity,1))}.border-gray-500{--tw-border-opacity:1;border-color:rgb(59 57 70/var(--tw-border-opacity,1))}.border-red{--tw-border-opacity:1;border-color:rgb(252 90 90/var(--tw-border-opacity,1))}.bg-gray-100{--tw-bg-opacity:1;background-color:rgb(248 249 251/var(--tw-bg-opacity,1))}.bg-gray-200\\/40{background-color:rgba(191,188,215,.4)}.bg-primary{background-color:var(--primary-color)}.bg-primaryHover{background-color:var(--primary-hover)}.bg-red\\/80{background-color:rgba(252,90,90,.8)}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity,1))}.bg-cover{background-size:cover}.bg-center{background-position:50%}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.px-0{padding-left:0;padding-right:0}.px-10{padding-left:2.5rem;padding-right:2.5rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-1\\.5{padding-bottom:.375rem;padding-top:.375rem}.py-10{padding-bottom:2.5rem;padding-top:2.5rem}.py-2{padding-bottom:.5rem;padding-top:.5rem}.py-3{padding-bottom:.75rem;padding-top:.75rem}.py-5{padding-bottom:1.25rem;padding-top:1.25rem}.py-6{padding-bottom:1.5rem;padding-top:1.5rem}.pb-2{padding-bottom:.5rem}.pb-8{padding-bottom:2rem}.pl-12{padding-left:3rem}.pl-6{padding-left:1.5rem}.pr-12{padding-right:3rem}.pr-6{padding-right:1.5rem}.pr-8{padding-right:2rem}.pt-0{padding-top:0}.pt-2{padding-top:.5rem}.pt-2\\.5{padding-top:.625rem}.pt-4{padding-top:1rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.indent-\\[5px\\]{text-indent:5px}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.\\!text-base{font-size:1rem!important;line-height:120%!important}.\\!text-xs{font-size:.75rem!important;line-height:135%!important}.text-2xl{font-size:1.5rem;line-height:120%}.text-3xl{font-size:2rem;line-height:120%}.text-base{font-size:1rem;line-height:120%}.text-lg{font-size:1.125rem;line-height:120%}.text-sm{font-size:.875rem;line-height:120%}.text-xl{font-size:1.25rem;line-height:120%}.text-xs{font-size:.75rem;line-height:135%}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.lowercase{text-transform:lowercase}.leading-\\[0\\]{line-height:0}.leading-none{line-height:1}.leading-tight{line-height:1.25}.tracking-tight{letter-spacing:-.025em}.text-\\[\\#B2B2B2\\]{--tw-text-opacity:1;color:rgb(178 178 178/var(--tw-text-opacity,1))}.text-black{--tw-text-opacity:1;color:rgb(0 0 0/var(--tw-text-opacity,1))}.text-gray-200{--tw-text-opacity:1;color:rgb(191 188 215/var(--tw-text-opacity,1))}.text-gray-300{--tw-text-opacity:1;color:rgb(136 134 159/var(--tw-text-opacity,1))}.text-gray-400{--tw-text-opacity:1;color:rgb(75 74 88/var(--tw-text-opacity,1))}.text-gray-500{--tw-text-opacity:1;color:rgb(59 57 70/var(--tw-text-opacity,1))}.text-gray-700{--tw-text-opacity:1;color:rgb(30 30 39/var(--tw-text-opacity,1))}.text-gray-800{--tw-text-opacity:1;color:rgb(20 20 26/var(--tw-text-opacity,1))}.text-gray-900{--tw-text-opacity:1;color:rgb(8 8 14/var(--tw-text-opacity,1))}.text-green{--tw-text-opacity:1;color:rgb(54 191 118/var(--tw-text-opacity,1))}.text-primary{color:var(--primary-color)}.text-red{--tw-text-opacity:1;color:rgb(252 90 90/var(--tw-text-opacity,1))}.text-textOnPrimary{color:var(--text-on-primary)}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.accent-\\[\\#4F2D7F\\]{accent-color:#4f2d7f}.opacity-40{opacity:.4}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-90{opacity:.9}.shadow-sm{--tw-shadow:0 1px 2px 0 rgba(0,0,0,.05);--tw-shadow-colored:0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.outline{outline-style:solid}.ring-offset-white{--tw-ring-offset-color:#fff}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition-all{transition-duration:.15s;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1)}.transition-colors{transition-duration:.15s;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1)}.transition-opacity{transition-duration:.15s;transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1)}.transition-transform{transition-duration:.15s;transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1)}.duration-200{transition-duration:.2s}.row-up-left{align-content:flex-start;display:flex;flex-direction:row;flex-wrap:wrap;justify-content:flex-start}.row-left{justify-content:flex-start}.row,.row-left{align-content:center;align-items:center;display:flex;flex-direction:row;flex-wrap:wrap}.row{justify-content:center}.column-left{align-items:flex-start}.column,.column-left{display:flex;flex-direction:column;justify-content:center}.column{align-items:center}@media (min-width:1280px){.text-5xl{font-size:5.125rem;letter-spacing:-.125rem;line-height:100%}.text-4xl{font-size:3.5rem}.text-3xl,.text-4xl{letter-spacing:-.0625rem;line-height:100%}.text-3xl{font-size:3rem}.text-2xl{font-size:2rem}.text-2xl,.text-xl{line-height:120%}.text-xl{font-size:1.5rem}.text-lg{font-size:1.25rem}.text-base,.text-lg{line-height:120%}.text-base{font-size:1.125rem}.text-sm{font-size:1rem}.text-sm,.text-xs{line-height:120%}.text-xs{font-size:.875rem}}:root{--primary-color:#7d68f4;--primary-hover:#9786f6;--text-on-primary:#fff}svg{transform:translate3d(var(--tw-translate-x),var(--tw-translate-y),0) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}*,:after,:before{text-underline-offset:4px}input[type=number],input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{-webkit-appearance:none;-moz-appearance:textfield!important}.btn.is-loading{cursor:not-allowed;opacity:.4;pointer-events:none}.btn .btn-spinner,.btn.is-loading .btn-label{opacity:0;visibility:hidden}.btn.is-loading .btn-spinner{opacity:1;visibility:visible}[class*=" uicon-"],[class^=uicon-]{letter-spacing:0;line-height:100%}.file\\:border-0::file-selector-button{border-width:0}.file\\:text-sm::file-selector-button{font-size:.875rem;line-height:120%}.file\\:font-medium::file-selector-button{font-weight:500}.placeholder\\:normal-case::-moz-placeholder{text-transform:none}.placeholder\\:normal-case::placeholder{text-transform:none}.placeholder\\:text-gray-300::-moz-placeholder{--tw-text-opacity:1;color:rgb(136 134 159/var(--tw-text-opacity,1))}.placeholder\\:text-gray-300::placeholder{--tw-text-opacity:1;color:rgb(136 134 159/var(--tw-text-opacity,1))}.placeholder\\:text-gray-500::-moz-placeholder{--tw-text-opacity:1;color:rgb(59 57 70/var(--tw-text-opacity,1))}.placeholder\\:text-gray-500::placeholder{--tw-text-opacity:1;color:rgb(59 57 70/var(--tw-text-opacity,1))}.first\\:rounded-l-md:first-child{border-bottom-left-radius:.375rem;border-top-left-radius:.375rem}.first\\:border-l:first-child{border-left-width:1px}.last\\:rounded-r-md:last-child{border-bottom-right-radius:.375rem;border-top-right-radius:.375rem}.hover\\:bg-black\\/5:hover{background-color:rgba(0,0,0,.05)}.hover\\:bg-gray-100:hover{--tw-bg-opacity:1;background-color:rgb(248 249 251/var(--tw-bg-opacity,1))}.hover\\:bg-gray-200:hover{--tw-bg-opacity:1;background-color:rgb(191 188 215/var(--tw-bg-opacity,1))}.hover\\:bg-gray-200\\/75:hover{background-color:rgba(191,188,215,.75)}.hover\\:bg-primaryHover:hover{background-color:var(--primary-hover)}.hover\\:bg-red\\/90:hover{background-color:rgba(252,90,90,.9)}.hover\\:text-gray-700:hover{--tw-text-opacity:1;color:rgb(30 30 39/var(--tw-text-opacity,1))}.hover\\:text-primaryHover:hover{color:var(--primary-hover)}.hover\\:underline:hover{text-decoration-line:underline}.hover\\:opacity-100:hover{opacity:1}.hover\\:brightness-90:hover{--tw-brightness:brightness(.9);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.focus\\:z-10:focus{z-index:10}.focus\\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\\:ring:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color)}.focus\\:ring-1:focus,.focus\\:ring:focus{box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus\\:ring-1:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color)}.focus\\:ring-2:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus\\:ring-primary:focus{--tw-ring-color:var(--primary-color)}.focus\\:ring-offset-2:focus{--tw-ring-offset-width:2px}.focus-visible\\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\\:ring-2:focus-visible{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus-visible\\:ring-offset-2:focus-visible{--tw-ring-offset-width:2px}.disabled\\:pointer-events-none:disabled{pointer-events:none}.disabled\\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:opacity-50:disabled{opacity:.5}.group[open] .group-open\\:rotate-90{--tw-rotate:90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.peer:disabled~.peer-disabled\\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\\:opacity-70{opacity:.7}.has-\\[\\:disabled\\]\\:opacity-50:has(:disabled){opacity:.5}.dark\\:border-gray-400:is(.dark *){--tw-border-opacity:1;border-color:rgb(75 74 88/var(--tw-border-opacity,1))}.dark\\:border-gray-500:is(.dark *){--tw-border-opacity:1;border-color:rgb(59 57 70/var(--tw-border-opacity,1))}.dark\\:border-gray-600:is(.dark *){--tw-border-opacity:1;border-color:rgb(40 40 52/var(--tw-border-opacity,1))}.dark\\:border-gray-700:is(.dark *){--tw-border-opacity:1;border-color:rgb(30 30 39/var(--tw-border-opacity,1))}.dark\\:bg-black:is(.dark *){--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity,1))}.dark\\:bg-gray-600:is(.dark *){--tw-bg-opacity:1;background-color:rgb(40 40 52/var(--tw-bg-opacity,1))}.dark\\:bg-gray-700:is(.dark *){--tw-bg-opacity:1;background-color:rgb(30 30 39/var(--tw-bg-opacity,1))}.dark\\:bg-gray-800:is(.dark *){--tw-bg-opacity:1;background-color:rgb(20 20 26/var(--tw-bg-opacity,1))}.dark\\:text-\\[\\#201a41\\]:is(.dark *){--tw-text-opacity:1;color:rgb(32 26 65/var(--tw-text-opacity,1))}.dark\\:text-gray-300:is(.dark *){--tw-text-opacity:1;color:rgb(136 134 159/var(--tw-text-opacity,1))}.dark\\:text-gray-400:is(.dark *){--tw-text-opacity:1;color:rgb(75 74 88/var(--tw-text-opacity,1))}.dark\\:text-white:is(.dark *){--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.dark\\:ring-offset-gray-900:is(.dark *){--tw-ring-offset-color:#08080e}.dark\\:placeholder\\:text-gray-400:is(.dark *)::-moz-placeholder{--tw-text-opacity:1;color:rgb(75 74 88/var(--tw-text-opacity,1))}.dark\\:placeholder\\:text-gray-400:is(.dark *)::placeholder{--tw-text-opacity:1;color:rgb(75 74 88/var(--tw-text-opacity,1))}.dark\\:hover\\:bg-black\\/90:hover:is(.dark *){background-color:rgba(0,0,0,.9)}.dark\\:hover\\:bg-gray-700:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(30 30 39/var(--tw-bg-opacity,1))}.dark\\:hover\\:bg-gray-800:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(20 20 26/var(--tw-bg-opacity,1))}.dark\\:focus\\:ring-offset-gray-900:focus:is(.dark *){--tw-ring-offset-color:#08080e}@media (min-width:640px){.sm\\:absolute{position:absolute}.sm\\:left-4{left:1rem}.sm\\:top-1\\/2{top:50%}.sm\\:mt-4{margin-top:1rem}.sm\\:inline{display:inline}.sm\\:h-6{height:1.5rem}.sm\\:min-h-\\[700px\\]{min-height:700px}.sm\\:w-6{width:1.5rem}.sm\\:w-\\[calc\\(100\\%-theme\\(space\\.16\\)-theme\\(space\\.16\\)\\)\\]{width:calc(100% - 8rem)}.sm\\:w-auto{width:auto}.sm\\:w-full{width:100%}.sm\\:max-w-md{max-width:28rem}.sm\\:-translate-y-1\\/2{--tw-translate-y:-50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.sm\\:flex-col{flex-direction:column}.sm\\:justify-normal{justify-content:normal}.sm\\:space-x-0>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(0px*(1 - var(--tw-space-x-reverse)));margin-right:calc(0px*var(--tw-space-x-reverse))}.sm\\:space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(1rem*var(--tw-space-y-reverse));margin-top:calc(1rem*(1 - var(--tw-space-y-reverse)))}.sm\\:bg-fixed{background-attachment:fixed}.sm\\:bg-left-top{background-position:0 0}.sm\\:px-10{padding-left:2.5rem;padding-right:2.5rem}.sm\\:px-14{padding-left:3.5rem;padding-right:3.5rem}.sm\\:py-14{padding-bottom:3.5rem;padding-top:3.5rem}.sm\\:py-4{padding-bottom:1rem;padding-top:1rem}.sm\\:pt-16{padding-top:4rem}.sm\\:text-2xl{font-size:1.5rem;line-height:120%}.sm\\:text-base{font-size:1rem;line-height:120%}}@media (min-width:1280px){.md\\:min-w-\\[448px\\]{min-width:448px}.md\\:p-10{padding:2.5rem}.md\\:py-10{padding-bottom:2.5rem;padding-top:2.5rem}.md\\:pl-10{padding-left:2.5rem}.md\\:pl-20{padding-left:5rem}.md\\:pr-10{padding-right:2.5rem}.md\\:pr-20{padding-right:5rem}.md\\:text-3xl{font-size:2rem;line-height:120%}.md\\:text-base{font-size:1rem;line-height:120%}.md\\:text-sm{font-size:.875rem;line-height:120%}.md\\:text-xs{font-size:.75rem;line-height:135%}}@media (max-height:900px) and (min-width:640px){.short\\:static{position:static}.short\\:left-auto{left:auto}.short\\:top-auto{top:auto}.short\\:inline{display:inline}.short\\:hidden{display:none}.short\\:h-5{height:1.25rem}.short\\:min-h-\\[558px\\]{min-height:558px}.short\\:w-5{width:1.25rem}.short\\:flex-1{flex:1 1 0%}.short\\:translate-y-0{--tw-translate-y:0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.short\\:flex-row{flex-direction:row}.short\\:space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-left:calc(1rem*(1 - var(--tw-space-x-reverse)));margin-right:calc(1rem*var(--tw-space-x-reverse))}.short\\:space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(0px*var(--tw-space-y-reverse));margin-top:calc(0px*(1 - var(--tw-space-y-reverse)))}.short\\:px-0{padding-left:0;padding-right:0}.short\\:py-3{padding-bottom:.75rem;padding-top:.75rem}}.\\[\\&\\>\\*\\:last-child\\]\\:mb-0>:last-child{margin-bottom:0}.\\[\\&_h1\\]\\:mb-6 h1,.\\[\\&_h2\\]\\:mb-6 h2{margin-bottom:1.5rem}`;function rS(){if(typeof document<"u"){const t=document.createElement("style");t.innerHTML=Zp,t.setAttribute("data-authhero-tailwind",""),document.head.appendChild(t)}}const iS='var Ke={Stringify:1},b=(e,t)=>{const n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},We=/[&<>\'"]/,Ue=async(e,t)=>{let n="";t||=[];const r=await Promise.all(e);for(let a=r.length-1;n+=r[a],a--,!(a<0);a--){let i=r[a];typeof i=="object"&&t.push(...i.callbacks||[]);const s=i.isEscaped;if(i=await(typeof i=="object"?i.toString():i),typeof i=="object"&&t.push(...i.callbacks||[]),i.isEscaped??s)n+=i;else{const o=[n];A(i,o),n=o[0]}}return b(n,t)},A=(e,t)=>{const n=e.search(We);if(n===-1){t[0]+=e;return}let r,a,i=0;for(a=n;a<e.length;a++){switch(e.charCodeAt(a)){case 34:r="&quot;";break;case 39:r="&#39;";break;case 38:r="&amp;";break;case 60:r="&lt;";break;case 62:r="&gt;";break;default:continue}t[0]+=e.substring(i,a)+r,i=a+1}t[0]+=e.substring(i,a)},Ve=e=>{const t=e.callbacks;if(!t?.length)return e;const n=[e],r={};return t.forEach(a=>a({phase:Ke.Stringify,buffer:n,context:r})),n[0]},ee=Symbol("RENDERER"),G=Symbol("ERROR_HANDLER"),v=Symbol("STASH"),Ie=Symbol("INTERNAL"),Ze=Symbol("MEMO"),F=Symbol("PERMALINK"),fe=e=>(e[Ie]=!0,e),Te=e=>({value:t,children:n})=>{if(!n)return;const r={children:[{tag:fe(()=>{e.push(t)}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:fe(()=>{e.pop()}),props:{}});const a={tag:"",props:r,type:""};return a[G]=i=>{throw e.pop(),i},a},Le=e=>{const t=[e],n=Te(t);return n.values=t,n.Provider=n,C.push(n),n},C=[],Pe=e=>{const t=[e],n=(r=>{t.push(r.value);let a;try{a=r.children?(Array.isArray(r.children)?new $e("",{},r.children):r.children).toString():""}finally{t.pop()}return a instanceof Promise?a.then(i=>b(i,i.callbacks)):b(a)});return n.values=t,n.Provider=n,n[ee]=Te(t),C.push(n),n},T=e=>e.values.at(-1),x={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},Y={},_="data-precedence",M=e=>Array.isArray(e)?e:[e],ue=new WeakMap,de=(e,t,n,r)=>({buffer:a,context:i})=>{if(!a)return;const s=ue.get(i)||{};ue.set(i,s);const o=s[e]||=[];let u=!1;const l=x[e];if(l.length>0){e:for(const[,f]of o)for(const c of l)if((f?.[c]??null)===n?.[c]){u=!0;break e}}if(u?a[0]=a[0].replaceAll(t,""):l.length>0?o.push([t,n,r]):o.unshift([t,n,r]),a[0].indexOf("</head>")!==-1){let f;if(r===void 0)f=o.map(([c])=>c);else{const c=[];f=o.map(([d,,p])=>{let y=c.indexOf(p);return y===-1&&(c.push(p),y=c.length-1),[d,y]}).sort((d,p)=>d[1]-p[1]).map(([d])=>d)}f.forEach(c=>{a[0]=a[0].replaceAll(c,"")}),a[0]=a[0].replace(/(?=<\\/head>)/,f.join(""))}},D=(e,t,n)=>b(new w(e,n,M(t??[])).toString()),$=(e,t,n,r)=>{if("itemProp"in n)return D(e,t,n);let{precedence:a,blocking:i,...s}=n;a=r?a??"":void 0,r&&(s[_]=a);const o=new w(e,s,M(t||[])).toString();return o instanceof Promise?o.then(u=>b(o,[...u.callbacks||[],de(e,u,s,a)])):b(o,[de(e,o,s,a)])},ze=({children:e,...t})=>{const n=te();if(n){const r=T(n);if(r==="svg"||r==="head")return new w("title",t,M(e??[]))}return $("title",e,t,!1)},Je=({children:e,...t})=>{const n=te();return["src","async"].some(r=>!t[r])||n&&T(n)==="head"?D("script",e,t):$("script",e,t,!1)},Xe=({children:e,...t})=>["href","precedence"].every(n=>n in t)?(t["data-href"]=t.href,delete t.href,$("style",e,t,!0)):D("style",e,t),Ge=({children:e,...t})=>["onLoad","onError"].some(n=>n in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?D("link",e,t):$("link",e,t,"precedence"in t),Ye=({children:e,...t})=>{const n=te();return n&&T(n)==="head"?D("meta",e,t):$("meta",e,t,!1)},Ne=(e,{children:t,...n})=>new w(e,n,M(t??[])),Qe=e=>(typeof e.action=="function"&&(e.action=F in e.action?e.action[F]:void 0),Ne("form",e)),Me=(e,t)=>(typeof t.formAction=="function"&&(t.formAction=F in t.formAction?t.formAction[F]:void 0),Ne(e,t)),et=e=>Me("input",e),tt=e=>Me("button",e);const V=Object.freeze(Object.defineProperty({__proto__:null,button:tt,form:Qe,input:et,link:Ge,meta:Ye,script:Je,style:Xe,title:ze},Symbol.toStringTag,{value:"Module"}));var nt=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),q=e=>nt.get(e)||e,De=(e,t)=>{for(const[n,r]of Object.entries(e)){const a=n[0]==="-"||!/[A-Z]/.test(n)?n:n.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);t(a,r==null?null:typeof r=="number"?a.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)}},P=void 0,te=()=>P,rt=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,at=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],it=["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"],ne=(e,t)=>{for(let n=0,r=e.length;n<r;n++){const a=e[n];if(typeof a=="string")A(a,t);else{if(typeof a=="boolean"||a===null||a===void 0)continue;a instanceof w?a.toStringToBuffer(t):typeof a=="number"||a.isEscaped?t[0]+=a:a instanceof Promise?t.unshift("",a):ne(a,t)}}},w=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?Ve(b(e[0],e.callbacks)).toString():e[0]:Ue(e,e.callbacks)}toStringToBuffer(e){const t=this.tag,n=this.props;let{children:r}=this;e[0]+=`<${t}`;const a=P&&T(P)==="svg"?i=>rt(q(i)):i=>q(i);for(let[i,s]of Object.entries(n))if(i=a(i),i!=="children"){if(i==="style"&&typeof s=="object"){let o="";De(s,(u,l)=>{l!=null&&(o+=`${o?";":""}${u}:${l}`)}),e[0]+=\' style="\',A(o,e),e[0]+=\'"\'}else if(typeof s=="string")e[0]+=` ${i}="`,A(s,e),e[0]+=\'"\';else if(s!=null)if(typeof s=="number"||s.isEscaped)e[0]+=` ${i}="${s}"`;else if(typeof s=="boolean"&&it.includes(i))s&&(e[0]+=` ${i}=""`);else if(i==="dangerouslySetInnerHTML"){if(r.length>0)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");r=[b(s.__html)]}else if(s instanceof Promise)e[0]+=` ${i}="`,e.unshift(\'"\',s);else if(typeof s=="function"){if(!i.startsWith("on")&&i!=="ref")throw new Error(`Invalid prop \'${i}\' of type \'function\' supplied to \'${t}\'.`)}else e[0]+=` ${i}="`,A(s.toString(),e),e[0]+=\'"\'}if(at.includes(t)&&r.length===0){e[0]+="/>";return}e[0]+=">",ne(r,e),e[0]+=`</${t}>`}},Z=class extends w{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(C.length===0)e.unshift("",r);else{const a=C.map(i=>[i,i.values.at(-1)]);e.unshift("",r.then(i=>(i instanceof w&&(i.localContexts=a),i)))}else r instanceof w?r.toStringToBuffer(e):typeof r=="number"||r.isEscaped?(e[0]+=r,r.callbacks&&(e.callbacks||=[],e.callbacks.push(...r.callbacks))):A(r,e)}},$e=class extends w{toStringToBuffer(e){ne(this.children,e)}},ve=!1,z=(e,t,n)=>{if(!ve){for(const r in Y)V[r][ee]=Y[r];ve=!0}return typeof e=="function"?new Z(e,t,n):V[e]?new Z(V[e],t,n):e==="svg"||e==="head"?(P||=Pe(""),new w(e,t,[new Z(P,{value:e},n)])):new w(e,t,n)},st=({children:e})=>new $e("",{children:e},Array.isArray(e)?e:e?[e]:[]);function O(e,t,n){let r;if(!t||!("children"in t))r=z(e,t,[]);else{const a=t.children;r=Array.isArray(a)?z(e,t,a):z(e,t,[a])}return r.key=n,r}var N="_hp",ot={Change:"Input",DoubleClick:"DblClick"},lt={svg:"2000/svg",math:"1998/Math/MathML"},k=[],Q=new WeakMap,I=void 0,ct=()=>I,S=e=>"t"in e,J={onClick:["click",!1]},pe=e=>{if(!e.startsWith("on"))return;if(J[e])return J[e];const t=e.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(t){const[,n,r]=t;return J[e]=[(ot[n]||n).toLowerCase(),!!r]}},he=(e,t)=>I&&e instanceof SVGElement&&/[A-Z]/.test(t)&&(t in e.style||t.match(/^(?:o|pai|str|u|ve)/))?t.replace(/([A-Z])/g,"-$1").toLowerCase():t,ft=(e,t,n)=>{t||={};for(let r in t){const a=t[r];if(r!=="children"&&(!n||n[r]!==a)){r=q(r);const i=pe(r);if(i){if(n?.[r]!==a&&(n&&e.removeEventListener(i[0],n[r],i[1]),a!=null)){if(typeof a!="function")throw new Error(`Event handler for "${r}" is not a function`);e.addEventListener(i[0],a,i[1])}}else if(r==="dangerouslySetInnerHTML"&&a)e.innerHTML=a.__html;else if(r==="ref"){let s;typeof a=="function"?s=a(e)||(()=>a(null)):a&&"current"in a&&(a.current=e,s=()=>a.current=null),Q.set(e,s)}else if(r==="style"){const s=e.style;typeof a=="string"?s.cssText=a:(s.cssText="",a!=null&&De(a,s.setProperty.bind(s)))}else{if(r==="value"){const o=e.nodeName;if(o==="INPUT"||o==="TEXTAREA"||o==="SELECT"){if(e.value=a==null||a===!1?null:a,o==="TEXTAREA"){e.textContent=a;continue}else if(o==="SELECT"){e.selectedIndex===-1&&(e.selectedIndex=0);continue}}}else(r==="checked"&&e.nodeName==="INPUT"||r==="selected"&&e.nodeName==="OPTION")&&(e[r]=a);const s=he(e,r);a==null||a===!1?e.removeAttribute(s):a===!0?e.setAttribute(s,""):typeof a=="string"||typeof a=="number"?e.setAttribute(s,a):e.setAttribute(s,a.toString())}}}if(n)for(let r in n){const a=n[r];if(r!=="children"&&!(r in t)){r=q(r);const i=pe(r);i?e.removeEventListener(i[0],a,i[1]):r==="ref"?Q.get(e)?.():e.removeAttribute(he(e,r))}}},ut=(e,t)=>{t[v][0]=0,k.push([e,t]);const n=t.tag[ee]||t.tag,r=n.defaultProps?{...n.defaultProps,...t.props}:t.props;try{return[n.call(null,r)]}finally{k.pop()}},Re=(e,t,n,r,a)=>{e.vR?.length&&(r.push(...e.vR),delete e.vR),typeof e.tag=="function"&&e[v][1][ae]?.forEach(i=>a.push(i)),e.vC.forEach(i=>{if(S(i))n.push(i);else if(typeof i.tag=="function"||i.tag===""){i.c=t;const s=n.length;if(Re(i,t,n,r,a),i.s){for(let o=s;o<n.length;o++)n[o].s=!0;i.s=!1}}else n.push(i),i.vR?.length&&(r.push(...i.vR),delete i.vR)})},dt=e=>{for(;;e=e.tag===N||!e.vC||!e.pP?e.nN:e.vC[0]){if(!e)return null;if(e.tag!==N&&e.e)return e.e}},Oe=e=>{S(e)||(e[v]?.[1][ae]?.forEach(t=>t[2]?.()),Q.get(e.e)?.(),e.p===2&&e.vC?.forEach(t=>t.p=2),e.vC?.forEach(Oe)),e.p||(e.e?.remove(),delete e.e),typeof e.tag=="function"&&(L.delete(e),B.delete(e),delete e[v][3],e.a=!0)},re=(e,t,n)=>{e.c=t,xe(e,t,n)},ge=(e,t)=>{if(t){for(let n=0,r=e.length;n<r;n++)if(e[n]===t)return n}},me=Symbol(),xe=(e,t,n)=>{const r=[],a=[],i=[];Re(e,t,r,a,i),a.forEach(Oe);const s=n?void 0:t.childNodes;let o,u=null;if(n)o=-1;else if(!s.length)o=0;else{const l=ge(s,dt(e.nN));l!==void 0?(u=s[l],o=l):o=ge(s,r.find(f=>f.tag!==N&&f.e)?.e)??-1,o===-1&&(n=!0)}for(let l=0,f=r.length;l<f;l++,o++){const c=r[l];let d;if(c.s&&c.e)d=c.e,c.s=!1;else{const p=n||!c.e;S(c)?(c.e&&c.d&&(c.e.textContent=c.t),c.d=!1,d=c.e||=document.createTextNode(c.t)):(d=c.e||=c.n?document.createElementNS(c.n,c.tag):document.createElement(c.tag),ft(d,c.props,c.pP),xe(c,d,p))}c.tag===N?o--:n?d.parentNode||t.appendChild(d):s[o]!==d&&s[o-1]!==d&&(s[o+1]===d?t.appendChild(s[o]):t.insertBefore(d,u||s[o]||null))}if(e.pP&&delete e.pP,i.length){const l=[],f=[];i.forEach(([,c,,d,p])=>{c&&l.push(c),d&&f.push(d),p?.()}),l.forEach(c=>c()),f.length&&requestAnimationFrame(()=>{f.forEach(c=>c())})}},vt=(e,t)=>!!(e&&e.length===t.length&&e.every((n,r)=>n[1]===t[r][1])),B=new WeakMap,K=(e,t,n)=>{const r=!n&&t.pC;n&&(t.pC||=t.vC);let a;try{n||=typeof t.tag=="function"?ut(e,t):M(t.props.children),n[0]?.tag===""&&n[0][G]&&(a=n[0][G],e[5].push([e,a,t]));const i=r?[...t.pC]:t.vC?[...t.vC]:void 0,s=[];let o;for(let u=0;u<n.length;u++){Array.isArray(n[u])&&n.splice(u,1,...n[u].flat());let l=_e(n[u]);if(l){typeof l.tag=="function"&&!l.tag[Ie]&&(C.length>0&&(l[v][2]=C.map(c=>[c,c.values.at(-1)])),e[5]?.length&&(l[v][3]=e[5].at(-1)));let f;if(i&&i.length){const c=i.findIndex(S(l)?d=>S(d):l.key!==void 0?d=>d.key===l.key&&d.tag===l.tag:d=>d.tag===l.tag);c!==-1&&(f=i[c],i.splice(c,1))}if(f)if(S(l))f.t!==l.t&&(f.t=l.t,f.d=!0),l=f;else{const c=f.pP=f.props;if(f.props=l.props,f.f||=l.f||t.f,typeof l.tag=="function"){const d=f[v][2];f[v][2]=l[v][2]||[],f[v][3]=l[v][3],!f.f&&((f.o||f)===l.o||f.tag[Ze]?.(c,f.props))&&vt(d,f[v][2])&&(f.s=!0)}l=f}else if(!S(l)&&I){const c=T(I);c&&(l.n=c)}if(!S(l)&&!l.s&&(K(e,l),delete l.f),s.push(l),o&&!o.s&&!l.s)for(let c=o;c&&!S(c);c=c.vC?.at(-1))c.nN=l;o=l}}t.vR=r?[...t.vC,...i||[]]:i||[],t.vC=s,r&&delete t.pC}catch(i){if(t.f=!0,i===me){if(a)return;throw i}const[s,o,u]=t[v]?.[3]||[];if(o){const l=()=>H([0,!1,e[2]],u),f=B.get(u)||[];f.push(l),B.set(u,f);const c=o(i,()=>{const d=B.get(u);if(d){const p=d.indexOf(l);if(p!==-1)return d.splice(p,1),l()}});if(c){if(e[0]===1)e[1]=!0;else if(K(e,u,[c]),(o.length===1||e!==s)&&u.c){re(u,u.c,!1);return}throw me}}throw i}finally{a&&e[5].pop()}},_e=e=>{if(!(e==null||typeof e=="boolean")){if(typeof e=="string"||typeof e=="number")return{t:e.toString(),d:!0};if("vR"in e&&(e={tag:e.tag,props:e.props,key:e.key,f:e.f,type:e.tag,ref:e.props.ref,o:e.o||e}),typeof e.tag=="function")e[v]=[0,[]];else{const t=lt[e.tag];t&&(I||=Le(""),e.props.children=[{tag:I,props:{value:e.n=`http://www.w3.org/${t}`,children:e.props.children}}])}return e}},Be=(e,t,n)=>{e.c===t&&(e.c=n,e.vC.forEach(r=>Be(r,t,n)))},ye=(e,t)=>{t[v][2]?.forEach(([n,r])=>{n.values.push(r)});try{K(e,t,void 0)}catch{return}if(t.a){delete t.a;return}t[v][2]?.forEach(([n])=>{n.values.pop()}),(e[0]!==1||!e[1])&&re(t,t.c,!1)},L=new WeakMap,Ee=[],H=async(e,t)=>{e[5]||=[];const n=L.get(t);n&&n[0](void 0);let r;const a=new Promise(i=>r=i);if(L.set(t,[r,()=>{e[2]?e[2](e,t,i=>{ye(i,t)}).then(()=>r(t)):(ye(e,t),r(t))}]),Ee.length)Ee.at(-1).add(t);else{await Promise.resolve();const i=L.get(t);i&&(L.delete(t),i[1]())}return a},pt=(e,t)=>{const n=[];n[5]=[],n[4]=!0,K(n,e,void 0),n[4]=!1;const r=document.createDocumentFragment();re(e,r,!0),Be(e,r,t),t.replaceChildren(r)},ht=(e,t,n)=>({tag:N,props:{children:e},key:n,e:t,p:1}),gt=0,ae=1,mt=2,yt=3,X=new WeakMap,ie=(e,t)=>!e||!t||e.length!==t.length||t.some((n,r)=>n!==e[r]),Et=void 0,we=[],He=e=>{const t=()=>typeof e=="function"?e():e,n=k.at(-1);if(!n)return[t(),()=>{}];const[,r]=n,a=r[v][1][gt]||=[],i=r[v][0]++;return a[i]||=[t(),s=>{const o=Et,u=a[i];if(typeof s=="function"&&(s=s(u[0])),!Object.is(s,u[0]))if(u[0]=s,we.length){const[l,f]=we.at(-1);Promise.all([l===3?r:H([l,!1,o],r),f]).then(([c])=>{if(!c||!(l===2||l===3))return;const d=c.vC;requestAnimationFrame(()=>{setTimeout(()=>{d===c.vC&&H([l===3?1:0,!1,o],c)})})})}else H([0,!1,o],r)}]},wt=(e,t,n)=>{const r=k.at(-1);if(!r)return;const[,a]=r,i=a[v][1][ae]||=[],s=a[v][0]++,[o,,u]=i[s]||=[];if(ie(o,n)){u&&u();const l=()=>{f[e]=void 0,f[2]=t()},f=[n,void 0,void 0,void 0,void 0];f[e]=l,i[s]=f}},je=(e,t)=>wt(3,e,t),se=(e,t)=>{const n=k.at(-1);if(!n)return e;const[,r]=n,a=r[v][1][mt]||=[],i=r[v][0]++,s=a[i];return ie(s?.[1],t)?a[i]=[e,t]:e=a[i][0],e},St=e=>{const t=X.get(e);if(t){if(t.length===2)throw t[1];return t[0]}throw e.then(n=>X.set(e,[n]),n=>X.set(e,[void 0,n])),e},bt=(e,t)=>{const n=k.at(-1);if(!n)return e();const[,r]=n,a=r[v][1][yt]||=[],i=r[v][0]++,s=a[i];return ie(s?.[1],t)&&(a[i]=[e(),t]),a[i][0]},At=Le({pending:!1,data:null,method:null,action:null}),Se=new Set,Ct=e=>{Se.add(e),e.finally(()=>Se.delete(e))},oe=(e,t)=>bt(()=>n=>{let r;e&&(typeof e=="function"?r=e(n)||(()=>{e(null)}):e&&"current"in e&&(e.current=n,r=()=>{e.current=null}));const a=t(n);return()=>{a?.(),r?.()}},[e]),be=Object.create(null),Ae=Object.create(null),R=(e,t,n,r,a)=>{if(t?.itemProp)return{tag:e,props:t,type:e,ref:t.ref};const i=document.head;let{onLoad:s,onError:o,precedence:u,blocking:l,...f}=t,c=null,d=!1;const p=x[e];let y;if(p.length>0){const g=i.querySelectorAll(e);e:for(const m of g)for(const h of x[e])if(m.getAttribute(h)===t[h]){c=m;break e}if(!c){const m=p.reduce((h,E)=>t[E]===void 0?h:`${h}-${E}-${t[E]}`,e);d=!Ae[m],c=Ae[m]||=(()=>{const h=document.createElement(e);for(const E of p)t[E]!==void 0&&h.setAttribute(E,t[E]),t.rel&&h.setAttribute("rel",t.rel);return h})()}}else y=i.querySelectorAll(e);u=r?u??"":void 0,r&&(f[_]=u);const le=se(g=>{if(p.length>0){let m=!1;for(const h of i.querySelectorAll(e)){if(m&&h.getAttribute(_)!==u){i.insertBefore(g,h);return}h.getAttribute(_)===u&&(m=!0)}i.appendChild(g)}else if(y){let m=!1;for(const h of y)if(h===g){m=!0;break}m||i.insertBefore(g,i.contains(y[0])?y[0]:i.querySelector(e)),y=void 0}},[u]),ce=oe(t.ref,g=>{const m=p[0];if(n===2&&(g.innerHTML=""),(d||y)&&le(g),!o&&!s)return;let h=be[g.getAttribute(m)]||=new Promise((E,U)=>{g.addEventListener("load",E),g.addEventListener("error",U)});s&&(h=h.then(s)),o&&(h=h.catch(o)),h.catch(()=>{})});if(a&&l==="render"){const g=x[e][0];if(t[g]){const m=t[g],h=be[m]||=new Promise((E,U)=>{le(c),c.addEventListener("load",E),c.addEventListener("error",U)});St(h)}}const W={tag:e,type:e,props:{...f,ref:ce},ref:ce};return W.p=n,c&&(W.e=c),ht(W,i)},kt=e=>{const t=ct();return(t&&T(t))?.endsWith("svg")?{tag:"title",props:e,type:"title",ref:e.ref}:R("title",e,void 0,!1,!1)},It=e=>!e||["src","async"].some(t=>!e[t])?{tag:"script",props:e,type:"script",ref:e.ref}:R("script",e,1,!1,!0),Tt=e=>!e||!["href","precedence"].every(t=>t in e)?{tag:"style",props:e,type:"style",ref:e.ref}:(e["data-href"]=e.href,delete e.href,R("style",e,2,!0,!0)),Lt=e=>!e||["onLoad","onError"].some(t=>t in e)||e.rel==="stylesheet"&&(!("precedence"in e)||"disabled"in e)?{tag:"link",props:e,type:"link",ref:e.ref}:R("link",e,1,"precedence"in e,!0),Pt=e=>R("meta",e,void 0,!1,!1),Fe=Symbol(),Nt=e=>{const{action:t,...n}=e;typeof t!="function"&&(n.action=t);const[r,a]=He([null,!1]),i=se(async l=>{const f=l.isTrusted?t:l.detail[Fe];if(typeof f!="function")return;l.preventDefault();const c=new FormData(l.target);a([c,!0]);const d=f(c);d instanceof Promise&&(Ct(d),await d),a([null,!0])},[]),s=oe(e.ref,l=>(l.addEventListener("submit",i),()=>{l.removeEventListener("submit",i)})),[o,u]=r;return r[1]=!1,{tag:At,props:{value:{pending:o!==null,data:o,method:o?"post":null,action:o?t:null},children:{tag:"form",props:{...n,ref:s},type:"form",ref:s}},f:u}},qe=(e,{formAction:t,...n})=>{if(typeof t=="function"){const r=se(a=>{a.preventDefault(),a.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[Fe]:t}}))},[]);n.ref=oe(n.ref,a=>(a.addEventListener("click",r),()=>{a.removeEventListener("click",r)}))}return{tag:e,props:n,type:e,ref:n.ref}},Mt=e=>qe("input",e),Dt=e=>qe("button",e);Object.assign(Y,{title:kt,script:It,style:Tt,link:Lt,meta:Pt,form:Nt,input:Mt,button:Dt});Pe(null);new TextEncoder;var $t=(e,t={})=>{let n;return Object.keys(t).length>0&&console.warn("createRoot options are not supported yet"),{render(r){if(n===null)throw new Error("Cannot update an unmounted root");n?n(r):pt(_e({tag:()=>{const[a,i]=He(r);return n=i,a},props:{}}),e)},unmount(){n?.(null),n=null}}},Rt=(e,t,n={})=>{const r=$t(e,n);return r.render(t),r};function Ot(){return je(()=>{const e=document.querySelectorAll("form"),t=[];return e.forEach(n=>{const r=i=>{if(i.defaultPrevented)return;const s=i.submitter;s&&s.type==="submit"&&(s.classList.add("is-loading"),s.disabled=!0)};n.addEventListener("submit",r);const a=i=>{i.persisted&&n.querySelectorAll("button[type=submit]").forEach(o=>{o.classList.remove("is-loading"),o.disabled=!1})};window.addEventListener("pageshow",a),t.push(()=>{n.removeEventListener("submit",r),window.removeEventListener("pageshow",a)})}),()=>{t.forEach(n=>n())}},[]),null}function xt(){return je(()=>{const e=document.querySelectorAll("[data-password-toggle]"),t=[];return e.forEach(n=>{const r=n.querySelector("input[type=\'password\'], input[data-password-input]"),a=n.querySelector("[data-password-toggle-btn]"),i=a?.querySelector("[data-show-icon]"),s=a?.querySelector("[data-hide-icon]");if(!r||!a||!i||!s)return;const o=l=>{l?(r.type="text",r.setAttribute("data-password-input","text"),i.classList.add("hidden"),s.classList.remove("hidden")):(r.type="password",r.setAttribute("data-password-input","password"),s.classList.add("hidden"),i.classList.remove("hidden"))},u=l=>{l.preventDefault();const f=r.type==="password";o(f)};a.addEventListener("click",u),t.push(()=>{a.removeEventListener("click",u)})}),()=>{t.forEach(n=>n())}},[]),null}function _t(){return document.querySelectorAll("[data-input-otp-container]").forEach(t=>{const n=Array.from(t.querySelectorAll("[data-input-otp-slot]"));if(!n.length)return;const r=t.closest("form");let a=null;if(r&&n.length>0){const o=n[0]?.getAttribute("name");o&&(a=r.querySelector(`input[name="${o}"][type="hidden"]`),a||(a=document.createElement("input"),a.type="hidden",a.name=o,r.appendChild(a)),n.forEach(u=>u.removeAttribute("name")))}const i=()=>{if(a){const s=n.map(o=>o.value).join("");a.value=s,s.length===n.length&&r&&setTimeout(()=>{r.requestSubmit()},100)}};n.forEach((s,o)=>{s.addEventListener("input",u=>{const l=u.target;let f=l.value;f=f.replace(/[^0-9]/g,""),f.length>1&&(f=f.charAt(0)),l.value=f,f&&o<n.length-1&&n[o+1]?.focus(),i()}),s.addEventListener("paste",u=>{u.preventDefault();const f=(u.clipboardData?.getData("text")||"").replace(/[^0-9]/g,"");for(let d=0;d<Math.min(f.length,n.length-o);d++){const p=n[o+d],y=f.charAt(d);p&&y&&(p.value=y)}const c=n.findIndex((d,p)=>p>=o&&!d.value);c!==-1?n[c]?.focus():n[Math.min(o+f.length,n.length-1)]?.focus(),i()}),s.addEventListener("keydown",u=>{if(u.key==="Backspace"){const l=u.target;if(!l.value&&o>0){u.preventDefault();const f=n[o-1];f&&(f.value="",f.focus()),i()}else l.value&&setTimeout(()=>i(),0)}else u.key==="ArrowLeft"&&o>0?(u.preventDefault(),n[o-1]?.focus()):u.key==="ArrowRight"&&o<n.length-1&&(u.preventDefault(),n[o+1]?.focus())}),s.addEventListener("focus",()=>{s.select()})}),i()}),null}const j="authhero_incognito_mode",Bt="https://unpkg.com/detectincognitojs@1.6.2";async function Ht(){return window.detectIncognito?window.detectIncognito:new Promise((e,t)=>{const n=document.createElement("script");n.src=Bt,n.type="text/javascript",n.crossOrigin="anonymous",n.onload=()=>{let r=window.detectIncognito;!r&&window.__detectIncognito&&(r=window.__detectIncognito),!r&&window.module&&window.module.exports&&(r=window.module.exports),r&&typeof r=="function"?e(r):r&&r.detectIncognito?e(r.detectIncognito):typeof r=="object"&&r.default?e(r.default):t(new Error("detectIncognito not found after loading script"))},n.onerror=()=>{t(new Error("Failed to load detectincognitojs script"))},document.head.appendChild(n)})}function jt(){try{const e=sessionStorage.getItem(j);return e===null?void 0:e==="true"}catch{return}}async function Ft(){try{const e=sessionStorage.getItem(j);if(e!==null)return e==="true";const t=await Ht(),{isPrivate:n}=await t();return sessionStorage.setItem(j,n.toString()),n}catch{try{sessionStorage.setItem(j,"false")}catch{}return!1}}const qt=()=>{const e=jt();if(e!==void 0){e&&Ce();return}Ft().then(t=>{t&&Ce()}).catch(()=>{})};function Ce(){const e=document.getElementById("incognito-warning-container");e&&e.classList.remove("hidden")}qt();const ke=document.getElementById("client-root");ke&&Rt(ke,O(st,{children:[O(Ot,{}),O(xt,{}),O(_t,{})]}));\n',oS=t=>p("div",{className:"rich-text mb-6 prose prose-gray max-w-none [&>*:last-child]:mb-0 [&_h1]:mb-6 [&_h2]:mb-6",dangerouslySetInnerHTML:{__html:t.config.content}},t.id),sS=t=>p("div",{className:"flex items-center gap-2",children:[p("input",{type:"checkbox",name:t.id,required:!!t.required,className:"w-5 h-5 accent-[#4F2D7F] align-middle",id:t.id}),p("span",{className:"text-base leading-tight",children:p("span",{dangerouslySetInnerHTML:{__html:t.config.text}})})]},t.id),aS=t=>p("div",{className:"mb-4",children:p("input",{type:"text",name:t.id,placeholder:t.config?.placeholder||"",required:!!t.required,className:"w-full rounded-lg border bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 border-gray-100 dark:border-gray-500",id:t.id})},t.id);function cS(t){switch(t.type){case"RICH_TEXT":return oS(t);case"LEGAL":return sS(t);case"TEXT":return aS(t);default:return null}}const Ol=({theme:t,branding:e,client:n,formName:r,error:i,components:s})=>{const c=s?.find(d=>d.type==="LEGAL"&&d.required)?.id,l=s?.find(d=>d.type==="NEXT_BUTTON");return p(Se,{title:r,theme:t,branding:e,client:n,children:[i&&p("div",{className:"mb-4 text-red-500",children:i}),p("div",{className:"flex flex-1 flex-col justify-center",children:p("form",{className:"pt-2",method:"post",children:[c&&p("style",{dangerouslySetInnerHTML:{__html:`
@@ -120,8 +120,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
120
120
  }
121
121
  `})]})},I0=({error:t,theme:e,branding:n,state:r,user:i,className:s})=>{const a=e?.colors?.primary_button||n?.colors?.primary||"#0066cc",c=e?.colors?.primary_button_label||"#ffffff",l=e?.colors?.body_text||"#333333",d=e?.colors?.input_border||"#d1d5db",u=e?.colors?.widget_background||"#ffffff",f=e?.colors?.widget_border||"#e5e7eb",g=e?.borders?.widget_corner_radius||8,_=e?.borders?.button_border_radius||4,w=e?.borders?.show_widget_shadow??!0,k=e?.fonts?.title?.size||24,z=e?.fonts?.title?.bold??!0,N=e?.fonts?.body_text?.size||14,I={backgroundColor:u,borderColor:f,borderRadius:`${g}px`,boxShadow:w?"0 1px 3px 0 rgba(0, 0, 0, 0.1)":"none",color:l},S={fontSize:`${k}px`,fontWeight:z?"700":"400",color:e?.colors?.header||l},E={fontSize:`${N}px`,color:e?.colors?.input_labels_placeholders||"#6b7280"},P={backgroundColor:a,color:c,borderRadius:`${_}px`},G={backgroundColor:"transparent",color:l,borderColor:d,borderRadius:`${_}px`},Z={color:e?.colors?.links_focused_components||a,fontSize:`${N}px`},W={borderColor:d,borderRadius:`${_}px`,fontSize:`${N}px`,color:l},M=e?.widget?.logo_position||"center",ce=M==="left"?"text-left":M==="right"?"text-right":"text-center",le=e?.widget?.logo_url||n?.logo_url,fe=M!=="none"&&le;return p("div",{className:Q("flex flex-col gap-6 w-full max-w-sm",s),children:p(en,{style:I,className:"border",children:[p(tn,{children:[fe&&p("div",{className:Q("mb-4",ce),children:p(Rt,{theme:e,branding:n})}),p(nn,{style:S,children:y.t("impersonation","Impersonation")}),p(rn,{style:E,children:y.t("impersonation_description","You have permission to impersonate other users.")})]}),p(on,{children:p("div",{className:"space-y-4",children:[p("div",{className:"p-3 bg-gray-50 dark:bg-gray-800 rounded-md",children:[p("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1",children:[y.t("current_user","Current user"),":"]}),p("p",{className:"font-semibold",style:{fontSize:`${N}px`},children:i.email})]}),p("form",{method:"post",action:`/u/impersonate/continue?state=${encodeURIComponent(r)}`,children:p(Jt,{type:"submit",className:"w-full transition-colors hover:brightness-90",style:P,children:y.t("continue","Continue")})}),p("div",{className:"relative",children:[p("div",{className:"absolute inset-0 flex items-center","aria-hidden":"true",children:p("div",{className:"w-full border-t",style:{borderColor:f}})}),p("div",{className:"relative flex justify-center text-xs uppercase",children:p("span",{className:"px-2",style:{backgroundColor:u,...E},children:y.t("or","Or")})})]}),p("details",{className:"group",children:[p("summary",{className:"cursor-pointer select-none flex items-center justify-between p-3 rounded-md hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",style:Z,children:[p("span",{className:"font-medium",children:y.t("advanced_options","Advanced Options")}),p("svg",{className:"w-5 h-5 transition-transform group-open:rotate-90",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:p("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),p("div",{className:"mt-3 p-4 border rounded-md",style:{borderColor:f},children:p("form",{method:"post",action:`/u/impersonate/switch?state=${encodeURIComponent(r)}`,children:p("div",{className:"space-y-4",children:[p("div",{className:"space-y-2",children:[p(_t,{htmlFor:"user_id",style:E,children:y.t("user_id_to_impersonate","User ID to Impersonate")}),p(Pt,{type:"text",id:"user_id",name:"user_id",placeholder:y.t("enter_user_id","Enter user ID"),required:!0,style:W,className:"w-full"}),t&&p(Re,{children:t})]}),p(Jt,{type:"submit",variant:"outline",className:"w-full transition-colors border",style:G,children:y.t("impersonate_user","Impersonate User")})]})})})]})]})}),p(F1,{children:p("a",{href:`/u/login/identifier?state=${encodeURIComponent(r)}`,className:"text-sm hover:underline focus:outline-none focus:ring-2 focus:ring-offset-2 transition-colors w-full text-center",style:Z,children:y.t("go_back","Go back")})})]})})},dS=new o.OpenAPIHono().openapi(o.createRoute({tags:["impersonation"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Impersonation page"},400:{description:"Bad Request"}}}),async t=>{const{state:e}=t.req.valid("query"),{theme:n,branding:r,client:i,loginSession:s,useShadcn:a}=await he(t,e,!0);if(!s.session_id)throw new v(400,{message:"No session linked to login session"});const c=await t.env.data.sessions.get(i.tenant.id,s.session_id);if(!c)throw new v(400,{message:"Session not found"});const l=await t.env.data.users.get(i.tenant.id,c.user_id);if(!l)throw new v(400,{message:"User not found"});return(await t.env.data.userPermissions.list(i.tenant.id,l.user_id)).some(f=>f.permission_name==="users:impersonate")?a?t.html(p(we,{title:y.t("impersonation","Impersonation"),theme:n,branding:r,client:i,children:p(I0,{theme:n,branding:r,client:i,user:l,state:e})})):t.html(p(N0,{theme:n,branding:r,client:i,user:l,state:e})):t.html(p(wt,{theme:n,branding:r,client:i,state:e,pageTitle:"Access Denied",message:"You do not have permission to impersonate other users."}),403)}).openapi(o.createRoute({tags:["impersonation"],method:"post",path:"/continue",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{302:{description:"Redirect to continue authentication flow",headers:o.z.object({Location:o.z.string().url()})}}}),async t=>{const{state:e}=t.req.valid("query"),{client:n,loginSession:r}=await he(t,e,!0);if(!r.session_id)throw new v(400,{message:"No session linked to login session"});const i=await t.env.data.sessions.get(n.tenant.id,r.session_id);if(!i)throw new v(400,{message:"Session not found"});const s=await t.env.data.users.get(n.tenant.id,i.user_id);if(!s)throw new v(400,{message:"User not found"});if(!(await t.env.data.userPermissions.list(n.tenant.id,s.user_id)).some(l=>l.permission_name==="users:impersonate"))throw new v(403,{message:"Access denied: insufficient permissions"});return Gt(t,{client:n,authParams:r.authParams,loginSession:r,user:s,sessionId:i.id,skipHooks:!0})}).openapi(o.createRoute({tags:["impersonation"],method:"post",path:"/switch",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({user_id:o.z.string().min(1,"User ID is required")})}}}},responses:{302:{description:"Redirect to continue authentication flow as impersonated user",headers:o.z.object({Location:o.z.string().url()})},400:{description:"Bad Request - User not found or impersonation failed"}}}),async t=>{const{state:e}=t.req.valid("query"),{user_id:n}=t.req.valid("form"),{theme:r,branding:i,client:s,loginSession:a,useShadcn:c}=await he(t,e,!0);if(!a.session_id)throw new v(400,{message:"No session linked to login session"});const l=await t.env.data.sessions.get(s.tenant.id,a.session_id);if(!l)throw new v(400,{message:"Current session not found"});const d=await t.env.data.users.get(s.tenant.id,l.user_id);if(!d)throw new v(400,{message:"Current user not found"});if(!(await t.env.data.userPermissions.list(s.tenant.id,d.user_id)).some(_=>_.permission_name==="users:impersonate"))return t.html(p(wt,{theme:r,branding:i,client:s,state:e,pageTitle:"Access Denied",message:"You do not have permission to impersonate other users."}),403);const g=await t.env.data.users.get(s.tenant.id,n);return g?(await t.env.data.sessions.update(s.tenant.id,l.id,{user_id:g.user_id}),await ie(t,s.tenant.id,{type:te.SUCCESS_LOGIN,description:`${g.email||g.user_id} (impersonated by ${d.email||d.user_id})`,userId:g.user_id,connection:g.connection,strategy:g.connection,strategy_type:g.is_social?"social":"database"}),Gt(t,{client:s,authParams:a.authParams,loginSession:a,user:g,sessionId:l.id,skipHooks:!0,impersonatingUser:d})):c?t.html(p(we,{title:y.t("impersonation","Impersonation"),theme:r,branding:i,client:s,children:p(I0,{theme:r,branding:i,client:s,user:d,state:e,error:`User with ID "${n}" not found.`})}),400):t.html(p(N0,{theme:r,branding:i,client:s,user:d,state:e,error:`User with ID "${n}" not found.`}),400)});function uS(t){const e=new o.OpenAPIHono,n=t.dataAdapter.cache||ds({defaultTtlSeconds:0,maxEntries:100,cleanupIntervalMs:0}),r=t.dataAdapter.cache?300:0;e.onError((s,a)=>s instanceof vr?a.redirect(s.location,s.status):s instanceof v?a.text(s.message||"Error",s.status):a.text("Unexpected error",500)),e.get("/css/tailwind.css",async s=>{const a=Zp;return s.text(a,200,{"content-type":"text/css; charset=utf-8"})}),e.get("/js/client.js",async s=>s.text(iS,200,{"content-type":"application/javascript; charset=utf-8"})),e.use(async(s,a)=>{const c=qo(s,t.dataAdapter),l=Qc(c,{defaultTtl:r,cacheEntities:["tenants","connections","clients","legacyClients","customDomains","resourceServers","roles","organizations","userRoles","userPermissions","branding","themes","promptSettings","forms"],cache:n});return s.env.data=Xc(s,l),a()}).use(Yc).use(Zc);const i=e.route("/info",Qx).route("/check-account",Hx).route("/account",Gx).route("/account/change-email",Wx).route("/account/change-email-verify",Jx).route("/account/change-email-confirmation",Xx).route("/login/identifier",sx).route("/enter-code",Tx).route("/enter-password",Lx).route("/invalid-session",Yx).route("/pre-signup",Zx).route("/pre-signup-sent",nS).route("/reset-password",Dx).route("/forgot-password",qx).route("/validate-email",tS).route("/signup",Ux).route("/impersonate",dS).route("/forms",lS);return i.doc("/u/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Universal login"}}),i}var pS=Object.defineProperty,fS=(t,e,n)=>e in t?pS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Gr=(t,e,n)=>fS(t,typeof e!="symbol"?e+"":e,n);const Ve=o.z.object({"#text":o.z.string()}),hS=o.z.object({"#text":o.z.string(),"@_xmlns:saml":o.z.string().optional()}),gS=o.z.object({"samlp:AuthnRequest":o.z.object({"saml:Issuer":hS,"@_xmlns:samlp":o.z.string(),"@_xmlns:saml":o.z.string().optional(),"@_ForceAuthn":o.z.string().transform(t=>t.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(Ve)}))})),":@":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(Ve)}),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 mS=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()})}),_S=o.z.object({"ds:Transform":o.z.array(o.z.any()),":@":o.z.object({"@_Algorithm":o.z.string()})}),j0=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(_S)}),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(Ve)})])),":@":o.z.object({"@_URI":o.z.string().optional()}).optional()})]))}),o.z.object({"ds:SignatureValue":o.z.array(Ve)}),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(Ve)}),o.z.object({"ds:Exponent":o.z.array(Ve)})]))}))}),o.z.object({"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(Ve)}))}),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(Ve)}),o.z.object({"ds:Exponent":o.z.array(Ve)})]))})),"ds:X509Data":o.z.array(o.z.object({"ds:X509Certificate":o.z.array(Ve)}))})]))})])),":@":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(Ve)}),j0,o.z.object({"samlp:Status":o.z.array(o.z.object({"samlp:StatusCode":o.z.array(Ve),":@":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(Ve)}),j0,o.z.object({"saml:Subject":o.z.array(o.z.union([o.z.object({"saml:NameID":o.z.array(Ve),":@":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(Ve)}))})),":@":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(Ve)}))})),":@":o.z.object({"@_AuthnInstant":o.z.string(),"@_SessionIndex":o.z.string(),"@_SessionNotOnOrAfter":o.z.string()})}),o.z.object({"saml:AttributeStatement":o.z.array(mS)})])),":@":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 lw={},rl={};(function(t){const e=":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=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+e+"]["+n+"]*",i=new RegExp("^"+r+"$"),s=function(c,l){const d=[];let u=l.exec(c);for(;u;){const f=[];f.startIndex=l.lastIndex-u[0].length;const g=u.length;for(let _=0;_<g;_++)f.push(u[_]);d.push(f),u=l.exec(c)}return d},a=function(c){const l=i.exec(c);return!(l===null||typeof l>"u")};t.isExist=function(c){return typeof c<"u"},t.isEmptyObject=function(c){return Object.keys(c).length===0},t.merge=function(c,l,d){if(l){const u=Object.keys(l),f=u.length;for(let g=0;g<f;g++)d==="strict"?c[u[g]]=[l[u[g]]]:c[u[g]]=l[u[g]]}},t.getValue=function(c){return t.isExist(c)?c:""},t.isName=a,t.getAllMatches=s,t.nameRegexp=r})(rl);const Yp=rl,yS={allowBooleanAttributes:!1,unpairedTags:[]};lw.validate=function(t,e){e=Object.assign({},yS,e);const n=[];let r=!1,i=!1;t[0]==="\uFEFF"&&(t=t.substr(1));for(let s=0;s<t.length;s++)if(t[s]==="<"&&t[s+1]==="?"){if(s+=2,s=O0(t,s),s.err)return s}else if(t[s]==="<"){let a=s;if(s++,t[s]==="!"){s=T0(t,s);continue}else{let c=!1;t[s]==="/"&&(c=!0,s++);let l="";for(;s<t.length&&t[s]!==">"&&t[s]!==" "&&t[s]!==" "&&t[s]!==`
122
122
  `&&t[s]!=="\r";s++)l+=t[s];if(l=l.trim(),l[l.length-1]==="/"&&(l=l.substring(0,l.length-1),s--),!zS(l)){let f;return l.trim().length===0?f="Invalid space after '<'.":f="Tag '"+l+"' is an invalid name.",Ee("InvalidTag",f,Xe(t,s))}const d=vS(t,s);if(d===!1)return Ee("InvalidAttr","Attributes for '"+l+"' have open quote.",Xe(t,s));let u=d.value;if(s=d.index,u[u.length-1]==="/"){const f=s-u.length;u=u.substring(0,u.length-1);const g=R0(u,e);if(g===!0)r=!0;else return Ee(g.err.code,g.err.msg,Xe(t,f+g.err.line))}else if(c)if(d.tagClosed){if(u.trim().length>0)return Ee("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",Xe(t,a));if(n.length===0)return Ee("InvalidTag","Closing tag '"+l+"' has not been opened.",Xe(t,a));{const f=n.pop();if(l!==f.tagName){let g=Xe(t,f.tagStartPos);return Ee("InvalidTag","Expected closing tag '"+f.tagName+"' (opened in line "+g.line+", col "+g.col+") instead of closing tag '"+l+"'.",Xe(t,a))}n.length==0&&(i=!0)}}else return Ee("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",Xe(t,s));else{const f=R0(u,e);if(f!==!0)return Ee(f.err.code,f.err.msg,Xe(t,s-u.length+f.err.line));if(i===!0)return Ee("InvalidXml","Multiple possible root nodes found.",Xe(t,s));e.unpairedTags.indexOf(l)!==-1||n.push({tagName:l,tagStartPos:a}),r=!0}for(s++;s<t.length;s++)if(t[s]==="<")if(t[s+1]==="!"){s++,s=T0(t,s);continue}else if(t[s+1]==="?"){if(s=O0(t,++s),s.err)return s}else break;else if(t[s]==="&"){const f=xS(t,s);if(f==-1)return Ee("InvalidChar","char '&' is not expected.",Xe(t,s));s=f}else if(i===!0&&!P0(t[s]))return Ee("InvalidXml","Extra text at the end",Xe(t,s));t[s]==="<"&&s--}}else{if(P0(t[s]))continue;return Ee("InvalidChar","char '"+t[s]+"' is not expected.",Xe(t,s))}if(r){if(n.length==1)return Ee("InvalidTag","Unclosed tag '"+n[0].tagName+"'.",Xe(t,n[0].tagStartPos));if(n.length>0)return Ee("InvalidXml","Invalid '"+JSON.stringify(n.map(s=>s.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return Ee("InvalidXml","Start tag expected.",1);return!0};function P0(t){return t===" "||t===" "||t===`
123
- `||t==="\r"}function O0(t,e){const n=e;for(;e<t.length;e++)if(t[e]=="?"||t[e]==" "){const r=t.substr(n,e-n);if(e>5&&r==="xml")return Ee("InvalidXml","XML declaration allowed only at the start of the document.",Xe(t,e));if(t[e]=="?"&&t[e+1]==">"){e++;break}else continue}return e}function T0(t,e){if(t.length>e+5&&t[e+1]==="-"&&t[e+2]==="-"){for(e+=3;e<t.length;e++)if(t[e]==="-"&&t[e+1]==="-"&&t[e+2]===">"){e+=2;break}}else if(t.length>e+8&&t[e+1]==="D"&&t[e+2]==="O"&&t[e+3]==="C"&&t[e+4]==="T"&&t[e+5]==="Y"&&t[e+6]==="P"&&t[e+7]==="E"){let n=1;for(e+=8;e<t.length;e++)if(t[e]==="<")n++;else if(t[e]===">"&&(n--,n===0))break}else if(t.length>e+9&&t[e+1]==="["&&t[e+2]==="C"&&t[e+3]==="D"&&t[e+4]==="A"&&t[e+5]==="T"&&t[e+6]==="A"&&t[e+7]==="["){for(e+=8;e<t.length;e++)if(t[e]==="]"&&t[e+1]==="]"&&t[e+2]===">"){e+=2;break}}return e}const wS='"',bS="'";function vS(t,e){let n="",r="",i=!1;for(;e<t.length;e++){if(t[e]===wS||t[e]===bS)r===""?r=t[e]:r!==t[e]||(r="");else if(t[e]===">"&&r===""){i=!0;break}n+=t[e]}return r!==""?!1:{value:n,index:e,tagClosed:i}}const $S=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function R0(t,e){const n=Yp.getAllMatches(t,$S),r={};for(let i=0;i<n.length;i++){if(n[i][1].length===0)return Ee("InvalidAttr","Attribute '"+n[i][2]+"' has no space in starting.",Oi(n[i]));if(n[i][3]!==void 0&&n[i][4]===void 0)return Ee("InvalidAttr","Attribute '"+n[i][2]+"' is without value.",Oi(n[i]));if(n[i][3]===void 0&&!e.allowBooleanAttributes)return Ee("InvalidAttr","boolean attribute '"+n[i][2]+"' is not allowed.",Oi(n[i]));const s=n[i][2];if(!SS(s))return Ee("InvalidAttr","Attribute '"+s+"' is an invalid name.",Oi(n[i]));if(!r.hasOwnProperty(s))r[s]=1;else return Ee("InvalidAttr","Attribute '"+s+"' is repeated.",Oi(n[i]))}return!0}function kS(t,e){let n=/\d/;for(t[e]==="x"&&(e++,n=/[\da-fA-F]/);e<t.length;e++){if(t[e]===";")return e;if(!t[e].match(n))break}return-1}function xS(t,e){if(e++,t[e]===";")return-1;if(t[e]==="#")return e++,kS(t,e);let n=0;for(;e<t.length;e++,n++)if(!(t[e].match(/\w/)&&n<20)){if(t[e]===";")break;return-1}return e}function Ee(t,e,n){return{err:{code:t,msg:e,line:n.line||n,col:n.col}}}function SS(t){return Yp.isName(t)}function zS(t){return Yp.isName(t)}function Xe(t,e){const n=t.substring(0,e).split(/\r?\n/);return{line:n.length,col:n[n.length-1].length+1}}function Oi(t){return t.startIndex+t[1].length}var Qp={};const dw={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,n){return t}},AS=function(t){return Object.assign({},dw,t)};Qp.buildOptions=AS;Qp.defaultOptions=dw;class ES{constructor(e){this.tagname=e,this.child=[],this[":@"]={}}add(e,n){e==="__proto__"&&(e="#__proto__"),this.child.push({[e]:n})}addChild(e){e.tagname==="__proto__"&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child})}}var CS=ES;const NS=rl;function IS(t,e){const n={};if(t[e+3]==="O"&&t[e+4]==="C"&&t[e+5]==="T"&&t[e+6]==="Y"&&t[e+7]==="P"&&t[e+8]==="E"){e=e+9;let r=1,i=!1,s=!1,a="";for(;e<t.length;e++)if(t[e]==="<"&&!s){if(i&&OS(t,e)){e+=7;let c,l;[c,l,e]=jS(t,e+1),l.indexOf("&")===-1&&(n[LS(c)]={regx:RegExp(`&${c};`,"g"),val:l})}else if(i&&TS(t,e))e+=8;else if(i&&RS(t,e))e+=8;else if(i&&BS(t,e))e+=9;else if(PS)s=!0;else throw new Error("Invalid DOCTYPE");r++,a=""}else if(t[e]===">"){if(s?t[e-1]==="-"&&t[e-2]==="-"&&(s=!1,r--):r--,r===0)break}else t[e]==="["?i=!0:a+=t[e];if(r!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:n,i:e}}function jS(t,e){let n="";for(;e<t.length&&t[e]!=="'"&&t[e]!=='"';e++)n+=t[e];if(n=n.trim(),n.indexOf(" ")!==-1)throw new Error("External entites are not supported");const r=t[e++];let i="";for(;e<t.length&&t[e]!==r;e++)i+=t[e];return[n,i,e]}function PS(t,e){return t[e+1]==="!"&&t[e+2]==="-"&&t[e+3]==="-"}function OS(t,e){return t[e+1]==="!"&&t[e+2]==="E"&&t[e+3]==="N"&&t[e+4]==="T"&&t[e+5]==="I"&&t[e+6]==="T"&&t[e+7]==="Y"}function TS(t,e){return t[e+1]==="!"&&t[e+2]==="E"&&t[e+3]==="L"&&t[e+4]==="E"&&t[e+5]==="M"&&t[e+6]==="E"&&t[e+7]==="N"&&t[e+8]==="T"}function RS(t,e){return t[e+1]==="!"&&t[e+2]==="A"&&t[e+3]==="T"&&t[e+4]==="T"&&t[e+5]==="L"&&t[e+6]==="I"&&t[e+7]==="S"&&t[e+8]==="T"}function BS(t,e){return t[e+1]==="!"&&t[e+2]==="N"&&t[e+3]==="O"&&t[e+4]==="T"&&t[e+5]==="A"&&t[e+6]==="T"&&t[e+7]==="I"&&t[e+8]==="O"&&t[e+9]==="N"}function LS(t){if(NS.isName(t))return t;throw new Error(`Invalid entity name ${t}`)}var US=IS;const DS=/^[-+]?0x[a-fA-F0-9]+$/,MS=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,qS={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function FS(t,e={}){if(e=Object.assign({},qS,e),!t||typeof t!="string")return t;let n=t.trim();if(e.skipLike!==void 0&&e.skipLike.test(n))return t;if(t==="0")return 0;if(e.hex&&DS.test(n))return VS(n,16);if(n.search(/[eE]/)!==-1){const r=n.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/);if(r){if(e.leadingZeros)n=(r[1]||"")+r[3];else if(!(r[2]==="0"&&r[3][0]==="."))return t;return e.eNotation?Number(n):t}else return t}else{const r=MS.exec(n);if(r){const i=r[1],s=r[2];let a=HS(r[3]);if(!e.leadingZeros&&s.length>0&&i&&n[2]!=="."||!e.leadingZeros&&s.length>0&&!i&&n[1]!==".")return t;if(e.leadingZeros&&s===t)return 0;{const c=Number(n),l=""+c;return l.search(/[eE]/)!==-1?e.eNotation?c:t:n.indexOf(".")!==-1?l==="0"&&a===""||l===a||i&&l==="-"+a?c:t:s?a===l||i+a===l?c:t:n===l||n===i+l?c:t}}else return t}}function HS(t){return t&&t.indexOf(".")!==-1&&(t=t.replace(/0+$/,""),t==="."?t="0":t[0]==="."?t="0"+t:t[t.length-1]==="."&&(t=t.substr(0,t.length-1))),t}function VS(t,e){if(parseInt)return parseInt(t,e);if(Number.parseInt)return Number.parseInt(t,e);if(window&&window.parseInt)return window.parseInt(t,e);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}var KS=FS;function GS(t){return typeof t=="function"?t:Array.isArray(t)?e=>{for(const n of t)if(typeof n=="string"&&e===n||n instanceof RegExp&&n.test(e))return!0}:()=>!1}var uw=GS;const pw=rl,Ti=CS,WS=US,JS=KS,XS=uw;let ZS=class{constructor(t){this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,n)=>String.fromCharCode(Number.parseInt(n,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,n)=>String.fromCharCode(Number.parseInt(n,16))}},this.addExternalEntities=YS,this.parseXml=r9,this.parseTextData=QS,this.resolveNameSpace=e9,this.buildAttributesMap=n9,this.isItStopNode=a9,this.replaceEntitiesValue=o9,this.readStopNodeData=l9,this.saveTextToParentTag=s9,this.addChild=i9,this.ignoreAttributesFn=XS(this.options.ignoreAttributes)}};function YS(t){const e=Object.keys(t);for(let n=0;n<e.length;n++){const r=e[n];this.lastEntities[r]={regex:new RegExp("&"+r+";","g"),val:t[r]}}}function QS(t,e,n,r,i,s,a){if(t!==void 0&&(this.options.trimValues&&!r&&(t=t.trim()),t.length>0)){a||(t=this.replaceEntitiesValue(t));const c=this.options.tagValueProcessor(e,t,n,i,s);return c==null?t:typeof c!=typeof t||c!==t?c:this.options.trimValues?xu(t,this.options.parseTagValue,this.options.numberParseOptions):t.trim()===t?xu(t,this.options.parseTagValue,this.options.numberParseOptions):t}}function e9(t){if(this.options.removeNSPrefix){const e=t.split(":"),n=t.charAt(0)==="/"?"/":"";if(e[0]==="xmlns")return"";e.length===2&&(t=n+e[1])}return t}const t9=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function n9(t,e,n){if(this.options.ignoreAttributes!==!0&&typeof t=="string"){const r=pw.getAllMatches(t,t9),i=r.length,s={};for(let a=0;a<i;a++){const c=this.resolveNameSpace(r[a][1]);if(this.ignoreAttributesFn(c,e))continue;let l=r[a][4],d=this.options.attributeNamePrefix+c;if(c.length)if(this.options.transformAttributeName&&(d=this.options.transformAttributeName(d)),d==="__proto__"&&(d="#__proto__"),l!==void 0){this.options.trimValues&&(l=l.trim()),l=this.replaceEntitiesValue(l);const u=this.options.attributeValueProcessor(c,l,e);u==null?s[d]=l:typeof u!=typeof l||u!==l?s[d]=u:s[d]=xu(l,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(s[d]=!0)}if(!Object.keys(s).length)return;if(this.options.attributesGroupName){const a={};return a[this.options.attributesGroupName]=s,a}return s}}const r9=function(t){t=t.replace(/\r\n?/g,`
124
- `);const e=new Ti("!xml");let n=e,r="",i="";for(let s=0;s<t.length;s++)if(t[s]==="<")if(t[s+1]==="/"){const a=er(t,">",s,"Closing Tag is not closed.");let c=t.substring(s+2,a).trim();if(this.options.removeNSPrefix){const u=c.indexOf(":");u!==-1&&(c=c.substr(u+1))}this.options.transformTagName&&(c=this.options.transformTagName(c)),n&&(r=this.saveTextToParentTag(r,n,i));const l=i.substring(i.lastIndexOf(".")+1);if(c&&this.options.unpairedTags.indexOf(c)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${c}>`);let d=0;l&&this.options.unpairedTags.indexOf(l)!==-1?(d=i.lastIndexOf(".",i.lastIndexOf(".")-1),this.tagsNodeStack.pop()):d=i.lastIndexOf("."),i=i.substring(0,d),n=this.tagsNodeStack.pop(),r="",s=a}else if(t[s+1]==="?"){let a=ku(t,s,!1,"?>");if(!a)throw new Error("Pi Tag is not closed.");if(r=this.saveTextToParentTag(r,n,i),!(this.options.ignoreDeclaration&&a.tagName==="?xml"||this.options.ignorePiTags)){const c=new Ti(a.tagName);c.add(this.options.textNodeName,""),a.tagName!==a.tagExp&&a.attrExpPresent&&(c[":@"]=this.buildAttributesMap(a.tagExp,i,a.tagName)),this.addChild(n,c,i)}s=a.closeIndex+1}else if(t.substr(s+1,3)==="!--"){const a=er(t,"-->",s+4,"Comment is not closed.");if(this.options.commentPropName){const c=t.substring(s+4,a-2);r=this.saveTextToParentTag(r,n,i),n.add(this.options.commentPropName,[{[this.options.textNodeName]:c}])}s=a}else if(t.substr(s+1,2)==="!D"){const a=WS(t,s);this.docTypeEntities=a.entities,s=a.i}else if(t.substr(s+1,2)==="!["){const a=er(t,"]]>",s,"CDATA is not closed.")-2,c=t.substring(s+9,a);r=this.saveTextToParentTag(r,n,i);let l=this.parseTextData(c,n.tagname,i,!0,!1,!0,!0);l==null&&(l=""),this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:c}]):n.add(this.options.textNodeName,l),s=a+2}else{let a=ku(t,s,this.options.removeNSPrefix),c=a.tagName;const l=a.rawTagName;let d=a.tagExp,u=a.attrExpPresent,f=a.closeIndex;this.options.transformTagName&&(c=this.options.transformTagName(c)),n&&r&&n.tagname!=="!xml"&&(r=this.saveTextToParentTag(r,n,i,!1));const g=n;if(g&&this.options.unpairedTags.indexOf(g.tagname)!==-1&&(n=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf("."))),c!==e.tagname&&(i+=i?"."+c:c),this.isItStopNode(this.options.stopNodes,i,c)){let _="";if(d.length>0&&d.lastIndexOf("/")===d.length-1)c[c.length-1]==="/"?(c=c.substr(0,c.length-1),i=i.substr(0,i.length-1),d=c):d=d.substr(0,d.length-1),s=a.closeIndex;else if(this.options.unpairedTags.indexOf(c)!==-1)s=a.closeIndex;else{const k=this.readStopNodeData(t,l,f+1);if(!k)throw new Error(`Unexpected end of ${l}`);s=k.i,_=k.tagContent}const w=new Ti(c);c!==d&&u&&(w[":@"]=this.buildAttributesMap(d,i,c)),_&&(_=this.parseTextData(_,c,i,!0,u,!0,!0)),i=i.substr(0,i.lastIndexOf(".")),w.add(this.options.textNodeName,_),this.addChild(n,w,i)}else{if(d.length>0&&d.lastIndexOf("/")===d.length-1){c[c.length-1]==="/"?(c=c.substr(0,c.length-1),i=i.substr(0,i.length-1),d=c):d=d.substr(0,d.length-1),this.options.transformTagName&&(c=this.options.transformTagName(c));const _=new Ti(c);c!==d&&u&&(_[":@"]=this.buildAttributesMap(d,i,c)),this.addChild(n,_,i),i=i.substr(0,i.lastIndexOf("."))}else{const _=new Ti(c);this.tagsNodeStack.push(n),c!==d&&u&&(_[":@"]=this.buildAttributesMap(d,i,c)),this.addChild(n,_,i),n=_}r="",s=f}}else r+=t[s];return e.child};function i9(t,e,n){const r=this.options.updateTag(e.tagname,n,e[":@"]);r===!1||(typeof r=="string"&&(e.tagname=r),t.addChild(e))}const o9=function(t){if(this.options.processEntities){for(let e in this.docTypeEntities){const n=this.docTypeEntities[e];t=t.replace(n.regx,n.val)}for(let e in this.lastEntities){const n=this.lastEntities[e];t=t.replace(n.regex,n.val)}if(this.options.htmlEntities)for(let e in this.htmlEntities){const n=this.htmlEntities[e];t=t.replace(n.regex,n.val)}t=t.replace(this.ampEntity.regex,this.ampEntity.val)}return t};function s9(t,e,n,r){return t&&(r===void 0&&(r=e.child.length===0),t=this.parseTextData(t,e.tagname,n,!1,e[":@"]?Object.keys(e[":@"]).length!==0:!1,r),t!==void 0&&t!==""&&e.add(this.options.textNodeName,t),t=""),t}function a9(t,e,n){const r="*."+n;for(const i in t){const s=t[i];if(r===s||e===s)return!0}return!1}function c9(t,e,n=">"){let r,i="";for(let s=e;s<t.length;s++){let a=t[s];if(r)a===r&&(r="");else if(a==='"'||a==="'")r=a;else if(a===n[0])if(n[1]){if(t[s+1]===n[1])return{data:i,index:s}}else return{data:i,index:s};else a===" "&&(a=" ");i+=a}}function er(t,e,n,r){const i=t.indexOf(e,n);if(i===-1)throw new Error(r);return i+e.length-1}function ku(t,e,n,r=">"){const i=c9(t,e+1,r);if(!i)return;let s=i.data;const a=i.index,c=s.search(/\s/);let l=s,d=!0;c!==-1&&(l=s.substring(0,c),s=s.substring(c+1).trimStart());const u=l;if(n){const f=l.indexOf(":");f!==-1&&(l=l.substr(f+1),d=l!==i.data.substr(f+1))}return{tagName:l,tagExp:s,closeIndex:a,attrExpPresent:d,rawTagName:u}}function l9(t,e,n){const r=n;let i=1;for(;n<t.length;n++)if(t[n]==="<")if(t[n+1]==="/"){const s=er(t,">",n,`${e} is not closed`);if(t.substring(n+2,s).trim()===e&&(i--,i===0))return{tagContent:t.substring(r,n),i:s};n=s}else if(t[n+1]==="?")n=er(t,"?>",n+1,"StopNode is not closed.");else if(t.substr(n+1,3)==="!--")n=er(t,"-->",n+3,"StopNode is not closed.");else if(t.substr(n+1,2)==="![")n=er(t,"]]>",n,"StopNode is not closed.")-2;else{const s=ku(t,n,">");s&&((s&&s.tagName)===e&&s.tagExp[s.tagExp.length-1]!=="/"&&i++,n=s.closeIndex)}}function xu(t,e,n){if(e&&typeof t=="string"){const r=t.trim();return r==="true"?!0:r==="false"?!1:JS(t,n)}else return pw.isExist(t)?t:""}var d9=ZS,fw={};function u9(t,e){return hw(t,e)}function hw(t,e,n){let r;const i={};for(let s=0;s<t.length;s++){const a=t[s],c=p9(a);let l="";if(n===void 0?l=c:l=n+"."+c,c===e.textNodeName)r===void 0?r=a[c]:r+=""+a[c];else{if(c===void 0)continue;if(a[c]){let d=hw(a[c],e,l);const u=h9(d,e);a[":@"]?f9(d,a[":@"],l,e):Object.keys(d).length===1&&d[e.textNodeName]!==void 0&&!e.alwaysCreateTextNode?d=d[e.textNodeName]:Object.keys(d).length===0&&(e.alwaysCreateTextNode?d[e.textNodeName]="":d=""),i[c]!==void 0&&i.hasOwnProperty(c)?(Array.isArray(i[c])||(i[c]=[i[c]]),i[c].push(d)):e.isArray(c,l,u)?i[c]=[d]:i[c]=d}}}return typeof r=="string"?r.length>0&&(i[e.textNodeName]=r):r!==void 0&&(i[e.textNodeName]=r),i}function p9(t){const e=Object.keys(t);for(let n=0;n<e.length;n++){const r=e[n];if(r!==":@")return r}}function f9(t,e,n,r){if(e){const i=Object.keys(e),s=i.length;for(let a=0;a<s;a++){const c=i[a];r.isArray(c,n+"."+c,!0,!0)?t[c]=[e[c]]:t[c]=e[c]}}}function h9(t,e){const{textNodeName:n}=e,r=Object.keys(t).length;return!!(r===0||r===1&&(t[n]||typeof t[n]=="boolean"||t[n]===0))}fw.prettify=u9;const{buildOptions:g9}=Qp,m9=d9,{prettify:_9}=fw,y9=lw;let w9=class{constructor(t){this.externalEntities={},this.options=g9(t)}parse(t,e){if(typeof t!="string")if(t.toString)t=t.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(e){e===!0&&(e={});const i=y9.validate(t,e);if(i!==!0)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}const n=new m9(this.options);n.addExternalEntities(this.externalEntities);const r=n.parseXml(t);return this.options.preserveOrder||r===void 0?r:_9(r,this.options)}addEntity(t,e){if(e.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(t.indexOf("&")!==-1||t.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(e==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}};var b9=w9;const v9=`
123
+ `||t==="\r"}function O0(t,e){const n=e;for(;e<t.length;e++)if(t[e]=="?"||t[e]==" "){const r=t.substr(n,e-n);if(e>5&&r==="xml")return Ee("InvalidXml","XML declaration allowed only at the start of the document.",Xe(t,e));if(t[e]=="?"&&t[e+1]==">"){e++;break}else continue}return e}function T0(t,e){if(t.length>e+5&&t[e+1]==="-"&&t[e+2]==="-"){for(e+=3;e<t.length;e++)if(t[e]==="-"&&t[e+1]==="-"&&t[e+2]===">"){e+=2;break}}else if(t.length>e+8&&t[e+1]==="D"&&t[e+2]==="O"&&t[e+3]==="C"&&t[e+4]==="T"&&t[e+5]==="Y"&&t[e+6]==="P"&&t[e+7]==="E"){let n=1;for(e+=8;e<t.length;e++)if(t[e]==="<")n++;else if(t[e]===">"&&(n--,n===0))break}else if(t.length>e+9&&t[e+1]==="["&&t[e+2]==="C"&&t[e+3]==="D"&&t[e+4]==="A"&&t[e+5]==="T"&&t[e+6]==="A"&&t[e+7]==="["){for(e+=8;e<t.length;e++)if(t[e]==="]"&&t[e+1]==="]"&&t[e+2]===">"){e+=2;break}}return e}const wS='"',bS="'";function vS(t,e){let n="",r="",i=!1;for(;e<t.length;e++){if(t[e]===wS||t[e]===bS)r===""?r=t[e]:r!==t[e]||(r="");else if(t[e]===">"&&r===""){i=!0;break}n+=t[e]}return r!==""?!1:{value:n,index:e,tagClosed:i}}const $S=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function R0(t,e){const n=Yp.getAllMatches(t,$S),r={};for(let i=0;i<n.length;i++){if(n[i][1].length===0)return Ee("InvalidAttr","Attribute '"+n[i][2]+"' has no space in starting.",Ti(n[i]));if(n[i][3]!==void 0&&n[i][4]===void 0)return Ee("InvalidAttr","Attribute '"+n[i][2]+"' is without value.",Ti(n[i]));if(n[i][3]===void 0&&!e.allowBooleanAttributes)return Ee("InvalidAttr","boolean attribute '"+n[i][2]+"' is not allowed.",Ti(n[i]));const s=n[i][2];if(!SS(s))return Ee("InvalidAttr","Attribute '"+s+"' is an invalid name.",Ti(n[i]));if(!r.hasOwnProperty(s))r[s]=1;else return Ee("InvalidAttr","Attribute '"+s+"' is repeated.",Ti(n[i]))}return!0}function kS(t,e){let n=/\d/;for(t[e]==="x"&&(e++,n=/[\da-fA-F]/);e<t.length;e++){if(t[e]===";")return e;if(!t[e].match(n))break}return-1}function xS(t,e){if(e++,t[e]===";")return-1;if(t[e]==="#")return e++,kS(t,e);let n=0;for(;e<t.length;e++,n++)if(!(t[e].match(/\w/)&&n<20)){if(t[e]===";")break;return-1}return e}function Ee(t,e,n){return{err:{code:t,msg:e,line:n.line||n,col:n.col}}}function SS(t){return Yp.isName(t)}function zS(t){return Yp.isName(t)}function Xe(t,e){const n=t.substring(0,e).split(/\r?\n/);return{line:n.length,col:n[n.length-1].length+1}}function Ti(t){return t.startIndex+t[1].length}var Qp={};const dw={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,n){return t}},AS=function(t){return Object.assign({},dw,t)};Qp.buildOptions=AS;Qp.defaultOptions=dw;class ES{constructor(e){this.tagname=e,this.child=[],this[":@"]={}}add(e,n){e==="__proto__"&&(e="#__proto__"),this.child.push({[e]:n})}addChild(e){e.tagname==="__proto__"&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child})}}var CS=ES;const NS=rl;function IS(t,e){const n={};if(t[e+3]==="O"&&t[e+4]==="C"&&t[e+5]==="T"&&t[e+6]==="Y"&&t[e+7]==="P"&&t[e+8]==="E"){e=e+9;let r=1,i=!1,s=!1,a="";for(;e<t.length;e++)if(t[e]==="<"&&!s){if(i&&OS(t,e)){e+=7;let c,l;[c,l,e]=jS(t,e+1),l.indexOf("&")===-1&&(n[LS(c)]={regx:RegExp(`&${c};`,"g"),val:l})}else if(i&&TS(t,e))e+=8;else if(i&&RS(t,e))e+=8;else if(i&&BS(t,e))e+=9;else if(PS)s=!0;else throw new Error("Invalid DOCTYPE");r++,a=""}else if(t[e]===">"){if(s?t[e-1]==="-"&&t[e-2]==="-"&&(s=!1,r--):r--,r===0)break}else t[e]==="["?i=!0:a+=t[e];if(r!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:n,i:e}}function jS(t,e){let n="";for(;e<t.length&&t[e]!=="'"&&t[e]!=='"';e++)n+=t[e];if(n=n.trim(),n.indexOf(" ")!==-1)throw new Error("External entites are not supported");const r=t[e++];let i="";for(;e<t.length&&t[e]!==r;e++)i+=t[e];return[n,i,e]}function PS(t,e){return t[e+1]==="!"&&t[e+2]==="-"&&t[e+3]==="-"}function OS(t,e){return t[e+1]==="!"&&t[e+2]==="E"&&t[e+3]==="N"&&t[e+4]==="T"&&t[e+5]==="I"&&t[e+6]==="T"&&t[e+7]==="Y"}function TS(t,e){return t[e+1]==="!"&&t[e+2]==="E"&&t[e+3]==="L"&&t[e+4]==="E"&&t[e+5]==="M"&&t[e+6]==="E"&&t[e+7]==="N"&&t[e+8]==="T"}function RS(t,e){return t[e+1]==="!"&&t[e+2]==="A"&&t[e+3]==="T"&&t[e+4]==="T"&&t[e+5]==="L"&&t[e+6]==="I"&&t[e+7]==="S"&&t[e+8]==="T"}function BS(t,e){return t[e+1]==="!"&&t[e+2]==="N"&&t[e+3]==="O"&&t[e+4]==="T"&&t[e+5]==="A"&&t[e+6]==="T"&&t[e+7]==="I"&&t[e+8]==="O"&&t[e+9]==="N"}function LS(t){if(NS.isName(t))return t;throw new Error(`Invalid entity name ${t}`)}var US=IS;const DS=/^[-+]?0x[a-fA-F0-9]+$/,MS=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,qS={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function FS(t,e={}){if(e=Object.assign({},qS,e),!t||typeof t!="string")return t;let n=t.trim();if(e.skipLike!==void 0&&e.skipLike.test(n))return t;if(t==="0")return 0;if(e.hex&&DS.test(n))return VS(n,16);if(n.search(/[eE]/)!==-1){const r=n.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/);if(r){if(e.leadingZeros)n=(r[1]||"")+r[3];else if(!(r[2]==="0"&&r[3][0]==="."))return t;return e.eNotation?Number(n):t}else return t}else{const r=MS.exec(n);if(r){const i=r[1],s=r[2];let a=HS(r[3]);if(!e.leadingZeros&&s.length>0&&i&&n[2]!=="."||!e.leadingZeros&&s.length>0&&!i&&n[1]!==".")return t;if(e.leadingZeros&&s===t)return 0;{const c=Number(n),l=""+c;return l.search(/[eE]/)!==-1?e.eNotation?c:t:n.indexOf(".")!==-1?l==="0"&&a===""||l===a||i&&l==="-"+a?c:t:s?a===l||i+a===l?c:t:n===l||n===i+l?c:t}}else return t}}function HS(t){return t&&t.indexOf(".")!==-1&&(t=t.replace(/0+$/,""),t==="."?t="0":t[0]==="."?t="0"+t:t[t.length-1]==="."&&(t=t.substr(0,t.length-1))),t}function VS(t,e){if(parseInt)return parseInt(t,e);if(Number.parseInt)return Number.parseInt(t,e);if(window&&window.parseInt)return window.parseInt(t,e);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}var KS=FS;function GS(t){return typeof t=="function"?t:Array.isArray(t)?e=>{for(const n of t)if(typeof n=="string"&&e===n||n instanceof RegExp&&n.test(e))return!0}:()=>!1}var uw=GS;const pw=rl,Ri=CS,WS=US,JS=KS,XS=uw;let ZS=class{constructor(t){this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,n)=>String.fromCharCode(Number.parseInt(n,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,n)=>String.fromCharCode(Number.parseInt(n,16))}},this.addExternalEntities=YS,this.parseXml=r9,this.parseTextData=QS,this.resolveNameSpace=e9,this.buildAttributesMap=n9,this.isItStopNode=a9,this.replaceEntitiesValue=o9,this.readStopNodeData=l9,this.saveTextToParentTag=s9,this.addChild=i9,this.ignoreAttributesFn=XS(this.options.ignoreAttributes)}};function YS(t){const e=Object.keys(t);for(let n=0;n<e.length;n++){const r=e[n];this.lastEntities[r]={regex:new RegExp("&"+r+";","g"),val:t[r]}}}function QS(t,e,n,r,i,s,a){if(t!==void 0&&(this.options.trimValues&&!r&&(t=t.trim()),t.length>0)){a||(t=this.replaceEntitiesValue(t));const c=this.options.tagValueProcessor(e,t,n,i,s);return c==null?t:typeof c!=typeof t||c!==t?c:this.options.trimValues?xu(t,this.options.parseTagValue,this.options.numberParseOptions):t.trim()===t?xu(t,this.options.parseTagValue,this.options.numberParseOptions):t}}function e9(t){if(this.options.removeNSPrefix){const e=t.split(":"),n=t.charAt(0)==="/"?"/":"";if(e[0]==="xmlns")return"";e.length===2&&(t=n+e[1])}return t}const t9=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function n9(t,e,n){if(this.options.ignoreAttributes!==!0&&typeof t=="string"){const r=pw.getAllMatches(t,t9),i=r.length,s={};for(let a=0;a<i;a++){const c=this.resolveNameSpace(r[a][1]);if(this.ignoreAttributesFn(c,e))continue;let l=r[a][4],d=this.options.attributeNamePrefix+c;if(c.length)if(this.options.transformAttributeName&&(d=this.options.transformAttributeName(d)),d==="__proto__"&&(d="#__proto__"),l!==void 0){this.options.trimValues&&(l=l.trim()),l=this.replaceEntitiesValue(l);const u=this.options.attributeValueProcessor(c,l,e);u==null?s[d]=l:typeof u!=typeof l||u!==l?s[d]=u:s[d]=xu(l,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(s[d]=!0)}if(!Object.keys(s).length)return;if(this.options.attributesGroupName){const a={};return a[this.options.attributesGroupName]=s,a}return s}}const r9=function(t){t=t.replace(/\r\n?/g,`
124
+ `);const e=new Ri("!xml");let n=e,r="",i="";for(let s=0;s<t.length;s++)if(t[s]==="<")if(t[s+1]==="/"){const a=er(t,">",s,"Closing Tag is not closed.");let c=t.substring(s+2,a).trim();if(this.options.removeNSPrefix){const u=c.indexOf(":");u!==-1&&(c=c.substr(u+1))}this.options.transformTagName&&(c=this.options.transformTagName(c)),n&&(r=this.saveTextToParentTag(r,n,i));const l=i.substring(i.lastIndexOf(".")+1);if(c&&this.options.unpairedTags.indexOf(c)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${c}>`);let d=0;l&&this.options.unpairedTags.indexOf(l)!==-1?(d=i.lastIndexOf(".",i.lastIndexOf(".")-1),this.tagsNodeStack.pop()):d=i.lastIndexOf("."),i=i.substring(0,d),n=this.tagsNodeStack.pop(),r="",s=a}else if(t[s+1]==="?"){let a=ku(t,s,!1,"?>");if(!a)throw new Error("Pi Tag is not closed.");if(r=this.saveTextToParentTag(r,n,i),!(this.options.ignoreDeclaration&&a.tagName==="?xml"||this.options.ignorePiTags)){const c=new Ri(a.tagName);c.add(this.options.textNodeName,""),a.tagName!==a.tagExp&&a.attrExpPresent&&(c[":@"]=this.buildAttributesMap(a.tagExp,i,a.tagName)),this.addChild(n,c,i)}s=a.closeIndex+1}else if(t.substr(s+1,3)==="!--"){const a=er(t,"-->",s+4,"Comment is not closed.");if(this.options.commentPropName){const c=t.substring(s+4,a-2);r=this.saveTextToParentTag(r,n,i),n.add(this.options.commentPropName,[{[this.options.textNodeName]:c}])}s=a}else if(t.substr(s+1,2)==="!D"){const a=WS(t,s);this.docTypeEntities=a.entities,s=a.i}else if(t.substr(s+1,2)==="!["){const a=er(t,"]]>",s,"CDATA is not closed.")-2,c=t.substring(s+9,a);r=this.saveTextToParentTag(r,n,i);let l=this.parseTextData(c,n.tagname,i,!0,!1,!0,!0);l==null&&(l=""),this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:c}]):n.add(this.options.textNodeName,l),s=a+2}else{let a=ku(t,s,this.options.removeNSPrefix),c=a.tagName;const l=a.rawTagName;let d=a.tagExp,u=a.attrExpPresent,f=a.closeIndex;this.options.transformTagName&&(c=this.options.transformTagName(c)),n&&r&&n.tagname!=="!xml"&&(r=this.saveTextToParentTag(r,n,i,!1));const g=n;if(g&&this.options.unpairedTags.indexOf(g.tagname)!==-1&&(n=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf("."))),c!==e.tagname&&(i+=i?"."+c:c),this.isItStopNode(this.options.stopNodes,i,c)){let _="";if(d.length>0&&d.lastIndexOf("/")===d.length-1)c[c.length-1]==="/"?(c=c.substr(0,c.length-1),i=i.substr(0,i.length-1),d=c):d=d.substr(0,d.length-1),s=a.closeIndex;else if(this.options.unpairedTags.indexOf(c)!==-1)s=a.closeIndex;else{const k=this.readStopNodeData(t,l,f+1);if(!k)throw new Error(`Unexpected end of ${l}`);s=k.i,_=k.tagContent}const w=new Ri(c);c!==d&&u&&(w[":@"]=this.buildAttributesMap(d,i,c)),_&&(_=this.parseTextData(_,c,i,!0,u,!0,!0)),i=i.substr(0,i.lastIndexOf(".")),w.add(this.options.textNodeName,_),this.addChild(n,w,i)}else{if(d.length>0&&d.lastIndexOf("/")===d.length-1){c[c.length-1]==="/"?(c=c.substr(0,c.length-1),i=i.substr(0,i.length-1),d=c):d=d.substr(0,d.length-1),this.options.transformTagName&&(c=this.options.transformTagName(c));const _=new Ri(c);c!==d&&u&&(_[":@"]=this.buildAttributesMap(d,i,c)),this.addChild(n,_,i),i=i.substr(0,i.lastIndexOf("."))}else{const _=new Ri(c);this.tagsNodeStack.push(n),c!==d&&u&&(_[":@"]=this.buildAttributesMap(d,i,c)),this.addChild(n,_,i),n=_}r="",s=f}}else r+=t[s];return e.child};function i9(t,e,n){const r=this.options.updateTag(e.tagname,n,e[":@"]);r===!1||(typeof r=="string"&&(e.tagname=r),t.addChild(e))}const o9=function(t){if(this.options.processEntities){for(let e in this.docTypeEntities){const n=this.docTypeEntities[e];t=t.replace(n.regx,n.val)}for(let e in this.lastEntities){const n=this.lastEntities[e];t=t.replace(n.regex,n.val)}if(this.options.htmlEntities)for(let e in this.htmlEntities){const n=this.htmlEntities[e];t=t.replace(n.regex,n.val)}t=t.replace(this.ampEntity.regex,this.ampEntity.val)}return t};function s9(t,e,n,r){return t&&(r===void 0&&(r=e.child.length===0),t=this.parseTextData(t,e.tagname,n,!1,e[":@"]?Object.keys(e[":@"]).length!==0:!1,r),t!==void 0&&t!==""&&e.add(this.options.textNodeName,t),t=""),t}function a9(t,e,n){const r="*."+n;for(const i in t){const s=t[i];if(r===s||e===s)return!0}return!1}function c9(t,e,n=">"){let r,i="";for(let s=e;s<t.length;s++){let a=t[s];if(r)a===r&&(r="");else if(a==='"'||a==="'")r=a;else if(a===n[0])if(n[1]){if(t[s+1]===n[1])return{data:i,index:s}}else return{data:i,index:s};else a===" "&&(a=" ");i+=a}}function er(t,e,n,r){const i=t.indexOf(e,n);if(i===-1)throw new Error(r);return i+e.length-1}function ku(t,e,n,r=">"){const i=c9(t,e+1,r);if(!i)return;let s=i.data;const a=i.index,c=s.search(/\s/);let l=s,d=!0;c!==-1&&(l=s.substring(0,c),s=s.substring(c+1).trimStart());const u=l;if(n){const f=l.indexOf(":");f!==-1&&(l=l.substr(f+1),d=l!==i.data.substr(f+1))}return{tagName:l,tagExp:s,closeIndex:a,attrExpPresent:d,rawTagName:u}}function l9(t,e,n){const r=n;let i=1;for(;n<t.length;n++)if(t[n]==="<")if(t[n+1]==="/"){const s=er(t,">",n,`${e} is not closed`);if(t.substring(n+2,s).trim()===e&&(i--,i===0))return{tagContent:t.substring(r,n),i:s};n=s}else if(t[n+1]==="?")n=er(t,"?>",n+1,"StopNode is not closed.");else if(t.substr(n+1,3)==="!--")n=er(t,"-->",n+3,"StopNode is not closed.");else if(t.substr(n+1,2)==="![")n=er(t,"]]>",n,"StopNode is not closed.")-2;else{const s=ku(t,n,">");s&&((s&&s.tagName)===e&&s.tagExp[s.tagExp.length-1]!=="/"&&i++,n=s.closeIndex)}}function xu(t,e,n){if(e&&typeof t=="string"){const r=t.trim();return r==="true"?!0:r==="false"?!1:JS(t,n)}else return pw.isExist(t)?t:""}var d9=ZS,fw={};function u9(t,e){return hw(t,e)}function hw(t,e,n){let r;const i={};for(let s=0;s<t.length;s++){const a=t[s],c=p9(a);let l="";if(n===void 0?l=c:l=n+"."+c,c===e.textNodeName)r===void 0?r=a[c]:r+=""+a[c];else{if(c===void 0)continue;if(a[c]){let d=hw(a[c],e,l);const u=h9(d,e);a[":@"]?f9(d,a[":@"],l,e):Object.keys(d).length===1&&d[e.textNodeName]!==void 0&&!e.alwaysCreateTextNode?d=d[e.textNodeName]:Object.keys(d).length===0&&(e.alwaysCreateTextNode?d[e.textNodeName]="":d=""),i[c]!==void 0&&i.hasOwnProperty(c)?(Array.isArray(i[c])||(i[c]=[i[c]]),i[c].push(d)):e.isArray(c,l,u)?i[c]=[d]:i[c]=d}}}return typeof r=="string"?r.length>0&&(i[e.textNodeName]=r):r!==void 0&&(i[e.textNodeName]=r),i}function p9(t){const e=Object.keys(t);for(let n=0;n<e.length;n++){const r=e[n];if(r!==":@")return r}}function f9(t,e,n,r){if(e){const i=Object.keys(e),s=i.length;for(let a=0;a<s;a++){const c=i[a];r.isArray(c,n+"."+c,!0,!0)?t[c]=[e[c]]:t[c]=e[c]}}}function h9(t,e){const{textNodeName:n}=e,r=Object.keys(t).length;return!!(r===0||r===1&&(t[n]||typeof t[n]=="boolean"||t[n]===0))}fw.prettify=u9;const{buildOptions:g9}=Qp,m9=d9,{prettify:_9}=fw,y9=lw;let w9=class{constructor(t){this.externalEntities={},this.options=g9(t)}parse(t,e){if(typeof t!="string")if(t.toString)t=t.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(e){e===!0&&(e={});const i=y9.validate(t,e);if(i!==!0)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}const n=new m9(this.options);n.addExternalEntities(this.externalEntities);const r=n.parseXml(t);return this.options.preserveOrder||r===void 0?r:_9(r,this.options)}addEntity(t,e){if(e.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(t.indexOf("&")!==-1||t.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(e==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}};var b9=w9;const v9=`
125
125
  `;function $9(t,e){let n="";return e.format&&e.indentBy.length>0&&(n=v9),gw(t,e,"",n)}function gw(t,e,n,r){let i="",s=!1;for(let a=0;a<t.length;a++){const c=t[a],l=k9(c);if(l===void 0)continue;let d="";if(n.length===0?d=l:d=`${n}.${l}`,l===e.textNodeName){let w=c[l];x9(d,e)||(w=e.tagValueProcessor(l,w),w=mw(w,e)),s&&(i+=r),i+=w,s=!1;continue}else if(l===e.cdataPropName){s&&(i+=r),i+=`<![CDATA[${c[l][0][e.textNodeName]}]]>`,s=!1;continue}else if(l===e.commentPropName){i+=r+`<!--${c[l][0][e.textNodeName]}-->`,s=!0;continue}else if(l[0]==="?"){const w=B0(c[":@"],e),k=l==="?xml"?"":r;let z=c[l][0][e.textNodeName];z=z.length!==0?" "+z:"",i+=k+`<${l}${z}${w}?>`,s=!0;continue}let u=r;u!==""&&(u+=e.indentBy);const f=B0(c[":@"],e),g=r+`<${l}${f}`,_=gw(c[l],e,d,u);e.unpairedTags.indexOf(l)!==-1?e.suppressUnpairedNode?i+=g+">":i+=g+"/>":(!_||_.length===0)&&e.suppressEmptyNode?i+=g+"/>":_&&_.endsWith(">")?i+=g+`>${_}${r}</${l}>`:(i+=g+">",_&&r!==""&&(_.includes("/>")||_.includes("</"))?i+=r+e.indentBy+_+r:i+=_,i+=`</${l}>`),s=!0}return i}function k9(t){const e=Object.keys(t);for(let n=0;n<e.length;n++){const r=e[n];if(t.hasOwnProperty(r)&&r!==":@")return r}}function B0(t,e){let n="";if(t&&!e.ignoreAttributes)for(let r in t){if(!t.hasOwnProperty(r))continue;let i=e.attributeValueProcessor(r,t[r]);i=mw(i,e),i===!0&&e.suppressBooleanAttributes?n+=` ${r.substr(e.attributeNamePrefix.length)}`:n+=` ${r.substr(e.attributeNamePrefix.length)}="${i}"`}return n}function x9(t,e){t=t.substr(0,t.length-e.textNodeName.length-1);let n=t.substr(t.lastIndexOf(".")+1);for(let r in e.stopNodes)if(e.stopNodes[r]===t||e.stopNodes[r]==="*."+n)return!0;return!1}function mw(t,e){if(t&&t.length>0&&e.processEntities)for(let n=0;n<e.entities.length;n++){const r=e.entities[n];t=t.replace(r.regex,r.val)}return t}var S9=$9;const z9=S9,A9=uw,E9={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function Fn(t){this.options=Object.assign({},E9,t),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=A9(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=I9),this.processTextOrObjNode=C9,this.options.format?(this.indentate=N9,this.tagEndChar=`>
126
126
  `,this.newLine=`
127
127
  `):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}Fn.prototype.build=function(t){return this.options.preserveOrder?z9(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0,[]).val)};Fn.prototype.j2x=function(t,e,n){let r="",i="";const s=n.join(".");for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a))if(typeof t[a]>"u")this.isAttribute(a)&&(i+="");else if(t[a]===null)this.isAttribute(a)||a===this.options.cdataPropName?i+="":a[0]==="?"?i+=this.indentate(e)+"<"+a+"?"+this.tagEndChar:i+=this.indentate(e)+"<"+a+"/"+this.tagEndChar;else if(t[a]instanceof Date)i+=this.buildTextValNode(t[a],a,"",e);else if(typeof t[a]!="object"){const c=this.isAttribute(a);if(c&&!this.ignoreAttributesFn(c,s))r+=this.buildAttrPairStr(c,""+t[a]);else if(!c)if(a===this.options.textNodeName){let l=this.options.tagValueProcessor(a,""+t[a]);i+=this.replaceEntitiesValue(l)}else i+=this.buildTextValNode(t[a],a,"",e)}else if(Array.isArray(t[a])){const c=t[a].length;let l="",d="";for(let u=0;u<c;u++){const f=t[a][u];if(!(typeof f>"u"))if(f===null)a[0]==="?"?i+=this.indentate(e)+"<"+a+"?"+this.tagEndChar:i+=this.indentate(e)+"<"+a+"/"+this.tagEndChar;else if(typeof f=="object")if(this.options.oneListGroup){const g=this.j2x(f,e+1,n.concat(a));l+=g.val,this.options.attributesGroupName&&f.hasOwnProperty(this.options.attributesGroupName)&&(d+=g.attrStr)}else l+=this.processTextOrObjNode(f,a,e,n);else if(this.options.oneListGroup){let g=this.options.tagValueProcessor(a,f);g=this.replaceEntitiesValue(g),l+=g}else l+=this.buildTextValNode(f,a,"",e)}this.options.oneListGroup&&(l=this.buildObjectNode(l,a,d,e)),i+=l}else if(this.options.attributesGroupName&&a===this.options.attributesGroupName){const c=Object.keys(t[a]),l=c.length;for(let d=0;d<l;d++)r+=this.buildAttrPairStr(c[d],""+t[a][c[d]])}else i+=this.processTextOrObjNode(t[a],a,e,n);return{attrStr:r,val:i}};Fn.prototype.buildAttrPairStr=function(t,e){return e=this.options.attributeValueProcessor(t,""+e),e=this.replaceEntitiesValue(e),this.options.suppressBooleanAttributes&&e==="true"?" "+t:" "+t+'="'+e+'"'};function C9(t,e,n,r){const i=this.j2x(t,n+1,r.concat(e));return t[this.options.textNodeName]!==void 0&&Object.keys(t).length===1?this.buildTextValNode(t[this.options.textNodeName],e,i.attrStr,n):this.buildObjectNode(i.val,e,i.attrStr,n)}Fn.prototype.buildObjectNode=function(t,e,n,r){if(t==="")return e[0]==="?"?this.indentate(r)+"<"+e+n+"?"+this.tagEndChar:this.indentate(r)+"<"+e+n+this.closeTag(e)+this.tagEndChar;{let i="</"+e+this.tagEndChar,s="";return e[0]==="?"&&(s="?",i=""),(n||n==="")&&t.indexOf("<")===-1?this.indentate(r)+"<"+e+n+s+">"+t+i:this.options.commentPropName!==!1&&e===this.options.commentPropName&&s.length===0?this.indentate(r)+`<!--${t}-->`+this.newLine:this.indentate(r)+"<"+e+n+s+this.tagEndChar+t+this.indentate(r)+i}};Fn.prototype.closeTag=function(t){let e="";return this.options.unpairedTags.indexOf(t)!==-1?this.options.suppressUnpairedNode||(e="/"):this.options.suppressEmptyNode?e="/":e=`></${t}`,e};Fn.prototype.buildTextValNode=function(t,e,n,r){if(this.options.cdataPropName!==!1&&e===this.options.cdataPropName)return this.indentate(r)+`<![CDATA[${t}]]>`+this.newLine;if(this.options.commentPropName!==!1&&e===this.options.commentPropName)return this.indentate(r)+`<!--${t}-->`+this.newLine;if(e[0]==="?")return this.indentate(r)+"<"+e+n+"?"+this.tagEndChar;{let i=this.options.tagValueProcessor(e,t);return i=this.replaceEntitiesValue(i),i===""?this.indentate(r)+"<"+e+n+this.closeTag(e)+this.tagEndChar:this.indentate(r)+"<"+e+n+">"+i+"</"+e+this.tagEndChar}};Fn.prototype.replaceEntitiesValue=function(t){if(t&&t.length>0&&this.options.processEntities)for(let e=0;e<this.options.entities.length;e++){const n=this.options.entities[e];t=t.replace(n.regex,n.val)}return t};function N9(t){return this.options.indentBy.repeat(t)}function I9(t){return t.startsWith(this.options.attributeNamePrefix)&&t!==this.options.textNodeName?t.substr(this.attrPrefixLen):!1}var j9=Fn;const P9=b9,O9=j9;var _w={XMLParser:P9,XMLBuilder:O9};class yw{constructor(e,n){if(Gr(this,"alphabet"),Gr(this,"padding"),Gr(this,"decodeMap",new Map),e.length!==32)throw new Error("Invalid alphabet");if(this.alphabet=e,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<e.length;r++)this.decodeMap.set(e[r],r)}encode(e,n){let r="",i=0,s=0;for(let a=0;a<e.length;a++)for(i=i<<8|e[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(e,n){const r=n?.strict??!0,i=Math.ceil(e.length/8),s=[];for(let a=0;a<i;a++){let c=0;const l=[];for(let u=0;u<8;u++){const f=e[a*8+u];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 g=this.decodeMap.get(f)??null;if(g===null)throw new Error(`Invalid character: ${f}`);l.push(g)}if(c===8||c===7||c===5||c===2)throw new Error("Invalid padding");const d=(l[0]<<3)+(l[1]>>2);if(s.push(d),c<6){const u=((l[1]&3)<<6)+(l[2]<<1)+(l[3]>>4);s.push(u)}if(c<4){const u=((l[3]&255)<<4)+(l[4]>>1);s.push(u)}if(c<3){const u=((l[4]&1)<<7)+(l[5]<<2)+(l[6]>>3);s.push(u)}if(c<1){const u=((l[6]&7)<<5)+l[7];s.push(u)}}return Uint8Array.from(s)}}new yw("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");new yw("0123456789ABCDEFGHIJKLMNOPQRSTUV");class ww{constructor(e,n){if(Gr(this,"alphabet"),Gr(this,"padding"),Gr(this,"decodeMap",new Map),e.length!==64)throw new Error("Invalid alphabet");if(this.alphabet=e,this.padding=n?.padding??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<e.length;r++)this.decodeMap.set(e[r],r)}encode(e,n){let r="",i=0,s=0;for(let a=0;a<e.length;a++)for(i=i<<8|e[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(e,n){const r=n?.strict??!0,i=Math.ceil(e.length/4),s=[];for(let a=0;a<i;a++){let c=0,l=0;for(let d=0;d<4;d++){const u=e[a*4+d];if(u==="="){if(a+1!==i)throw new Error(`Invalid character: ${u}`);c+=1;continue}if(u===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const f=this.decodeMap.get(u)??null;if(f===null)throw new Error(`Invalid character: ${u}`);l+=f<<6*(3-d)}s.push(l>>16&255),c<2&&s.push(l>>8&255),c<1&&s.push(l&255)}return Uint8Array.from(s)}}const T9=new ww("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");new ww("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");async function R9(t){const e=new DecompressionStream("deflate-raw"),n=new Uint8Array(t),r=new Blob([n]).stream().pipeThrough(e);return new Uint8Array(await new Response(r).arrayBuffer())}async function B9(t){const e=await T9.decode(t.replace(/ /g,"+"));try{const n=await R9(e);return new TextDecoder().decode(n)}catch(n){return console.warn("Decompression failed, assuming data is not compressed:",n),new TextDecoder().decode(e)}}async function L9(t){const e=await B9(t),n=new _w.XMLParser({attributeNamePrefix:"@_",alwaysCreateTextNode:!0,ignoreAttributes:!1}).parse(e);return gS.parse(n)}function U9(t){const e=t.certificates.map(r=>({"@_use":"signing",KeyInfo:{"@_xmlns":"http://www.w3.org/2000/09/xmldsig#",X509Data:{X509Certificate:r}}})),n={EntityDescriptor:{"@_entityID":t.entityId,"@_xmlns":"urn:oasis:names:tc:SAML:2.0:metadata",IDPSSODescriptor:{"@_protocolSupportEnumeration":"urn:oasis:names:tc:SAML:2.0:protocol",KeyDescriptor:e,SingleLogoutService:[{"@_Binding":"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect","@_Location":t.singleLogoutServiceUrl},{"@_Binding":"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST","@_Location":t.singleLogoutServiceUrl}],NameIDFormat:["urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress","urn:oasis:names:tc:SAML:2.0:nameid-format:persistent","urn:oasis:names:tc:SAML:2.0:nameid-format:transient"],SingleSignOnService:[{"@_Binding":"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect","@_Location":t.assertionConsumerServiceUrl},{"@_Binding":"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST","@_Location":t.assertionConsumerServiceUrl}],Attribute:[{"@_Name":"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:uri","@_FriendlyName":"E-Mail Address","@_xmlns":"urn:oasis:names:tc:SAML:2.0:assertion"},{"@_Name":"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:uri","@_FriendlyName":"Given Name","@_xmlns":"urn:oasis:names:tc:SAML:2.0:assertion"},{"@_Name":"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:uri","@_FriendlyName":"Name","@_xmlns":"urn:oasis:names:tc:SAML:2.0:assertion"},{"@_Name":"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:uri","@_FriendlyName":"Surname","@_xmlns":"urn:oasis:names:tc:SAML:2.0:assertion"},{"@_Name":"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:uri","@_FriendlyName":"Name ID","@_xmlns":"urn:oasis:names:tc:SAML:2.0:assertion"}]}}};return new _w.XMLBuilder({ignoreAttributes:!1,suppressEmptyNode:!0,preserveOrder:!1,format:!0,attributeNamePrefix:"@_"}).build(n)}const D9=new o.OpenAPIHono().openapi(o.createRoute({tags:["saml"],method:"get",path:"/metadata/{client_id}",request:{params:o.z.object({client_id:o.z.string()})},responses:{200:{description:"Decoded SAML Request",content:{"text/xml":{schema:o.z.string()}}},400:{description:"Bad Request"}}}),async t=>{const{client_id:e}=t.req.valid("param"),n=await t.env.data.legacyClients.get(e);if(!n)throw new v(404,{message:"Client not found"});const{signingKeys:r}=await t.env.data.keys.list({q:"type:saml_encryption"});if(r.length===0)throw new v(500,{message:"No signing key found"});const i=r.map(c=>new Wc(c.cert).toString("base64")),s=t.env.ISSUER,a=U9({entityId:n.addons?.samlp?.audience||n.client_id,certificates:i,assertionConsumerServiceUrl:`${s}samlp/${e}`,singleLogoutServiceUrl:`${s}samlp/${e}/logout`});return new Response(a,{headers:{"Content-Type":"text/xml"}})}).openapi(o.createRoute({tags:["saml"],method:"get",path:"/{client_id}",request:{query:o.z.object({SAMLRequest:o.z.string(),RelayState:o.z.string().optional(),SigAlg:o.z.string().optional(),Signature:o.z.string().optional()}),params:o.z.object({client_id:o.z.string()})},responses:{200:{description:"Decoded SAML Request",content:{"text/xml":{schema:o.z.string()}}},400:{description:"Bad Request"}}}),async t=>{const{client_id:e}=t.req.valid("param"),{SAMLRequest:n,RelayState:r}=t.req.valid("query"),i=await t.env.data.legacyClients.get(e);if(!i)throw new v(404,{message:"Client not found"});t.set("client_id",i.client_id),t.set("tenant_id",i.tenant.id);const s=await L9(n),a=s["samlp:AuthnRequest"]["saml:Issuer"]["#text"],c=await t.env.data.loginSessions.create(t.var.tenant_id,{csrf_token:pe(),authParams:{client_id:e,state:JSON.stringify({requestId:s["samlp:AuthnRequest"]["@_ID"],relayState:r}),response_mode:Ct.SAML_POST,redirect_uri:s["samlp:AuthnRequest"]["@_AssertionConsumerServiceURL"],audience:a},expires_at:new Date(Date.now()+or*1e3).toISOString(),ip:t.get("ip"),useragent:t.get("useragent"),auth0Client:mn(t.get("auth0_client"))});return t.redirect(`/u/login/identifier?state=${c.id}`)});function M9(t){const e=new o.OpenAPIHono;e.use(async(r,i)=>{const s=qo(r,t.dataAdapter),a=t.dataAdapter.cache||ds({defaultTtlSeconds:0,maxEntries:100,cleanupIntervalMs:0}),c=t.dataAdapter.cache?300:0,l=Qc(s,{defaultTtl:c,cacheEntities:["tenants","connections","clients","branding","themes","promptSettings","forms"],cache:a});return r.env.data=Xc(r,l),i()}),e.use(Yc).use(Zc).use(Pp(e));const n=e.route("/",D9);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"SAML API"},security:[{oauth2:["openid","email","profile"]}]}),jp(n),n}const q9="Account detected",F9="Manage your account details",H9="Account",V9="We have detected that you have already created an account through",K9="By signing in, you agree to our",G9="and",W9="email address",J9="email or phone number",X9="phone number",Z9="Callback URL mismatch",Y9="The provided redirect_uri is not in the list of allowed callback URLs.",Q9="Change email address",ez="continue with user",tz="Please click the button to create a new password account.",nz="Enter the code at {{vendorName}} to complete the login",rz="Welcome to {{vendorName}}! {{code}} is the login code",iz="Welcome to {{vendorName}}! {{code}} is the login code",oz="Code expired",sz="Invalid code",az="Please check <0>{{username}}</0> and enter the six-digit code that we've sent you.",cz="The code is already used",lz="The code is valid for 30 minutes",dz="A configuration error occurred.",uz="Confirm password",pz="Are you sure you want to unlink this account?",fz="Need Help?",hz="Contact us",gz="or continue with social account",mz="Continue with {{provider}}",_z="Would you like to continue with your existing account?",yz="Copyright © 2023 SESAMY. All rights reserved.",wz="©2023 Sesamy",bz="Choose a password with a mix of uppercase and lowercase letters, numbers, and symbols.",vz="Please enter a valid email address.",$z="The passwords didn't match. Try again.",kz="Choose password",xz="Password must be at least 8 characters long and contain at least one lowercase letter, one uppercase letter, one number and one symbol.",Sz="Create new account",zz="Sign up with password",Az="Current email address",Ez="You are currently logged in as <0>{{email}}</0>",Cz="Edit",Nz="Email",Iz="Email is already taken",jz="Email changed to <0>{{email}}</0> ",Pz="Email or Phone Number",Oz="Email address",Tz="Your email address has been validated",Rz="Now enter your password to login again",Bz="An email has been sent to <0>{{email}}</0> with a verification link. Please click the link to verify your email address and set a password.",Lz="Email verification sent",Uz="Do you have to keep logging in?",Dz="You are currently inside the {{browserName}}. This browser often logs you out, so we recommend using your phone's default browser instead.",Mz="Enter a code",qz="We'll send you a verification link to ensure you own this email address.",Fz="Enter new email",Hz="Enter new password",Vz="Enter password",Kz="Enter your email address and password to login.",Gz="Enter your password",Wz="Something went wrong",Jz="The magic link has expired. Please click on the button below to receive a new link in your inbox.",Xz="Hey! We updated our login experience. <0>Click here to learn more about it.</0>",Zz="Send password reset email",Yz="Click the button below and we’ll send instructions on how to reset your password.",Qz="Password reset email sent",e7="Forgot password?",t7="Forgot password?",n7="Go back",r7="Hide password",i7="Incognito Mode Detected",o7="You are in incognito/private mode. Session data may not persist across page refreshes. Some features might not work as expected.",s7="Invalid identifier",a7="Invalid password",c7=`The link is no longer valid.
@@ -155,4 +155,4 @@ Varmista, että avaat kirjautumislinkin samalla selaimella, jolla aloitit kirjau
155
155
  Voit aloittaa uuden kirjautumisen klikkaamalla alla olevaa linkkiä.`,PH="Virheellinen linkki",OH="Linkitetyt tilit",TH="Kirjaudu sisään napsauttamalla painiketta",RH="Kirjaudu sisään",BH="Tai kirjoita koodi osoitteessa {{vendorName}} kirjautumisen loppuun saattamiseksi.",LH="Kirjoita sähköpostiosoitteesi avataksesi tämän ohjelman osoitteessa {{service}}",UH="Yhdistä tilisi {{service}}",DH="Olet kirjautunut sisään nimellä",MH="Kirjaudu sisään",qH="Kirjoita sähköpostiosoitteesi kirjautuaksesi sisään.",FH="Anna sähköpostiosoitteesi, niin lähetämme sinulle kirjautumiskoodin.",HH="Kirjoita sähköpostiosoitteesi tai puhelinnumerosi kirjautuaksesi sisään",VH="Anna sähköpostiosoitteesi, niin lähetämme sinulle kirjautumislinkin.",KH="Anna puhelinnumerosi kirjautuaksesi sisään",GH="Kirjoita {{authMethod}} kirjautuaksesi sisään.",WH="Kirjaudu ulos",JH="Uusi sähköpostiosoite",XH="Yksi kertainen koodi lähetetään uuteen sähköpostiosoitteeseesi, syötä koodi seuraavassa vaiheessa.",ZH="Ei sähköpostiosoitetta asetettu",YH="Ei, haluan käyttää toista tiliä",QH="tai",eV="Salasana",tV="Salasana sisältää kielletyn sanan",nV="Salasana ei saa sisältää henkilötietoja, kuten nimeäsi tai sähköpostiosoitettasi",rV="Salasana on nollattu",iV="Menestys",oV="Salasanan on sisällettävä vähintään yksi pieni kirjain",sV="Salasanan on sisällettävä vähintään yksi numero",aV="Salasanan on sisällettävä vähintään yksi erikoismerkki",cV="Salasanan on sisällettävä vähintään yksi iso kirjain",lV="Koodia ei löytynyt tai se on vanhentunut",dV="Salasanaa ei voitu nollata",uV="Salasanaa on käytetty äskettäin, eikä sitä voi käyttää uudelleen",pV="Salasanan on oltava vähintään {{minLength}} merkkiä",fV="Vaihda salasana tilillesi {{vendorName}} ",hV="Vaihda salasana tilillesi {{vendorName}} ",gV="Puhelinnumero",mV="Tietosuojakäytäntö",_V="Uudelleenohjaus",yV="Vahvista salasana",wV="Rekisteröi uusi salasana",bV="Lähetä koodi uudelleen",vV="Vaihda salasana",$V="Kirjoita alla oleva uusi salasanasi sähköpostitiliä varten: ",kV="Napsauta painiketta salasanasi palauttamiseksi",xV="Napsauta painiketta salasanasi palauttamiseksi",SV="Nollaa salasanasi",zV="Vaihda salasana tilillesi {{vendorName}} ",AV="Nollaa salasana",EV="Lähetä",CV="Lähetä minulle uusi maaginen linkki",NV="Muista tarkistaa roskapostikansiosi, jos sähköposti ei ole saapunut.",IV="Aseta salasana",jV="Näytä salasana",PV="Kirjaudu sisään",OV="Rekisteröityminen",TV="Rekisteröidy onnistuneesti",RV="{{code}} on kirjautumiskoodisi {{vendorName}}",BV="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.",LV="Siirry Spotifyn Content Access -sivulle",UV='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ä.',DV="Vaihe 1: Poista Spotify-tilisi linkitys",MV="Kun olet onnistuneesti irrottanut Spotify-tilisi, voit yhdistää sen uudelleen Sesamyn kanssa. Toista vain aiemmin tekemäsi vaiheet, jotka johtivat sinut tälle sivulle.",qV="Vaihe 2: Yhdistä Spotify-tilisi uudelleen Sesamyn kanssa",FV="Hups! Spotify-tilisi on jo linkitetty",HV="Valmis",VV="Jos sinulla on kysyttävää tai tarvitset apua, voit ottaa yhteyttä tukitiimiimme.",KV="Ehdot ja edellytykset",GV="Jokin meni pieleen. Yritä uudelleen.",WV="Irrota",JV="Sähköpostiosoitteesi on vahvistettava. Olemme lähettäneet uuden sähköpostiviestin sähköpostiisi.",XV="Päivitä sähköposti",ZV="Käyttäjätiliä ei ole olemassa",YV="Käyttäjätiliä ei ole olemassa",QV="Emme löytäneet käyttäjää, jolla on annettu sähköpostiosoite. Yritä uudelleen.",eK="Yritä uudelleen.",tK="Validoi koodi",nK="Tarkista sähköpostin vahvistusohjeet postilaatikostasi.",rK="Rekisteröitynyt",iK="Vahvista sähköpostiosoitteesi napsauttamalla painiketta",oK="Vahvista sähköpostiosoitteesi",sK="Vahvista sähköpostiosoitteesi",aK="Vahvista tili",cK="Vahvista sähköpostiosoitteesi",lK="Tervetuloa",dK="Tervetuloa tilillesi {{vendorName}}!",uK="Tarkista sähköpostisi osoitteesta <0>{{email}}</0> ja syötä lähettämämme kuusinumeroinen koodi.",pK="Jatka tällä tilillä",fK="Kyllä, jatka {{text}}",hK="Kyllä, jatka olemassa olevalla tilillä",gK={account_detected:pF,account_page_description:fF,account_title:hF,account_with_sso_provider:gF,agree_to:mF,and:_F,auth_method_email:yF,auth_method_email_or_phone:wF,auth_method_phone:bF,callback_url_mismatch:vF,callback_url_not_allowed:$F,change_email:kF,check_email_title:xF,click_to_sign_up_description:SF,code_email_enter_code:zF,code_email_subject:AF,code_email_title:EF,code_expired:CF,code_invalid:NF,code_sent_template:IF,code_used:jF,code_valid_30_minutes:PF,configuration_error_message:OF,confirm_password:TF,confirm_unlink:RF,contact_support:BF,contact_us:LF,continue:"Jatka",continue_social_login:UF,continue_with:DF,continue_with_sso_provider_headline:MF,copyright:qF,copyright_sesamy:FF,create_account_description:HF,create_account_email_invalid:VF,create_account_passwords_didnt_match:KF,create_account_title:GF,create_account_weak_password:WF,create_new_account_link:JF,create_password_account_title:XF,current_email:ZF,currently_logged_in_as:YF,edit:QF,email:eH,email_already_taken:tH,email_changed_to_template:nH,email_or_phone_placeholder:rH,email_placeholder:iH,email_validated:oH,email_validated_cta:sH,email_verification_for_signup_sent_description:aH,email_verification_for_signup_sent_title:cH,embedded_browser_detected:lH,embedded_browser_warning:dH,enter_a_code_btn:uH,enter_email_for_verification_description:pH,enter_new_email:fH,enter_new_password_placeholder:hH,enter_password:gH,enter_password_description:mH,enter_your_password_btn:_H,error_page_title:yH,expired_code:wH,fokus_info_message:bH,forgot_password_cta:vH,forgot_password_description:$H,forgot_password_email_sent:kH,forgot_password_link:xH,forgot_password_title:SH,go_back:zH,hide_password:AH,incognito_mode_detected:EH,incognito_mode_warning:CH,"invalid-email":"Virheellinen sähköpostiosoite",invalid_identifier:NH,invalid_password:IH,invalid_session_body:jH,invalid_session_title:PH,linked_accounts:OH,link_email_click_to_login:TH,link_email_login:RH,link_email_or_enter_code:BH,link_page_body:LH,link_page_headline:UH,logged_in_as:DH,login:MH,login_description:qH,login_description_code:FH,login_description_combined:HH,login_description_link:VH,login_description_phone:KH,login_description_template:GH,logout:WH,new_email:JH,new_email_code_info:XH,no_email_address:ZH,no_use_another:YH,or:QH,password:eV,password_contains_forbidden_word:tV,password_contains_personal_info:nV,password_has_been_reset:rV,password_has_been_reset_title:iV,password_missing_lowercase:oV,password_missing_number:sV,password_missing_special:aV,password_missing_uppercase:cV,password_reset_code_expired:lV,password_reset_failed:dV,password_reused:uV,password_too_short:pV,password_reset_subject:fV,password_reset_title:hV,phone_placeholder:gV,privacy_policy:mV,redirecting:_V,reenter_new_password_placeholder:yV,register_password_account:wV,resend_code:bV,reset_password_cta:vV,reset_password_description:$V,reset_password_email_click_to_reset:kV,reset_password_email_cta:xV,reset_password_email_reset:SV,reset_password_subject:zV,reset_password_title:AV,send:EV,send_me_a_new_magic_link:CV,sent_code_spam:NV,"Server error: Invalid code":"Virheellinen koodi",set_password:IV,show_password:jV,sign_in:PV,signup:OV,signup_success:TV,sms_code_text:RV,spotify_already_linked_body:BV,spotify_already_linked_cta:LV,spotify_already_linked_step1_body:UV,spotify_already_linked_step1_title:DV,spotify_already_linked_step2_body:MV,spotify_already_linked_step2_title:qV,spotify_already_linked_title:FV,success:HV,support_info:VV,terms:KV,unexpected_error_try_again:GV,unlink:WV,unverified_email:JV,update_email:XV,user_account_does_not_exist:ZV,user_not_found:YV,user_not_found_body:QV,user_not_found_cta:eK,validate_code:tK,validate_email_body:nK,validate_email_title:rK,verify_email_click_to_verify:iK,verify_email_subject:oK,verify_email_title:sK,verify_email_verify:aK,verify_your_email:cK,welcome:lK,welcome_to_your_account:dK,we_sent_a_code_to:uK,yes_continue:pK,yes_continue_with:fK,yes_continue_with_existing_account:hK},mK="Konto opdaget",_K="Administrer dine kontooplysninger",yK="Konto",wK="Vi har opdaget, at du allerede har oprettet en konto gennem",bK="Når du logger ind, accepterer du vores",vK="og",$K="e-mail-adresse",kK="e-mail eller telefonnummer",xK="Telefonnummer",SK="Uoverensstemmelse mellem URL og tilbagekald",zK="Den angivne redirect_uri er ikke på listen over tilladte tilbagekalds-URL'er.",AK="Ændre e-mailadresse",EK="Fortsæt med brugeren",CK="Klik på knappen for at oprette en ny adgangskodekonto.",NK="Indtast koden på {{vendorName}} for at gennemføre login.",IK="Velkommen til {{vendorName}}! {{code}} er login-koden",jK="Velkommen til {{vendorName}}! {{code}} er login-koden",PK="Koden er udløbet",OK="Ugyldig kode",TK="Tjek venligst <0>{{username}}</0> og indtast den sekscifrede kode, som vi har sendt til dig.",RK="Koden er allerede brugt",BK="Koden er gyldig i 30 minutter",LK="Der opstod en konfigurationsfejl.",UK="Bekræft adgangskode",DK="Er du sikker på, at du vil fjerne forbindelsen til denne konto?",MK="Har du brug for hjælp?",qK="Kontakt os",FK="eller fortsæt med social konto",HK="Fortsæt med {{provider}}",VK="Vil du gerne fortsætte med din eksisterende konto?",KK="Ophavsret © 2023 SESAMY. Alle rettigheder forbeholdes.",GK="©2023 Sesamy",WK="Vælg en adgangskode med en blanding af store og små bogstaver, tal og symboler.",JK="Indtast venligst en gyldig e-mailadresse.",XK="Adgangskoderne stemte ikke overens. Prøv igen.",ZK="Vælg adgangskode",YK="Adgangskoden skal være mindst 8 tegn lang og indeholde mindst et lille bogstav, et stort bogstav, et tal og et symbol.",QK="Opret ny konto",eG="Tilmeld dig med adgangskode",tG="Nuværende e-mailadresse",nG="Du er i øjeblikket logget ind som <0>{{email}}</0>",rG="Rediger",iG="E-mail",oG="E-mailen er allerede optaget",sG="E-mail ændret til <0>{{email}}</0> ",aG="E-mail eller telefonnummer",cG="E-mail-adresse",lG="Din e-mailadresse er blevet valideret",dG="Indtast nu din adgangskode for at logge ind igen",uG="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.",pG="E-mail-bekræftelse sendt",fG="Skal man blive ved med at logge ind?",hG="Du er i øjeblikket inde på {{browserName}}. Denne browser logger dig ofte ud, så vi anbefaler, at du bruger din telefons standardbrowser i stedet.",gG="Indtast en kode",mG="Vi sender dig et bekræftelseslink for at sikre, at du ejer denne e-mailadresse.",_G="Indtast ny e-mail",yG="Indtast ny adgangskode",wG="Indtast adgangskode",bG="Indtast din e-mailadresse og adgangskode for at logge ind.",vG="Indtast din adgangskode",$G="Noget gik galt",kG="Det magiske link er udløbet. Klik på knappen nedenfor for at modtage et nyt link i din indbakke.",xG="Hej! Vi har opdateret vores login-oplevelse. <0>Klik her for at lære mere om det.</0>",SG="Send e-mail til nulstilling af adgangskode",zG="Klik på knappen nedenfor, så sender vi instruktioner om, hvordan du nulstiller din adgangskode.",AG="E-mail til nulstilling af adgangskode sendt",EG="Har du glemt din adgangskode?",CG="Har du glemt din adgangskode?",NG="Gå tilbage",IG="Skjul adgangskode",jG="Inkognitotilstand opdaget",PG="Du er i inkognito/privat tilstand. Sessionsdata fortsætter muligvis ikke på tværs af sideopdateringer. Nogle funktioner fungerer måske ikke som forventet.",OG="Ugyldig identifikator",TG="Ugyldig adgangskode",RG="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.",BG="Ugyldigt link",LG="Koblede konti",UG="Klik på knappen for at logge ind",DG="Login",MG="Eller indtast koden på {{vendorName}} for at gennemføre login.",qG="Indtast din e-mailadresse for at låse op for dette show på {{service}}",FG="Forbind din konto med {{service}}",HG="Du er logget ind som",VG="Login",KG="Indtast din e-mailadresse for at logge ind.",GG="Indtast din e-mailadresse, så sender vi dig en login-kode.",WG="Indtast din e-mail eller dit telefonnummer for at logge ind",JG="Indtast din e-mailadresse, så sender vi dig et login-link.",XG="Indtast dit telefonnummer for at logge ind",ZG="Indtast din {{authMethod}} for at logge ind.",YG="Log ud",QG="Ny emailadresse",eW="En engangskode vil blive sendt til din nye e-mailadresse, indtast koden i næste trin.",tW="Ingen e-mailadresse er angivet",nW="Nej, jeg vil bruge en anden konto",rW="eller",iW="Adgangskode",oW="Adgangskoden indeholder et forbudt ord",sW="Adgangskoden må ikke indeholde personlige oplysninger som dit navn eller e-mail",aW="Adgangskoden er blevet nulstillet",cW="Succes",lW="Adgangskoden skal indeholde mindst ét lille bogstav",dW="Adgangskoden skal indeholde mindst ét tal",uW="Adgangskoden skal indeholde mindst ét specialtegn",pW="Adgangskoden skal indeholde mindst ét stort bogstav",fW="Koden blev ikke fundet eller er udløbet",hW="Adgangskoden kunne ikke nulstilles",gW="Adgangskoden er blevet brugt for nylig og kan ikke genbruges",mW="Adgangskoden skal være mindst {{minLength}} tegn",_W="Skift adgangskode til din {{vendorName}} konto",yW="Skift adgangskode til din {{vendorName}} -konto",wW="Telefonnummer",bW="Politik for beskyttelse af personlige oplysninger",vW="Omdirigering",$W="Bekræft adgangskode",kW="Registrer en ny adgangskode",xW="Send koden igen",SW="Skift adgangskode",zW="Indtast din nye adgangskode til e-mailkontoen nedenfor: ",AW="Klik på knappen for at nulstille din adgangskode",EW="Klik på knappen for at nulstille din adgangskode",CW="Nulstil din adgangskode",NW="Skift adgangskode til din {{vendorName}} -konto",IW="Nulstil adgangskode",jW="Send",PW="Send mig et nyt magisk link",OW="Husk at tjekke din spam-mappe, hvis e-mailen ikke er kommet frem.",TW="Indstil adgangskode",RW="Vis adgangskode",BW="Log ind",LW="Tilmelding",UW="Tilmeld dig med succes",DW="{{code}} er din login-kode til {{vendorName}}",MW="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.",qW="Gå til Spotifys side for adgang til indhold",FW='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.',HW="Trin 1: Fjern forbindelsen til din Spotify-konto",VW="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.",KW="Trin 2: Relink din Spotify-konto til Sesamy",GW="Ups! Din Spotify-konto er allerede forbundet",WW="Færdig",JW="Hvis du har spørgsmål eller brug for hjælp, kan du kontakte vores supportteam",XW="Vilkår og betingelser",ZW="Noget gik galt. Prøv venligst igen.",YW="Frakobl",QW="Din e-mailadresse skal valideres. Vi har sendt en ny e-mail til din indbakke",eJ="Opdatering af e-mail",tJ="Brugerkontoen findes ikke",nJ="Brugerkontoen findes ikke",rJ="Vi kunne ikke finde en bruger med den angivne e-mailadresse. Prøv venligst igen.",iJ="Prøv igen.",oJ="Valider koden",sJ="Tjek din indbakke for instruktioner om validering af e-mail.",aJ="Tilmeldte sig",cJ="Klik på knappen for at bekræfte din e-mailadresse",lJ="Bekræft din e-mailadresse",dJ="Bekræft din e-mailadresse",uJ="Bekræft konto",pJ="Bekræft din e-mail",fJ="Velkommen",hJ="Velkommen til din {{vendorName}} konto!",gJ="Tjek venligst din e-mail på <0>{{email}}</0> og indtast den sekscifrede kode, vi har sendt dig.",mJ="Fortsæt med denne konto",_J="Ja, fortsæt med {{text}}",yJ="Ja, fortsæt med eksisterende konto",wJ={account_detected:mK,account_page_description:_K,account_title:yK,account_with_sso_provider:wK,agree_to:bK,and:vK,auth_method_email:$K,auth_method_email_or_phone:kK,auth_method_phone:xK,callback_url_mismatch:SK,callback_url_not_allowed:zK,change_email:AK,check_email_title:EK,click_to_sign_up_description:CK,code_email_enter_code:NK,code_email_subject:IK,code_email_title:jK,code_expired:PK,code_invalid:OK,code_sent_template:TK,code_used:RK,code_valid_30_minutes:BK,configuration_error_message:LK,confirm_password:UK,confirm_unlink:DK,contact_support:MK,contact_us:qK,continue:"Fortsæt",continue_social_login:FK,continue_with:HK,continue_with_sso_provider_headline:VK,copyright:KK,copyright_sesamy:GK,create_account_description:WK,create_account_email_invalid:JK,create_account_passwords_didnt_match:XK,create_account_title:ZK,create_account_weak_password:YK,create_new_account_link:QK,create_password_account_title:eG,current_email:tG,currently_logged_in_as:nG,edit:rG,email:iG,email_already_taken:oG,email_changed_to_template:sG,email_or_phone_placeholder:aG,email_placeholder:cG,email_validated:lG,email_validated_cta:dG,email_verification_for_signup_sent_description:uG,email_verification_for_signup_sent_title:pG,embedded_browser_detected:fG,embedded_browser_warning:hG,enter_a_code_btn:gG,enter_email_for_verification_description:mG,enter_new_email:_G,enter_new_password_placeholder:yG,enter_password:wG,enter_password_description:bG,enter_your_password_btn:vG,error_page_title:$G,expired_code:kG,fokus_info_message:xG,forgot_password_cta:SG,forgot_password_description:zG,forgot_password_email_sent:AG,forgot_password_link:EG,forgot_password_title:CG,go_back:NG,hide_password:IG,incognito_mode_detected:jG,incognito_mode_warning:PG,"invalid-email":"Ugyldig e-mail",invalid_identifier:OG,invalid_password:TG,invalid_session_body:RG,invalid_session_title:BG,linked_accounts:LG,link_email_click_to_login:UG,link_email_login:DG,link_email_or_enter_code:MG,link_page_body:qG,link_page_headline:FG,logged_in_as:HG,login:VG,login_description:KG,login_description_code:GG,login_description_combined:WG,login_description_link:JG,login_description_phone:XG,login_description_template:ZG,logout:YG,new_email:QG,new_email_code_info:eW,no_email_address:tW,no_use_another:nW,or:rW,password:iW,password_contains_forbidden_word:oW,password_contains_personal_info:sW,password_has_been_reset:aW,password_has_been_reset_title:cW,password_missing_lowercase:lW,password_missing_number:dW,password_missing_special:uW,password_missing_uppercase:pW,password_reset_code_expired:fW,password_reset_failed:hW,password_reused:gW,password_too_short:mW,password_reset_subject:_W,password_reset_title:yW,phone_placeholder:wW,privacy_policy:bW,redirecting:vW,reenter_new_password_placeholder:$W,register_password_account:kW,resend_code:xW,reset_password_cta:SW,reset_password_description:zW,reset_password_email_click_to_reset:AW,reset_password_email_cta:EW,reset_password_email_reset:CW,reset_password_subject:NW,reset_password_title:IW,send:jW,send_me_a_new_magic_link:PW,sent_code_spam:OW,"Server error: Invalid code":"Ugyldig kode",set_password:TW,show_password:RW,sign_in:BW,signup:LW,signup_success:UW,sms_code_text:DW,spotify_already_linked_body:MW,spotify_already_linked_cta:qW,spotify_already_linked_step1_body:FW,spotify_already_linked_step1_title:HW,spotify_already_linked_step2_body:VW,spotify_already_linked_step2_title:KW,spotify_already_linked_title:GW,success:WW,support_info:JW,terms:XW,unexpected_error_try_again:ZW,unlink:YW,unverified_email:QW,update_email:eJ,user_account_does_not_exist:tJ,user_not_found:nJ,user_not_found_body:rJ,user_not_found_cta:iJ,validate_code:oJ,validate_email_body:sJ,validate_email_title:aJ,verify_email_click_to_verify:cJ,verify_email_subject:lJ,verify_email_title:dJ,verify_email_verify:uJ,verify_your_email:pJ,welcome:fJ,welcome_to_your_account:hJ,we_sent_a_code_to:gJ,yes_continue:mJ,yes_continue_with:_J,yes_continue_with_existing_account:yJ},bJ=({...t})=>p("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",...t,children:[p("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"}),p("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"}),p("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"}),p("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"})]}),vJ=t=>{const{theme:e,branding:n,client:r,authParams:i}=t,a=`/authorize?${new URLSearchParams({...i})}`;return p(Se,{theme:e,branding:n,client:r,title:y.t("user_not_found"),children:p("div",{className:"flex flex-1 flex-col justify-center",children:[p("p",{className:"mb-8 text-gray-300 text-lg",children:y.t("user_not_found_body")}),p(xe,{Component:"a",href:a,children:y.t("user_not_found_cta")})]})})},$J=({...t})=>p("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",...t,children:[p("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"}),p("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
156
156
  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
157
157
  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`})]});function kJ(t,e){const{mainTenantId:n,mainClientId:r}=e;return{...t,legacyClients:{get:async i=>{const s=await t.legacyClients.get(i);if(!s)return null;const a=r?await t.legacyClients.get(r):void 0,c=await t.connections.list(s.tenant.id),l=n?await t.connections.list(n):{connections:[]},d=c.connections.map(f=>{const g=l.connections?.find(w=>w.name===f.name);if(!g?.options)return f;const _=ht.parse({...g||{},...f});return _.options=Dr.parse({...g.options||{},...f.options}),_}).filter(f=>f),u={...a?.tenant||{},...s.tenant};return!s.tenant.audience&&a?.tenant?.audience&&(u.audience=a.tenant.audience),{...s,web_origins:[...a?.web_origins||[],...s.web_origins||[]],allowed_logout_urls:[...a?.allowed_logout_urls||[],...s.allowed_logout_urls||[]],callbacks:[...a?.callbacks||[],...s.callbacks||[]],connections:d,tenant:u}}},connections:{...t.connections,get:async(i,s)=>{const a=await t.connections.get(i,s);if(!a||!n)return a;const c=await t.connections.get(n,s);if(!c)return a;const l=ht.parse({...c,...a});return l.options=Dr.parse({...c.options||{},...a.options}),l},list:async(i,s)=>{const a=await t.connections.list(i,s);if(!n||i===n)return a;const c=await t.connections.list(n),l=a.connections.map(d=>{const u=c.connections?.find(g=>g.name===d.name);if(!u?.options)return d;const f=ht.parse({...u,...d});return f.options=Dr.parse({...u.options||{},...d.options}),f});return{...a,connections:l}}}}}function xJ(t,e){return kJ(t,e)}async function SJ(t,e){const{adminEmail:n,adminPassword:r,tenantId:i="default",tenantName:s="Default Tenant",audience:a="urn:default",clientId:c="default",callbacks:l=["https://manage.authhero.net/auth-callback","https://localhost:5173/auth-callback"],debug:d=!0}=e;await t.tenants.get(i)?d&&console.log(`Tenant "${i}" already exists, skipping...`):(d&&console.log(`Creating tenant "${i}"...`),await t.tenants.create({id:i,friendly_name:s,audience:a,sender_email:"noreply@example.com",sender_name:"AuthHero"}),d&&console.log("✅ Tenant created"));const{signingKeys:f}=await t.keys.list({q:"type:jwt_signing"});if(f.length===0){d&&console.log("Creating signing key...");const N=await Da({name:`CN=${i}`});await t.keys.create(N),d&&console.log("✅ Signing key created")}else d&&console.log("Signing key already exists, skipping...");const g=await t.users.list(i,{q:`email:${n}`});let _;if(g.users.length===0){d&&console.log(`Creating admin user "${n}"...`),_=(await t.users.create(i,{user_id:`auth2|${pe()}`,email:n,email_verified:!0,connection:"Username-Password-Authentication",provider:"auth2"})).user_id;const I=await Pn.hash(r,10);await t.passwords.create(i,{user_id:_,password:I,algorithm:"bcrypt",is_current:!0}),d&&(console.log("✅ Admin user created"),console.log(` Email: ${n}`))}else _=g.users[0].user_id,d&&console.log(`Admin user "${n}" already exists, skipping...`);return(await t.connections.list(i)).connections.some(N=>N.name==="Username-Password-Authentication")?d&&console.log("Password connection already exists, skipping..."):(d&&console.log("Creating password connection..."),await t.connections.create(i,{name:"Username-Password-Authentication",strategy:"Username-Password-Authentication",options:{}}),d&&console.log("✅ Password connection created")),await t.clients.get(i,c)?d&&console.log("Default client already exists, skipping..."):(d&&console.log("Creating default client..."),await t.clients.create(i,{client_id:c,name:"Default Application",callbacks:l,connections:["Username-Password-Authentication"]}),d&&(console.log("✅ Default client created"),console.log(` Client ID: ${c}`),console.log(` Callback URLs: ${l.join(", ")}`))),d&&console.log(`
158
- 🎉 Seeding complete!`),{tenantId:i,userId:_,email:n,clientId:c}}y.init({supportedLngs:["en","it","nb","sv","pl","cs","fi","da"],fallbackLng:"en",resources:{en:{translation:VA},it:{translation:JN},nb:{translation:QP},sv:{translation:rB},pl:{translation:aD},cs:{translation:uF},fi:{translation:gK},da:{translation:wJ}}});function zJ(t){const e=new o.OpenAPIHono;e.use("*",async(a,c)=>{t.hooks&&(a.env.hooks={...t.hooks,...a.env.hooks||{}}),t.samlSigner&&(a.env.samlSigner=t.samlSigner),await c()}),e.get("/",a=>a.json({name:"authhero"}));const n=r5(t);e.route("/api/v2",n);const r=uS(t);e.route("/u",r);const i=M9(t);e.route("/samlp",i);const s=J8(t);return e.route("/",s),{app:e,managementApp:n,oauthApp:s,samlApp:i,universalApp:r,createX509Certificate:Da}}exports.AppLogo=Rt;exports.Auth0Client=gm;exports.AuthLayout=we;exports.AuthorizationResponseMode=Ct;exports.AuthorizationResponseType=mt;exports.Button=xe;exports.ButtonUI=Jt;exports.CardContent=on;exports.CardDescription=rn;exports.CardFooter=F1;exports.CardHeader=tn;exports.CardTitle=nn;exports.CardUI=en;exports.CheckEmailPage=iw;exports.CodeChallengeMethod=Ga;exports.ComponentCategory=Au;exports.ComponentType=zu;exports.EmailValidatedPage=aw;exports.EnterCodePage=bu;exports.EnterPasswordPage=Us;exports.ErrorMessage=Re;exports.Footer=H1;exports.ForgotPasswordPage=nw;exports.ForgotPasswordSentPage=rw;exports.FormComponent=Bt;exports.GoBack=lt;exports.GoogleLogo=bJ;exports.GrantType=St;exports.HttpSamlSigner=c_;exports.Icon=Ne;exports.IdentifierForm=Ts;exports.IdentifierPage=Rs;exports.InputUI=Pt;exports.InvalidSession=sw;exports.LabelUI=_t;exports.Layout=Se;exports.LocationInfo=mm;exports.LogTypes=te;exports.Message=wt;exports.NodeType=X0;exports.PreSignUpConfirmationPage=cw;exports.PreSignUpPage=ow;exports.ResetPasswordPage=Rr;exports.SignUpPage=Gn;exports.SocialButton=K1;exports.Spinner=V1;exports.Trans=Un;exports.UnverifiedEmailPage=tw;exports.UserNotFoundPage=vJ;exports.VippsLogo=$J;exports.auth0FlowInsertSchema=nb;exports.auth0FlowSchema=rm;exports.auth0QuerySchema=Zw;exports.auth0UserResponseSchema=Ft;exports.authParamsSchema=go;exports.baseUserSchema=Va;exports.bordersSchema=vm;exports.brandingSchema=Bl;exports.buttonComponentSchema=V0;exports.clientGrantInsertSchema=Vs;exports.clientGrantListSchema=tb;exports.clientGrantSchema=Xn;exports.clientInsertSchema=Hs;exports.clientSchema=Jn;exports.codeInsertSchema=om;exports.codeSchema=ib;exports.codeTypeSchema=im;exports.colorsSchema=$m;exports.componentSchema=J0;exports.connectionInsertSchema=Ks;exports.connectionOptionsSchema=Dr;exports.connectionSchema=ht;exports.coordinatesSchema=ui;exports.createInMemoryCache=ds;exports.createPassthroughAdapter=kb;exports.createWriteOnlyAdapter=xb;exports.customDomainInsertSchema=Eu;exports.customDomainSchema=xn;exports.customDomainWithTenantIdSchema=ob;exports.emailProviderSchema=zs;exports.endingSchema=nm;exports.fieldComponentSchema=G0;exports.flowNodeSchema=Y0;exports.fontDetailsSchema=Kn;exports.fontsSchema=km;exports.formControlSchema=sb;exports.formInsertSchema=Gs;exports.formNodeComponentDefinition=cm;exports.formSchema=Br;exports.genericComponentSchema=W0;exports.genericNodeSchema=Q0;exports.hookInsertSchema=ks;exports.hookSchema=Lr;exports.identitySchema=F0;exports.init=zJ;exports.injectTailwindCSS=rS;exports.inviteInsertSchema=Cu;exports.inviteSchema=io;exports.inviteeSchema=pm;exports.inviterSchema=um;exports.jwksKeySchema=fm;exports.jwksSchema=Nu;exports.legacyClientSchema=rb;exports.legalComponentSchema=K0;exports.logInsertSchema=_m;exports.logSchema=Ws;exports.loginSessionInsertSchema=hm;exports.loginSessionSchema=ub;exports.nodeSchema=em;exports.openIDConfigurationSchema=Ll;exports.organizationBrandingSchema=Lm;exports.organizationEnabledConnectionSchema=Um;exports.organizationInsertSchema=Ys;exports.organizationSchema=zn;exports.organizationTokenQuotaSchema=Dm;exports.pageBackgroundSchema=xm;exports.parseUserId=$b;exports.passwordInsertSchema=ym;exports.passwordSchema=fb;exports.profileDataSchema=q0;exports.promptSettingSchema=Ss;exports.refreshTokenInsertSchema=ju;exports.refreshTokenSchema=hb;exports.resourceServerInsertSchema=Js;exports.resourceServerListSchema=_b;exports.resourceServerOptionsSchema=Em;exports.resourceServerSchema=Zn;exports.resourceServerScopeSchema=Am;exports.richTextComponentSchema=H0;exports.roleInsertSchema=Xs;exports.roleListSchema=Zs;exports.rolePermissionInsertSchema=Cm;exports.rolePermissionListSchema=Im;exports.rolePermissionSchema=Nm;exports.roleSchema=Yn;exports.seed=SJ;exports.sessionInsertSchema=bm;exports.sessionSchema=Ja;exports.signingKeySchema=Ul;exports.smsProviderSchema=mb;exports.smsSendParamsSchema=gb;exports.startSchema=tm;exports.stepNodeSchema=Z0;exports.tailwindCss=Zp;exports.tenantInsertSchema=ro;exports.tenantSchema=Sn;exports.tenantSettingsSchema=vb;exports.themeInsertSchema=zm;exports.themeSchema=xs;exports.tokenResponseSchema=Iu;exports.totalsSchema=it;exports.userInsertSchema=Fs;exports.userOrganizationInsertSchema=Mm;exports.userOrganizationSchema=bb;exports.userPermissionInsertSchema=jm;exports.userPermissionListSchema=yb;exports.userPermissionSchema=Pm;exports.userPermissionWithDetailsListSchema=Tm;exports.userPermissionWithDetailsSchema=Om;exports.userResponseSchema=Yw;exports.userRoleInsertSchema=Rm;exports.userRoleListSchema=wb;exports.userRoleSchema=Bm;exports.userSchema=Su;exports.verificationMethodsSchema=sm;exports.waitUntil=Zm;exports.widgetSchema=Sm;exports.withMainTenantFallback=xJ;
158
+ 🎉 Seeding complete!`),{tenantId:i,userId:_,email:n,clientId:c}}y.init({supportedLngs:["en","it","nb","sv","pl","cs","fi","da"],fallbackLng:"en",resources:{en:{translation:VA},it:{translation:JN},nb:{translation:QP},sv:{translation:rB},pl:{translation:aD},cs:{translation:uF},fi:{translation:gK},da:{translation:wJ}}});function zJ(t){const e=new o.OpenAPIHono;e.use("*",async(a,c)=>{t.hooks&&(a.env.hooks={...t.hooks,...a.env.hooks||{}}),t.samlSigner&&(a.env.samlSigner=t.samlSigner),await c()}),e.get("/",a=>a.json({name:"authhero"}));const n=r5(t);e.route("/api/v2",n);const r=uS(t);e.route("/u",r);const i=M9(t);e.route("/samlp",i);const s=J8(t);return e.route("/",s),{app:e,managementApp:n,oauthApp:s,samlApp:i,universalApp:r,createX509Certificate:Da}}exports.AppLogo=Rt;exports.Auth0Client=gm;exports.AuthLayout=we;exports.AuthorizationResponseMode=Ct;exports.AuthorizationResponseType=mt;exports.Button=xe;exports.ButtonUI=Jt;exports.CardContent=on;exports.CardDescription=rn;exports.CardFooter=F1;exports.CardHeader=tn;exports.CardTitle=nn;exports.CardUI=en;exports.CheckEmailPage=iw;exports.CodeChallengeMethod=Ga;exports.ComponentCategory=Au;exports.ComponentType=zu;exports.EmailValidatedPage=aw;exports.EnterCodePage=bu;exports.EnterPasswordPage=Us;exports.ErrorMessage=Re;exports.Footer=H1;exports.ForgotPasswordPage=nw;exports.ForgotPasswordSentPage=rw;exports.FormComponent=Bt;exports.GoBack=lt;exports.GoogleLogo=bJ;exports.GrantType=St;exports.HttpSamlSigner=c_;exports.Icon=Ne;exports.IdentifierForm=Ts;exports.IdentifierPage=Rs;exports.InputUI=Pt;exports.InvalidSession=sw;exports.LabelUI=_t;exports.Layout=Se;exports.LocationInfo=mm;exports.LogTypes=te;exports.Message=wt;exports.NodeType=X0;exports.PreSignUpConfirmationPage=cw;exports.PreSignUpPage=ow;exports.ResetPasswordPage=Rr;exports.SignUpPage=Gn;exports.SocialButton=K1;exports.Spinner=V1;exports.Trans=Un;exports.UnverifiedEmailPage=tw;exports.UserNotFoundPage=vJ;exports.VippsLogo=$J;exports.auth0FlowInsertSchema=nb;exports.auth0FlowSchema=rm;exports.auth0QuerySchema=Zw;exports.auth0UserResponseSchema=Ft;exports.authParamsSchema=mo;exports.baseUserSchema=Va;exports.bordersSchema=vm;exports.brandingSchema=Bl;exports.buttonComponentSchema=V0;exports.clientGrantInsertSchema=Vs;exports.clientGrantListSchema=tb;exports.clientGrantSchema=Xn;exports.clientInsertSchema=Hs;exports.clientSchema=Jn;exports.codeInsertSchema=om;exports.codeSchema=ib;exports.codeTypeSchema=im;exports.colorsSchema=$m;exports.componentSchema=J0;exports.connectionInsertSchema=Ks;exports.connectionOptionsSchema=Dr;exports.connectionSchema=ht;exports.coordinatesSchema=pi;exports.createInMemoryCache=ds;exports.createPassthroughAdapter=kb;exports.createWriteOnlyAdapter=xb;exports.customDomainInsertSchema=Eu;exports.customDomainSchema=xn;exports.customDomainWithTenantIdSchema=ob;exports.emailProviderSchema=zs;exports.endingSchema=nm;exports.fieldComponentSchema=G0;exports.flowNodeSchema=Y0;exports.fontDetailsSchema=Kn;exports.fontsSchema=km;exports.formControlSchema=sb;exports.formInsertSchema=Gs;exports.formNodeComponentDefinition=cm;exports.formSchema=Br;exports.genericComponentSchema=W0;exports.genericNodeSchema=Q0;exports.hookInsertSchema=ks;exports.hookSchema=Lr;exports.identitySchema=F0;exports.init=zJ;exports.injectTailwindCSS=rS;exports.inviteInsertSchema=Cu;exports.inviteSchema=oo;exports.inviteeSchema=pm;exports.inviterSchema=um;exports.jwksKeySchema=fm;exports.jwksSchema=Nu;exports.legacyClientSchema=rb;exports.legalComponentSchema=K0;exports.logInsertSchema=_m;exports.logSchema=Ws;exports.loginSessionInsertSchema=hm;exports.loginSessionSchema=ub;exports.nodeSchema=em;exports.openIDConfigurationSchema=Ll;exports.organizationBrandingSchema=Lm;exports.organizationEnabledConnectionSchema=Um;exports.organizationInsertSchema=Ys;exports.organizationSchema=zn;exports.organizationTokenQuotaSchema=Dm;exports.pageBackgroundSchema=xm;exports.parseUserId=$b;exports.passwordInsertSchema=ym;exports.passwordSchema=fb;exports.profileDataSchema=q0;exports.promptSettingSchema=Ss;exports.refreshTokenInsertSchema=ju;exports.refreshTokenSchema=hb;exports.resourceServerInsertSchema=Js;exports.resourceServerListSchema=_b;exports.resourceServerOptionsSchema=Em;exports.resourceServerSchema=Zn;exports.resourceServerScopeSchema=Am;exports.richTextComponentSchema=H0;exports.roleInsertSchema=Xs;exports.roleListSchema=Zs;exports.rolePermissionInsertSchema=Cm;exports.rolePermissionListSchema=Im;exports.rolePermissionSchema=Nm;exports.roleSchema=Yn;exports.seed=SJ;exports.sessionInsertSchema=bm;exports.sessionSchema=Ja;exports.signingKeySchema=Ul;exports.smsProviderSchema=mb;exports.smsSendParamsSchema=gb;exports.startSchema=tm;exports.stepNodeSchema=Z0;exports.tailwindCss=Zp;exports.tenantInsertSchema=io;exports.tenantSchema=Sn;exports.tenantSettingsSchema=vb;exports.themeInsertSchema=zm;exports.themeSchema=xs;exports.tokenResponseSchema=Iu;exports.totalsSchema=it;exports.userInsertSchema=Fs;exports.userOrganizationInsertSchema=Mm;exports.userOrganizationSchema=bb;exports.userPermissionInsertSchema=jm;exports.userPermissionListSchema=yb;exports.userPermissionSchema=Pm;exports.userPermissionWithDetailsListSchema=Tm;exports.userPermissionWithDetailsSchema=Om;exports.userResponseSchema=Yw;exports.userRoleInsertSchema=Rm;exports.userRoleListSchema=wb;exports.userRoleSchema=Bm;exports.userSchema=Su;exports.verificationMethodsSchema=sm;exports.waitUntil=Zm;exports.widgetSchema=Sm;exports.withMainTenantFallback=xJ;