@muze-nl/metro-oidc 0.9.2 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- (()=>{var wr=Object.defineProperty;var Pt=(e,t)=>{for(var r in t)wr(e,r,{get:t[r],enumerable:!0})};var N={};Pt(N,{Client:()=>he,client:()=>I,deepClone:()=>me,metroError:()=>l,request:()=>L,response:()=>He,url:()=>S});var Q="https://metro.muze.nl/details/";Symbol.metroProxy||(Symbol.metroProxy=Symbol("isProxy"));Symbol.metroSource||(Symbol.metroSource=Symbol("source"));var he=class e{clientOptions={url:S(typeof window<"u"?window.location:"https://localhost"),verbs:["get","post","put","delete","patch","head","options","query"]};static tracers={};constructor(...t){for(let r of t)if(typeof r=="string"||r instanceof String)this.clientOptions.url=S(this.clientOptions.url.href,r);else if(r instanceof e)Object.assign(this.clientOptions,r.clientOptions);else if(r instanceof Function)this.#e([r]);else if(r&&typeof r=="object")for(let n in r)n=="middlewares"?this.#e(r[n]):n=="url"?this.clientOptions.url=S(this.clientOptions.url.href,r[n]):typeof r[n]=="function"?this.clientOptions[n]=r[n](this.clientOptions[n],this.clientOptions):this.clientOptions[n]=r[n];for(let r of this.clientOptions.verbs)this[r]=async function(...n){return this.fetch(L(this.clientOptions,...n,{method:r.toUpperCase()}),xr(...n))}}#e(t){typeof t=="function"&&(t=[t]);let r=t.findIndex(n=>typeof n!="function");if(r>=0)throw l("metro.client: middlewares must be a function or an array of functions "+Q+"client/invalid-middlewares/",t[r]);Array.isArray(this.clientOptions.middlewares)||(this.clientOptions.middlewares=[]),this.clientOptions.middlewares=this.clientOptions.middlewares.concat(t)}fetch(t,r){if(t=L(t,r),!t.url)throw l("metro.client."+t.method.toLowerCase()+": Missing url parameter "+Q+"client/fetch-missing-url/",t);if(r||(r={}),typeof r!="object"||r instanceof String)throw l("metro.client.fetch: Invalid options parameter "+Q+"client/fetch-invalid-options/",r);r=Object.assign({},this.clientOptions,r);let n=Pr(t,r),o=Tr(this,r,n),i=this.clientOptions?.middlewares||[];return br(i,n,o)(t)}with(...t){return new e(me(this.clientOptions),...t)}get location(){return this.clientOptions.url}};async function gr(e){e[Symbol.metroProxy]&&(e=e[Symbol.metroSource]);let t=await fetch(e);return He(t)}function br(e,t,r){let n;for(let o of[gr,...e])n=Sr(o,n,t,r);return n}function Sr(e,t,r,n){let o=r.tracers;return async function(i){pe(o,"request",i,e,r);let s;try{s=await e(i,t,n)}catch(a){throw pe(o,"error",a,i,e,r),a}return pe(o,"response",s,e,r),s}}var Er=0,Ar=["trace","tracer","tracers"];function xr(...e){let t={};for(let r of e)if(Tt(r))for(let n of Ar)n in r&&(t[n]=r[n]);return t}function Pr(e,t={}){let r=Rr(t.trace||t.tracer||t.tracers),n=[];r?n=r.localTracers||[]:n=de(t.trace).concat(de(t.tracer)).concat(de(t.tracers));let o=Object.values(he.tracers||{});return{__metroTraceContext:!0,id:"metro-trace-context-"+ ++Er,parent:r,request:e,options:t,globalTracers:o,localTracers:n,tracers:o.concat(n)}}function Rr(e){return e?e.context?.__metroTraceContext?e.context:e.__metroTraceContext?e:null:null}function de(e){return!e||e.__metroTraceContext||e.context?.__metroTraceContext?[]:Array.isArray(e)?e.flatMap(de):kr(e)?[e]:Tt(e)?Object.values(e).flatMap(de):[]}function kr(e){return e&&typeof e=="object"&&["request","response","error","event","diagnostic","span","link","current"].some(t=>typeof e[t]=="function")}function Tr(e,t,r){let n=Kr(r);return Object.freeze({client:e,options:t,trace:n,fetch(o,i={}){return e.fetch(o,Object.assign({},i,{trace:n}))}})}function Kr(e){let t={__metroTraceContext:!0,context:e,event(r,n={}){pe(e.tracers,"event",r,n,e)},diagnostic(r={}){pe(e.tracers,"diagnostic",r,e)},current(){for(let r of e.tracers)if(typeof r.current=="function"){let n=r.current(e);if(n)return n}return{traceId:null,spanId:null}},async span(r,n,o={}){let i=e.tracers.find(s=>typeof s.span=="function");return i?Or(i,r,n,o,e):n()},link(r){let n=null;for(let o of e.tracers)typeof o.link=="function"&&(n=o.link(r,void 0,e)||n);return n},options(r={}){return Object.assign({},r,{trace:t})}};return t}function pe(e,t,...r){for(let n of e)n&&typeof n[t]=="function"&&vr(n,t,r)}async function Or(e,t,r,n,o){let i=null,s=()=>(i||(i=(async()=>r())()),i);try{await e.span(t,s,n,o)}catch(a){Me.error("metro: tracer.span() failed",a)}return s()}function vr(e,t,r){let n=o=>{Me.error("metro: tracer."+t+"() failed",o)};try{let o=e[t].call(e,...r);typeof o?.then=="function"&&o.then(void 0,n)}catch(o){n(o)}}function Tt(e){return e&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function I(...e){return new he(...me(e))}function Cr(e,t){let r=t||{};!r.url&&t.url&&(r.url=t.url);for(let n of["method","headers","body","mode","credentials","cache","redirect","referrer","referrerPolicy","integrity","keepalive","signal","priority","url"]){let o=e[n];if(!(typeof o>"u"||o==null))if(o?.[Symbol.metroProxy]&&(o=o[Symbol.metroSource]),typeof o=="function")r[n]=o(r[n],r);else if(n=="url")r.url=S(r.url,o);else if(n=="headers"){r.headers=new Headers(t.headers),o instanceof Headers||(o=new Headers(e.headers));for(let[i,s]of o.entries())r.headers.set(i,s)}else r[n]=o}return e instanceof Request&&e.data&&(r.body=e.data),r}function L(...e){let t={url:S(typeof window<"u"?window.location:"https://localhost/"),duplex:"half"};for(let o of e)typeof o=="string"||o instanceof URL||o instanceof URLSearchParams?t.url=S(t.url,o):o&&(o instanceof FormData||o instanceof ReadableStream||o instanceof Blob||o instanceof ArrayBuffer||o instanceof DataView)?t.body=o:o&&typeof o=="object"&&Object.assign(t,Cr(o,t));let r=new Request(t.url,t),n=t.body;return n&&typeof n=="object"&&!(n instanceof String)&&!(n instanceof ReadableStream)&&!(n instanceof Blob)&&!(n instanceof ArrayBuffer)&&!(n instanceof DataView)&&!(n instanceof FormData)&&!(n instanceof URLSearchParams)&&globalThis.ArrayBuffer&&ArrayBuffer.isView(n)&&typeof n.toString=="function"&&(t.body=n.toString({headers:r.headers}),r=new Request(t.url,t)),Object.freeze(r),new Proxy(r,{get(o,i){let s;switch(i){case Symbol.metroSource:s=o;break;case Symbol.metroProxy:s=!0;break;case"with":s=function(...a){return typeof n<"u"&&a.unshift({body:n}),L(o,...a)};break;case"data":s=n;break;default:o[i]instanceof Function?i==="clone"?s=function(){let a=o.clone();return typeof n<"u"&&!(typeof ReadableStream<"u"&&n instanceof ReadableStream)?L(a,{body:n}):L(a)}:s=o[i].bind(o):s=o[i];break}return s}})}function Rt(e,t){let r=t||{};!r.url&&t.url&&(r.url=t.url);for(let n of["status","statusText","headers","body","url","type","redirected"]){let o=e[n];typeof o>"u"||o==null||(o?.[Symbol.metroProxy]&&(o=o[Symbol.metroSource]),typeof o=="function"?r[n]=o(r[n],r):n=="url"?r.url=new URL(o,r.url||"https://localhost/"):r[n]=o)}return e instanceof Response&&e.data&&(r.body=e.data),r}function He(...e){let t={};for(let o of e)typeof o=="string"?t.body=o:o instanceof Response?Object.assign(t,Rt(o,t)):o&&typeof o=="object"&&(o instanceof FormData||o instanceof Blob||o instanceof ArrayBuffer||o instanceof DataView||o instanceof ReadableStream||o instanceof URLSearchParams||o instanceof String||typeof globalThis.TypedArray<"u"&&o instanceof globalThis.TypedArray?t.body=o:Object.assign(t,Rt(o,t)));let r;t.body&&(r=t.body),[101,204,205,304].includes(t.status)&&(t.body=null);let n=new Response(t.body,t);return Object.freeze(n),new Proxy(n,{get(o,i){let s;switch(i){case Symbol.metroProxy:s=!0;break;case Symbol.metroSource:s=o;break;case"with":s=function(...a){return He(o,...a)};break;case"data":s=r;break;case"ok":s=o.status>=200&&o.status<300;break;default:typeof o[i]=="function"?s=o[i].bind(o):s=o[i];break}return s}})}function kt(e,t){typeof t=="function"?t(e.searchParams,e):(t=new URLSearchParams(t),t.forEach((r,n)=>{e.searchParams.append(n,r)}))}function Ir(e,t){let r=e[Symbol.metroSource]||e;t instanceof URLSearchParams||(t=new URLSearchParams(t));let n=r.hash||"#";return n+="?"+t,S(r,{hash:n})}function S(...e){let t=["hash","fragment","host","hostname","href","password","pathname","port","protocol","username","search","searchParams","hashParams"],r=new URL("https://localhost/"),n=null;for(let o of e)if(typeof o=="string"||o instanceof String)r=new URL(o,r);else if(o instanceof URL||typeof Location<"u"&&o instanceof Location)r=new URL(o);else if(o instanceof URLSearchParams)kt(r,o);else if(o&&typeof o=="object")for(let i in o)switch(i){case"search":typeof o.search=="function"?o.search(r.search,r):r.search=new URLSearchParams(o.search);break;case"searchParams":kt(r,o.searchParams);break;default:if(!t.includes(i))throw l("metro.url: unknown url parameter "+Q+"url/unknown-param-name/",i);if(i=="fragment"){let s=o.fragment;s&&typeof s=="string"&&s[0]!="#"&&(s="#"+s),o.hash=s,i="hash"}else i=="hashParams"&&(n=o.hashParams);if(typeof o[i]=="function")o[i](r[i],r);else if(typeof o[i]=="string"||o[i]instanceof String||typeof o[i]=="number"||o[i]instanceof Number||typeof o[i]=="boolean"||o[i]instanceof Boolean)r[i]=""+o[i];else if(typeof o[i]=="object"&&o[i].toString)r[i]=o[i].toString();else throw l("metro.url: unsupported value for "+i+" "+Q+"url/unsupported-param-value/",e[i]);break}else throw l("metro.url: unsupported option value "+Q+"url/unsupported-option-value/",o);return n&&(r.hash||(r.hash="#"),typeof n=="string"?r.hash+=n:r=Ir(r,n)),Object.freeze(r),new Proxy(r,{get(o,i){let s;switch(i){case Symbol.metroProxy:s=!0;break;case Symbol.metroSource:s=o;break;case"with":s=function(...a){return S(o,...a)};break;case"filename":s=o.pathname.split("/").pop();break;case"folderpath":s=o.pathname.substring(0,o.pathname.lastIndexOf("/")+1);break;case"authority":s=o.username??"",s+=o.password?":"+o.password:"",s+=s?"@":"",s+=o.hostname,s+=o.port?":"+o.port:"",s+="/",s=o.protocol+"//"+s;break;case"fragment":s=o.hash.substring(1);break;case"scheme":o.protocol?s=o.protocol.substring(0,o.protocol.length-1):s="";break;default:o[i]instanceof Function?s=o[i].bind(o):s=o[i];break}return s}})}var Me={error:(e,...t)=>{console.error("\u24C2\uFE0F ",e,...t)},info:(e,...t)=>{console.info("\u24C2\uFE0F ",e,...t)},group:e=>{console.group("\u24C2\uFE0F "+e)},groupEnd:e=>{console.groupEnd("\u24C2\uFE0F "+e)}};function l(e,...t){return Me.error(e,...t),new Error(e,...t)}function me(e){if(Array.isArray(e))return e.slice().map(me);if(e&&typeof e=="object")if(e.__proto__?.constructor==Object||!e.__proto__){let t=Object.assign({},e);return Object.keys(t).forEach(r=>{t[r]=me(e[r])}),t}else return e;return e}var Ge={};Pt(Ge,{Optional:()=>u,Recommended:()=>te,Required:()=>b,allOf:()=>Fe,anyOf:()=>X,assert:()=>k,disable:()=>Dr,enable:()=>Wr,error:()=>g,fails:()=>O,formatIssue:()=>vt,formatIssues:()=>Ct,instanceOf:()=>Y,issues:()=>Mr,not:()=>re,oneOf:()=>T,validEmail:()=>Ve,validURL:()=>_,warn:()=>It});var ze=!1;function Wr(){ze=!0}function Dr(){ze=!1}function G(e="",t){return(typeof e>"u"||e==null)&&(e=""),typeof t=="number"?`${e}[${t}]`:`${e}.${t}`}function Kt(e=""){if(Array.isArray(e))return e;if(!e)return[];let t=[],r=/(?:^|\.)([^.\[\]]+)|\[(\d+)\]/g,n;for(;n=r.exec(e);)typeof n[1]<"u"?t.push(n[1]):typeof n[2]<"u"&&t.push(Number(n[2]));return t}function $e(e=[]){return typeof e=="string"?e.startsWith(".")?e.slice(1):e:e.map((t,r)=>typeof t=="number"?`[${t}]`:`${r?".":""}${t}`).join("")}function je(e){return e===String?"string":e===Number?"number":e===Boolean?"boolean":e.name||"function"}function Ot(e,t=60){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function Jr(e){return`'${Ot(String(e).replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n"))}'`}function Ur(e){try{let r=JSON.stringify(e);if(typeof r=="string")return Ot(r)}catch{}let t=e?.constructor?.name;return t&&t!="Object"?t:Object.prototype.toString.call(e)}function ee(e){return typeof e=="string"?Jr(e):typeof e>"u"?"undefined":e===null?"null":typeof e=="function"?je(e):e instanceof RegExp?e.toString():typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):typeof e=="symbol"?e.toString():Ur(e)}function q(e){return e===String||e===Number||e===Boolean||typeof e=="function"?je(e):e instanceof RegExp?e.toString():Array.isArray(e)?"["+e.map(q).join(", ")+"]":ee(e)}function Lr(e){return e.map(q).join(", ")}function Nr(e,t,r){return e=="data and pattern are not equal"?`expected ${ee(r)}, found ${ee(t)}`:e=="data does not match pattern"||/^data\[\d+\] does not match pattern$/.test(e)?`expected ${q(r)}, found ${ee(t)}`:e=="data is undefined, should match pattern"?`missing; expected ${q(r)}`:e=="data is required"?"required":e=="data is an empty string, which is not allowed"?"empty string is not allowed":e=="data is not an object, pattern is"?"data is not an object":e=="data is not an instanceof pattern"?`expected instance of ${q(r)}, found ${ee(t)}`:e=="data does not match oneOf patterns"||e=="data does not match anyOf patterns"?`expected one of ${Lr(r)}, found ${ee(t)}`:e=="data matches pattern, when required not to"?`must not match ${q(r)}`:e}function vt(e,t={}){if(!e||typeof e!="object")return String(e);let r=e.pathString||$e(e.path||[])||"value";return`${t.indent??""}${r}: ${e.message}`}function Ct(e,t={}){if(!e)return!1;let r=t.indent??" - ";return(Array.isArray(e)?e:[e]).map(n=>vt(n,{...t,indent:r}))}function Hr(e){if(!e||typeof e!="object")return{path:[],pathString:"",message:String(e),expected:void 0,actual:void 0};let t=Kt(e.path),r=$e(t),n=e.actual??e.found,o=q(e.expected),i=Nr(e.message,n,e.expected);return{path:t,pathString:r,message:i,expected:o,actual:n}}function Be(e){if(!e)return[];let t=[];for(let r of Array.isArray(e)?e:[e])if(r){if(r&&typeof r=="object"&&r.problems){let n=Be(r.problems);if(n.length){t=t.concat(n);continue}}t.push(Hr(r))}return t}function k(e,t){if(ze){let r=O(e,t);if(r){let n=Be(r),i=`Assertions failed:
1
+ (()=>{var wr=Object.defineProperty;var Rt=(e,t)=>{for(var r in t)wr(e,r,{get:t[r],enumerable:!0})};var N={};Rt(N,{Client:()=>me,client:()=>C,deepClone:()=>ye,metroError:()=>l,request:()=>L,response:()=>Ne,url:()=>S});var ee="https://metro.muze.nl/details/";Symbol.metroProxy||(Symbol.metroProxy=Symbol("isProxy"));Symbol.metroSource||(Symbol.metroSource=Symbol("source"));var me=class e{clientOptions={url:S(typeof window<"u"?window.location:"https://localhost"),verbs:["get","post","put","delete","patch","head","options","query"]};static tracers={};constructor(...t){for(let r of t)if(typeof r=="string"||r instanceof String)this.clientOptions.url=S(this.clientOptions.url.href,r);else if(r instanceof e)Object.assign(this.clientOptions,r.clientOptions);else if(r instanceof Function)this.#e([r]);else if(r&&typeof r=="object")for(let n in r)n=="middlewares"?this.#e(r[n]):n=="url"?this.clientOptions.url=S(this.clientOptions.url.href,r[n]):typeof r[n]=="function"?this.clientOptions[n]=r[n](this.clientOptions[n],this.clientOptions):this.clientOptions[n]=r[n];for(let r of this.clientOptions.verbs)this[r]=async function(...n){return this.fetch(L(this.clientOptions,...n,{method:r.toUpperCase()}),xr(...n))}}#e(t){typeof t=="function"&&(t=[t]);let r=t.findIndex(n=>typeof n!="function");if(r>=0)throw l("metro.client: middlewares must be a function or an array of functions "+ee+"client/invalid-middlewares/",t[r]);Array.isArray(this.clientOptions.middlewares)||(this.clientOptions.middlewares=[]),this.clientOptions.middlewares=this.clientOptions.middlewares.concat(t)}fetch(t,r){if(t=L(t,r),!t.url)throw l("metro.client."+t.method.toLowerCase()+": Missing url parameter "+ee+"client/fetch-missing-url/",t);if(r||(r={}),typeof r!="object"||r instanceof String)throw l("metro.client.fetch: Invalid options parameter "+ee+"client/fetch-invalid-options/",r);r=Object.assign({},this.clientOptions,r);let n=Rr(t,r),o=Tr(this,r,n),i=this.clientOptions?.middlewares||[];return br(i,n,o)(t)}with(...t){return new e(ye(this.clientOptions),...t)}get location(){return this.clientOptions.url}};async function gr(e){e[Symbol.metroProxy]&&(e=e[Symbol.metroSource]);let t=await fetch(e);return Ne(t)}function br(e,t,r){let n;for(let o of[gr,...e])n=Sr(o,n,t,r);return n}function Sr(e,t,r,n){let o=r.tracers;return async function(i){he(o,"request",i,e,r);let s;try{s=await e(i,t,n)}catch(a){throw he(o,"error",a,i,e,r),a}return he(o,"response",s,e,r),s}}var Er=0,Ar=["trace","tracer","tracers"];function xr(...e){let t={};for(let r of e)if(Tt(r))for(let n of Ar)n in r&&(t[n]=r[n]);return t}function Rr(e,t={}){let r=Pr(t.trace||t.tracer||t.tracers),n=[];r?n=r.localTracers||[]:n=pe(t.trace).concat(pe(t.tracer)).concat(pe(t.tracers));let o=Object.values(me.tracers||{});return{__metroTraceContext:!0,id:"metro-trace-context-"+ ++Er,parent:r,request:e,options:t,globalTracers:o,localTracers:n,tracers:o.concat(n)}}function Pr(e){return e?e.context?.__metroTraceContext?e.context:e.__metroTraceContext?e:null:null}function pe(e){return!e||e.__metroTraceContext||e.context?.__metroTraceContext?[]:Array.isArray(e)?e.flatMap(pe):kr(e)?[e]:Tt(e)?Object.values(e).flatMap(pe):[]}function kr(e){return e&&typeof e=="object"&&["request","response","error","event","diagnostic","span","link","current"].some(t=>typeof e[t]=="function")}function Tr(e,t,r){let n=Kr(r);return Object.freeze({client:e,options:t,trace:n,fetch(o,i={}){return e.fetch(o,Object.assign({},i,{trace:n}))}})}function Kr(e){let t={__metroTraceContext:!0,context:e,event(r,n={}){he(e.tracers,"event",r,n,e)},diagnostic(r={}){he(e.tracers,"diagnostic",r,e)},current(){for(let r of e.tracers)if(typeof r.current=="function"){let n=r.current(e);if(n)return n}return{traceId:null,spanId:null}},async span(r,n,o={}){let i=e.tracers.find(s=>typeof s.span=="function");return i?Or(i,r,n,o,e):n()},link(r){let n=null;for(let o of e.tracers)typeof o.link=="function"&&(n=o.link(r,void 0,e)||n);return n},options(r={}){return Object.assign({},r,{trace:t})}};return t}function he(e,t,...r){for(let n of e)n&&typeof n[t]=="function"&&vr(n,t,r)}async function Or(e,t,r,n,o){let i=null,s=()=>(i||(i=(async()=>r())()),i);try{await e.span(t,s,n,o)}catch(a){He.error("metro: tracer.span() failed",a)}return s()}function vr(e,t,r){let n=o=>{He.error("metro: tracer."+t+"() failed",o)};try{let o=e[t].call(e,...r);typeof o?.then=="function"&&o.then(void 0,n)}catch(o){n(o)}}function Tt(e){return e&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function C(...e){return new me(...ye(e))}function Cr(e,t){let r=t||{};!r.url&&t.url&&(r.url=t.url);for(let n of["method","headers","body","mode","credentials","cache","redirect","referrer","referrerPolicy","integrity","keepalive","signal","priority","url"]){let o=e[n];if(!(typeof o>"u"||o==null))if(o?.[Symbol.metroProxy]&&(o=o[Symbol.metroSource]),typeof o=="function")r[n]=o(r[n],r);else if(n=="url")r.url=S(r.url,o);else if(n=="headers"){r.headers=new Headers(t.headers),o instanceof Headers||(o=new Headers(e.headers));for(let[i,s]of o.entries())r.headers.set(i,s)}else r[n]=o}return e instanceof Request&&e.data&&(r.body=e.data),r}function L(...e){let t={url:S(typeof window<"u"?window.location:"https://localhost/"),duplex:"half"};for(let o of e)typeof o=="string"||o instanceof URL||o instanceof URLSearchParams?t.url=S(t.url,o):o&&(o instanceof FormData||o instanceof ReadableStream||o instanceof Blob||o instanceof ArrayBuffer||o instanceof DataView)?t.body=o:o&&typeof o=="object"&&Object.assign(t,Cr(o,t));let r=new Request(t.url,t),n=t.body;return n&&typeof n=="object"&&!(n instanceof String)&&!(n instanceof ReadableStream)&&!(n instanceof Blob)&&!(n instanceof ArrayBuffer)&&!(n instanceof DataView)&&!(n instanceof FormData)&&!(n instanceof URLSearchParams)&&globalThis.ArrayBuffer&&ArrayBuffer.isView(n)&&typeof n.toString=="function"&&(t.body=n.toString({headers:r.headers}),r=new Request(t.url,t)),Object.freeze(r),new Proxy(r,{get(o,i){let s;switch(i){case Symbol.metroSource:s=o;break;case Symbol.metroProxy:s=!0;break;case"with":s=function(...a){return typeof n<"u"&&a.unshift({body:n}),L(o,...a)};break;case"data":s=n;break;default:o[i]instanceof Function?i==="clone"?s=function(){let a=o.clone();return typeof n<"u"&&!(typeof ReadableStream<"u"&&n instanceof ReadableStream)?L(a,{body:n}):L(a)}:s=o[i].bind(o):s=o[i];break}return s}})}function Pt(e,t){let r=t||{};!r.url&&t.url&&(r.url=t.url);for(let n of["status","statusText","headers","body","url","type","redirected"]){let o=e[n];typeof o>"u"||o==null||(o?.[Symbol.metroProxy]&&(o=o[Symbol.metroSource]),typeof o=="function"?r[n]=o(r[n],r):n=="url"?r.url=new URL(o,r.url||"https://localhost/"):r[n]=o)}return e instanceof Response&&e.data&&(r.body=e.data),r}function Ne(...e){let t={};for(let o of e)typeof o=="string"?t.body=o:o instanceof Response?Object.assign(t,Pt(o,t)):o&&typeof o=="object"&&(o instanceof FormData||o instanceof Blob||o instanceof ArrayBuffer||o instanceof DataView||o instanceof ReadableStream||o instanceof URLSearchParams||o instanceof String||typeof globalThis.TypedArray<"u"&&o instanceof globalThis.TypedArray?t.body=o:Object.assign(t,Pt(o,t)));let r;t.body&&(r=t.body),[101,204,205,304].includes(t.status)&&(t.body=null);let n=new Response(t.body,t);return Object.freeze(n),new Proxy(n,{get(o,i){let s;switch(i){case Symbol.metroProxy:s=!0;break;case Symbol.metroSource:s=o;break;case"with":s=function(...a){return Ne(o,...a)};break;case"data":s=r;break;case"ok":s=o.status>=200&&o.status<300;break;default:typeof o[i]=="function"?s=o[i].bind(o):s=o[i];break}return s}})}function kt(e,t){typeof t=="function"?t(e.searchParams,e):(t=new URLSearchParams(t),t.forEach((r,n)=>{e.searchParams.append(n,r)}))}function Ir(e,t){let r=e[Symbol.metroSource]||e;t instanceof URLSearchParams||(t=new URLSearchParams(t));let n=r.hash||"#";return n+="?"+t,S(r,{hash:n})}function S(...e){let t=["hash","fragment","host","hostname","href","password","pathname","port","protocol","username","search","searchParams","hashParams"],r=new URL("https://localhost/"),n=null;for(let o of e)if(typeof o=="string"||o instanceof String)r=new URL(o,r);else if(o instanceof URL||typeof Location<"u"&&o instanceof Location)r=new URL(o);else if(o instanceof URLSearchParams)kt(r,o);else if(o&&typeof o=="object")for(let i in o)switch(i){case"search":typeof o.search=="function"?o.search(r.search,r):r.search=new URLSearchParams(o.search);break;case"searchParams":kt(r,o.searchParams);break;default:if(!t.includes(i))throw l("metro.url: unknown url parameter "+ee+"url/unknown-param-name/",i);if(i=="fragment"){let s=o.fragment;s&&typeof s=="string"&&s[0]!="#"&&(s="#"+s),o.hash=s,i="hash"}else i=="hashParams"&&(n=o.hashParams);if(typeof o[i]=="function")o[i](r[i],r);else if(typeof o[i]=="string"||o[i]instanceof String||typeof o[i]=="number"||o[i]instanceof Number||typeof o[i]=="boolean"||o[i]instanceof Boolean)r[i]=""+o[i];else if(typeof o[i]=="object"&&o[i].toString)r[i]=o[i].toString();else throw l("metro.url: unsupported value for "+i+" "+ee+"url/unsupported-param-value/",e[i]);break}else throw l("metro.url: unsupported option value "+ee+"url/unsupported-option-value/",o);return n&&(r.hash||(r.hash="#"),typeof n=="string"?r.hash+=n:r=Ir(r,n)),Object.freeze(r),new Proxy(r,{get(o,i){let s;switch(i){case Symbol.metroProxy:s=!0;break;case Symbol.metroSource:s=o;break;case"with":s=function(...a){return S(o,...a)};break;case"filename":s=o.pathname.split("/").pop();break;case"folderpath":s=o.pathname.substring(0,o.pathname.lastIndexOf("/")+1);break;case"authority":s=o.username??"",s+=o.password?":"+o.password:"",s+=s?"@":"",s+=o.hostname,s+=o.port?":"+o.port:"",s+="/",s=o.protocol+"//"+s;break;case"fragment":s=o.hash.substring(1);break;case"scheme":o.protocol?s=o.protocol.substring(0,o.protocol.length-1):s="";break;default:o[i]instanceof Function?s=o[i].bind(o):s=o[i];break}return s}})}var He={error:(e,...t)=>{console.error("\u24C2\uFE0F ",e,...t)},info:(e,...t)=>{console.info("\u24C2\uFE0F ",e,...t)},group:e=>{console.group("\u24C2\uFE0F "+e)},groupEnd:e=>{console.groupEnd("\u24C2\uFE0F "+e)}};function l(e,...t){return He.error(e,...t),new Error(e,...t)}function ye(e){if(Array.isArray(e))return e.slice().map(ye);if(e&&typeof e=="object")if(e.__proto__?.constructor==Object||!e.__proto__){let t=Object.assign({},e);return Object.keys(t).forEach(r=>{t[r]=ye(e[r])}),t}else return e;return e}var Ve={};Rt(Ve,{Optional:()=>u,Recommended:()=>re,Required:()=>b,allOf:()=>Be,anyOf:()=>Y,assert:()=>k,disable:()=>Dr,enable:()=>Wr,error:()=>g,fails:()=>O,formatIssue:()=>vt,formatIssues:()=>Ct,instanceOf:()=>q,issues:()=>Mr,not:()=>ne,oneOf:()=>T,validEmail:()=>Fe,validURL:()=>w,warn:()=>It});var je=!1;function Wr(){je=!0}function Dr(){je=!1}function G(e="",t){return(typeof e>"u"||e==null)&&(e=""),typeof t=="number"?`${e}[${t}]`:`${e}.${t}`}function Kt(e=""){if(Array.isArray(e))return e;if(!e)return[];let t=[],r=/(?:^|\.)([^.\[\]]+)|\[(\d+)\]/g,n;for(;n=r.exec(e);)typeof n[1]<"u"?t.push(n[1]):typeof n[2]<"u"&&t.push(Number(n[2]));return t}function ze(e=[]){return typeof e=="string"?e.startsWith(".")?e.slice(1):e:e.map((t,r)=>typeof t=="number"?`[${t}]`:`${r?".":""}${t}`).join("")}function Me(e){return e===String?"string":e===Number?"number":e===Boolean?"boolean":e.name||"function"}function Ot(e,t=60){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function Jr(e){return`'${Ot(String(e).replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n"))}'`}function Ur(e){try{let r=JSON.stringify(e);if(typeof r=="string")return Ot(r)}catch{}let t=e?.constructor?.name;return t&&t!="Object"?t:Object.prototype.toString.call(e)}function te(e){return typeof e=="string"?Jr(e):typeof e>"u"?"undefined":e===null?"null":typeof e=="function"?Me(e):e instanceof RegExp?e.toString():typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):typeof e=="symbol"?e.toString():Ur(e)}function X(e){return e===String||e===Number||e===Boolean||typeof e=="function"?Me(e):e instanceof RegExp?e.toString():Array.isArray(e)?"["+e.map(X).join(", ")+"]":te(e)}function Lr(e){return e.map(X).join(", ")}function Nr(e,t,r){return e=="data and pattern are not equal"?`expected ${te(r)}, found ${te(t)}`:e=="data does not match pattern"||/^data\[\d+\] does not match pattern$/.test(e)?`expected ${X(r)}, found ${te(t)}`:e=="data is undefined, should match pattern"?`missing; expected ${X(r)}`:e=="data is required"?"required":e=="data is an empty string, which is not allowed"?"empty string is not allowed":e=="data is not an object, pattern is"?"data is not an object":e=="data is not an instanceof pattern"?`expected instance of ${X(r)}, found ${te(t)}`:e=="data does not match oneOf patterns"||e=="data does not match anyOf patterns"?`expected one of ${Lr(r)}, found ${te(t)}`:e=="data matches pattern, when required not to"?`must not match ${X(r)}`:e}function vt(e,t={}){if(!e||typeof e!="object")return String(e);let r=e.pathString||ze(e.path||[])||"value";return`${t.indent??""}${r}: ${e.message}`}function Ct(e,t={}){if(!e)return!1;let r=t.indent??" - ";return(Array.isArray(e)?e:[e]).map(n=>vt(n,{...t,indent:r}))}function Hr(e){if(!e||typeof e!="object")return{path:[],pathString:"",message:String(e),expected:void 0,actual:void 0};let t=Kt(e.path),r=ze(t),n=e.actual??e.found,o=X(e.expected),i=Nr(e.message,n,e.expected);return{path:t,pathString:r,message:i,expected:o,actual:n}}function $e(e){if(!e)return[];let t=[];for(let r of Array.isArray(e)?e:[e])if(r){if(r&&typeof r=="object"&&r.problems){let n=$e(r.problems);if(n.length){t=t.concat(n);continue}}t.push(Hr(r))}return t}function k(e,t){if(je){let r=O(e,t);if(r){let n=$e(r),i=`Assertions failed:
2
2
  `+Ct(n).join(`
3
- `);throw console.error("\u{1F170}\uFE0F "+i),new Error(i,{cause:{problems:r,issues:n,source:e}})}}}function u(e){return function(r,n,o){if(typeof r<"u"&&r!=null&&typeof e<"u")return O(r,e,n,o)}}function b(e){return function(r,n,o){return r==null||typeof r>"u"?g("data is required",r,e||"any value",o):typeof e<"u"?O(r,e,n,o):!1}}function te(e){return function(r,n,o){return r==null||typeof r>"u"?(It("data does not contain recommended value",r,e,o),!1):O(r,e,n,o)}}function T(...e){return function(r,n,o){for(let i of e)if(!O(r,i,n,o))return!1;return g("data does not match oneOf patterns",r,e,o)}}function X(...e){return function(r,n,o){if(!Array.isArray(r))return g("data is not an array",r,"anyOf",o);for(let[i,s]of r.entries()){let a=G(o,i);if(T(...e)(s,n,a))return g("data does not match anyOf patterns",s,e,a)}return!1}}function Fe(...e){return function(r,n,o){let i=[];for(let s of e)i=i.concat(O(r,s,n,o));if(i=i.filter(Boolean),i.length)return g("data does not match all given patterns",r,e,o,i)}}function _(e,t,r){try{e instanceof URL&&(e=e.href);let n=new URL(e);if(n.href!=e&&!(n.href+"/"==e||n.href==e+"/"))return g("data is not a valid url",e,"validURL",r)}catch{return g("data is not a valid url",e,"validURL",r)}}function Ve(e,t,r){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e))return g("data is not a valid email",e,"validEmail",r)}function Y(e){return function(r,n,o){if(!(r instanceof e))return g("data is not an instanceof pattern",r,e,o)}}function re(e){return function(r,n,o){if(!O(r,e,n,o))return g("data matches pattern, when required not to",r,e,o)}}function Mr(e,t,r){let n=O(e,t,r);return n?Be(n):!1}function O(e,t,r,n=""){typeof r>"u"&&(r=e);let o=[];if(t===Boolean)typeof e!="boolean"&&!(e instanceof Boolean)&&o.push(g("data is not a boolean",e,t,n));else if(t===Number)typeof e!="number"&&!(e instanceof Number)&&o.push(g("data is not a number",e,t,n));else if(t===String)typeof e!="string"&&!(e instanceof String)&&o.push(g("data is not a string",e,t,n)),e==""&&o.push(g("data is an empty string, which is not allowed",e,t,n));else if(t instanceof RegExp)if(Array.isArray(e)){let i=e.findIndex((s,a)=>O(s,t,r,G(n,a)));i>-1&&o.push(g("data["+i+"] does not match pattern",e[i],t,G(n,i)))}else typeof e>"u"?o.push(g("data is undefined, should match pattern",e,t,n)):t.test(e)||o.push(g("data does not match pattern",e,t,n));else if(t instanceof Function){let i=t(e,r,n);i&&(Array.isArray(i)?o=o.concat(i):o.push(i))}else if(Array.isArray(t))if(!Array.isArray(e))o.push(g("data is not an array",e,[],n));else for(let i of t)for(let s of e.keys()){let a=O(e[s],i,r,G(n,s));Array.isArray(a)?o=o.concat(a):a&&o.push(a)}else if(t&&typeof t=="object")if(Array.isArray(e)){let i=e.findIndex((s,a)=>O(s,t,r,G(n,a)));i>-1&&o.push(g("data["+i+"] does not match pattern",e[i],t,G(n,i)))}else if(!e||typeof e!="object")o.push(g("data is not an object, pattern is",e,t,n));else if(e instanceof URLSearchParams&&(e=Object.fromEntries(e)),t instanceof Function){let i=O(e,t,r,n);i&&(o=o.concat(i))}else for(let[i,s]of Object.entries(t)){let a=O(e[i],s,r,G(n,i));a&&(o=o.concat(a))}else t!=e&&o.push(g("data and pattern are not equal",e,t,n));return o.length?o:!1}function g(e,t,r,n="",o){let i=Kt(n),s={path:n,pathString:$e(i),pathParts:i,message:e,found:t,expected:r};return o&&(s.problems=o),s}function It(e,t,r,n){console.warn("\u{1F170}\uFE0F Assert: "+n,e,r,t)}globalThis.assert={...Ge};function Wt(e){let t,r;if(typeof localStorage<"u")t={get:()=>localStorage.getItem("metro/state:"+e),set:n=>localStorage.setItem("metro/state:"+e,n),has:()=>localStorage.getItem("metro/state:"+e)!==null,delete:()=>localStorage.removeItem("metro/state:"+e)},r={get:n=>JSON.parse(localStorage.getItem(e+":"+n)),set:(n,o)=>localStorage.setItem(e+":"+n,JSON.stringify(o)),has:n=>localStorage.getItem(e+":"+n)!==null,delete:n=>localStorage.removeItem(e+":"+n)};else{let n=new Map;t={get:()=>n.get("metro/state:"+e),set:o=>n.set("metro/state:"+e,o),has:()=>n.has("metro/state:"+e),delete:()=>n.delete("metro/state:"+e)},r=new Map}return{state:t,tokens:r}}var Ae=new Map,jr=new Map([["bearer","Bearer"],["dpop","DPoP"]]),zr=new Set(["none","client_secret_post","client_secret_basic"]);function Xe(e){let t={client:I(),force_authorization:!1,site:"default",oauth2_configuration:{authorization_endpoint:"/authorize",token_endpoint:"/token",redirect_uri:globalThis.document?.location.href,grant_type:"authorization_code",code_verifier:Ye(64)},authorize_callback:async c=>(window.location.href!=c.href&&window.location.replace(c.href),!1)};k(e,{});let r=Object.assign({},t.oauth2_configuration,e?.oauth2_configuration);e=Object.assign({},t,e),e.oauth2_configuration=r;let n=e.tokens??"site:"+e.site,o=Wt(e.site);e.tokens||(e.tokens=o.tokens),e.state||(e.state=o.state),k(e,{oauth2_configuration:{client_id:b(/.+/),grant_type:"authorization_code",authorization_endpoint:b(_),token_endpoint:b(_),redirect_uri:b(_)}});for(let c in r)switch(c){case"access_token":case"authorization_code":case"refresh_token":e.tokens.set(c,$r(c,r[c]));break}return async function(c,f){if(e.force_authorization)return i(c,f);let m=await f(c);return m.ok||!Dt(m)?m:i(c,f)};async function i(c,f,m={}){a();let w=e.tokens.get("access_token"),R=e.tokens.get("refresh_token"),v=Xr(w);if(!w||v&&!R){if(!await s(p))throw qe(c);return i(c,f)}else if(v&&R){if(!await s(d))throw qe(c);return i(c,f)}else{let le=L(c,{headers:{Authorization:w.type+" "+w.value}}),Je=await f(le);if(!Dt(Je)||m.handledRejectedToken)return Je;if(e.tokens.get("access_token")?.value!==w.value)return i(c,f,{handledRejectedToken:!0});e.tokens.delete("access_token");let Se=p;if(R&&(Se=d),!await s(Se))throw qe(c);return i(c,f,{handledRejectedToken:!0})}}function s(c){if(!Ae.has(n)){let f=c().finally(()=>{Ae.delete(n)});Ae.set(n,f)}return Ae.get(n)}function a(){if(typeof window<"u"&&window?.location){let c=S(window.location),f,m,w;if(c.searchParams.has("code")||c.searchParams.has("error"))w=c.searchParams,c=c.with({search:""}),history.pushState({},"",c.href);else if(c.hash){let R=c.hash.substr(1);w=new URLSearchParams("?"+R),c=c.with({hash:""}),history.pushState({},"",c.href)}if(w){if(P(w.get("iss")),w.has("error"))throw l("oauth2mw: authorization failed: "+w.get("error")+(w.get("error_description")?" ("+w.get("error_description")+")":""));f=w.get("code"),m=w.get("state"),D(m),f&&e.tokens.set("authorization_code",f)}}}async function p(){if(r.grant_type==="authorization_code"&&!e.tokens.has("authorization_code")){let w=await y();if(!e.authorize_callback||typeof e.authorize_callback!="function")throw l("oauth2mw: oauth2 with grant_type:authorization_code requires a callback function in client options.authorize_callback");let R=await e.authorize_callback(w);if(R)K(R);else return!1}let c=h(),f=await e.client.post(c);if(!f.ok){let w=await f.text();throw l("OAuth2mw: fetch access_token: "+f.status+": "+f.statusText+" ("+w+")",{cause:c})}let m=await f.json();return V(m),e.tokens.delete("authorization_code"),m}async function d(){let c=h("refresh_token"),f=await e.client.post(c);if(!f.ok){let w=await f.text();throw l("OAuth2mw: refresh access_token: "+f.status+": "+f.statusText+" ("+w+")",{cause:c})}let m=await f.json();return V(m),m}async function y(){if(!r.authorization_endpoint)throw l("oauth2mw: Missing options.oauth2_configuration.authorization_endpoint");let c=S(r.authorization_endpoint,{hash:""});k(r,{client_id:/.+/,redirect_uri:/.+/,scope:/.*/});let f={response_type:"code",client_id:r.client_id,redirect_uri:r.redirect_uri,state:r.state||Qr(40)};return r.response_type&&(f.response_type=r.response_type),r.response_mode&&(f.response_mode=r.response_mode),e.state.set(f.state),r.code_verifier&&(e.tokens.set("code_verifier",r.code_verifier),f.code_challenge=await Zr(r.code_verifier),f.code_challenge_method="S256"),r.scope&&(f.scope=r.scope),r.prompt&&(f.prompt=r.prompt),r.login_hint&&(f.login_hint=r.login_hint),r.nonce&&(f.nonce=r.nonce),S(c,{search:f})}function h(c=null){if(k(r,{client_id:/.+/,redirect_uri:/.+/}),!r.token_endpoint)throw l("oauth2mw: Missing options.endpoints.token url");let f=S(r.token_endpoint,{hash:""}),m={grant_type:c||r.grant_type},w={};switch(A(m,w),r.scope&&(m.scope=r.scope),m.grant_type){case"authorization_code":m.redirect_uri=r.redirect_uri,m.code=e.tokens.get("authorization_code");let R=e.tokens.get("code_verifier");R&&(m.code_verifier=R);break;case"client_credentials":break;case"refresh_token":m.refresh_token=qr(e.tokens.get("refresh_token"));break;default:throw new Error("Unknown grant_type: "+m.grant_type)}return L(f,{method:"POST",headers:w,body:new URLSearchParams(m)})}function A(c,f){let m=Fr(r);if(m==="none"){c.client_id=r.client_id;return}if(!r.client_secret)throw l("oauth2mw: token_endpoint_auth_method "+m+" requires oauth2_configuration.client_secret");if(m==="client_secret_post"){c.client_id=r.client_id,c.client_secret=r.client_secret;return}if(m==="client_secret_basic"){f.Authorization=Vr(r.client_id,r.client_secret);return}}function K(c){let f=c;if(c&&typeof c=="object"){if(P(c.iss),c.error)throw l("oauth2mw: authorization failed: "+c.error);D(c.state),f=c.authorization_code||c.code}if(!f)throw l("oauth2mw: authorization callback did not return an authorization code");e.tokens.set("authorization_code",f)}function P(c){if(r.issuer){if(!c){if(r.authorization_response_iss_parameter_supported)throw l("oauth2mw: authorization response is missing iss, expected "+r.issuer);return}if(c!==r.issuer)throw l("oauth2mw: authorization response is from issuer "+c+", expected "+r.issuer)}}function D(c){let f=e.state.get();if(!c||c!==f)throw l("oauth2mw: authorization state mismatch")}function V(c){let f=Br(c,r.token_type);e.tokens.set("access_token",f),c.refresh_token&&e.tokens.set("refresh_token",{value:c.refresh_token})}}function Dt(e){if(!e)return!1;let t=Qe(e.headers?.get("WWW-Authenticate"));return e.status===400?t?.error==="invalid_token":t?.error==="insufficient_scope"?!1:e.status===401}function $r(e,t){return e==="access_token"&&t&&typeof t=="object"?t:e==="access_token"?{value:t,type:"Bearer",expires:null}:t}function Br(e,t){if(!e||typeof e!="object")throw l("OAuth2mw: token endpoint did not return a JSON object");if(!e.access_token)throw l("OAuth2mw: token response did not include access_token");if(!e.token_type)throw l("OAuth2mw: token response did not include token_type");let r=Jt(e.token_type);if(t&&r!==Jt(t))throw l("OAuth2mw: token endpoint returned a "+r+" token, but "+t+" is required");return{value:e.access_token,expires:e.expires_in===void 0?null:Yr(e.expires_in),type:r,scope:e.scope}}function Jt(e){let t=jr.get(String(e).toLowerCase());if(!t)throw l("OAuth2mw: unsupported token_type "+e);return t}function Fr(e){let t=e.token_endpoint_auth_method||(e.client_secret?"client_secret_post":"none");if(!zr.has(t))throw l("oauth2mw: unsupported token_endpoint_auth_method "+t);return t}function Vr(e,t){let r=Ut(e)+":"+Ut(t);return"Basic "+Gr(r)}function Ut(e){return encodeURIComponent(e).replace(/%20/g,"+")}function Gr(e){return typeof btoa=="function"?btoa(e):Buffer.from(e,"binary").toString("base64")}function qr(e){return e&&typeof e=="object"?e.value:e}function Xr(e){if(!e)return!0;if(!e.expires)return!1;let t=new Date(e.expires);return new Date().getTime()>t.getTime()}function Yr(e){if(e instanceof Date)return new Date(e.getTime());if(typeof e=="number"){let t=new Date;return t.setSeconds(t.getSeconds()+e),t}throw new TypeError("Unknown expires type "+e)}function Ye(e=64){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),Ze(t)}async function Zr(e){let r=new TextEncoder().encode(e),n=await globalThis.crypto.subtle.digest("SHA-256",r);return Ze(n)}function Ze(e){let t=Array.from(new Uint8Array(e),r=>String.fromCharCode(r)).join("");return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Qr(e){let t=new Uint8Array(Math.ceil(e*3/4)+1);if(globalThis.crypto?.getRandomValues)return globalThis.crypto.getRandomValues(t),Ze(t).slice(0,e);let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="",o=0;for(;o<e;)n+=r.charAt(Math.floor(Math.random()*r.length)),o++;return n}function qe(e){let t=new Error("oauth2mw: authorization was not completed for "+e.url+"; no access token was obtained");return t.code="authorization_not_completed",t.request=e,t}function Lt(){let e=new URL(document.location.href);if(!e.searchParams.has("code")){if(e.hash){let t=e.hash.substr(1);if(new URLSearchParams("?"+t).has("code"))return!0}return!1}return!0}function Qe(e){if(!e||typeof e!="string")return null;let t=e.trim(),r=t.search(/\s/),n=r<0?t:t.slice(0,r),o=r<0?"":t.slice(r+1);if(!["bearer","dpop"].includes(n.toLowerCase()))return null;let i={scheme:n},s=/([A-Za-z][A-Za-z0-9_-]*)=("(?:[^"\\]|\\.)*"|[^,\s]*)/g,a;for(;a=s.exec(o);){let p=a[2];p.startsWith('"')&&p.endsWith('"')&&(p=p.slice(1,-1).replace(/\\"/g,'"')),i[a[1]]=p}return i}var tn=new TextEncoder,rn=new TextDecoder;function xe(e){return typeof e=="string"?tn.encode(e):rn.decode(e)}function Nt(e){if(typeof e.modulusLength!="number"||e.modulusLength<2048)throw new tt(`${e.name} modulusLength must be at least 2048 bits`)}function nn(e){switch(e.algorithm.name){case"ECDSA":return{name:e.algorithm.name,hash:"SHA-256"};case"RSA-PSS":return Nt(e.algorithm),{name:e.algorithm.name,saltLength:32};case"RSASSA-PKCS1-v1_5":return Nt(e.algorithm),{name:e.algorithm.name};case"Ed25519":return{name:e.algorithm.name}}throw new z}async function on(e,t,r){if(r.usages.includes("sign")===!1)throw new TypeError('private CryptoKey instances used for signing assertions must include "sign" in their "usages"');let n=`${Pe(xe(JSON.stringify(e)))}.${Pe(xe(JSON.stringify(t)))}`,o=Pe(await crypto.subtle.sign(nn(r),r,xe(n)));return`${n}.${o}`}var et;Uint8Array.prototype.toBase64?et=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):et=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let r=[];for(let n=0;n<t.byteLength;n+=32768)r.push(String.fromCharCode.apply(null,t.subarray(n,n+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};function Pe(e){return et(e)}var z=class extends Error{constructor(t){var r;super(t??"operation not supported"),this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}},tt=class extends Error{constructor(t){var r;super(t),this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}};function sn(e){if(e.algorithm.hash.name==="SHA-256")return"PS256";throw new z("unsupported RsaHashedKeyAlgorithm hash name")}function an(e){if(e.algorithm.hash.name==="SHA-256")return"RS256";throw new z("unsupported RsaHashedKeyAlgorithm hash name")}function cn(e){if(e.algorithm.namedCurve==="P-256")return"ES256";throw new z("unsupported EcKeyAlgorithm namedCurve")}function un(e){switch(e.algorithm.name){case"RSA-PSS":return sn(e);case"RSASSA-PKCS1-v1_5":return an(e);case"ECDSA":return cn(e);case"Ed25519":return"Ed25519";default:throw new z("unsupported CryptoKey algorithm name")}}function Ht(e){return e instanceof CryptoKey}function fn(e){return Ht(e)&&e.type==="private"}function ln(e){return Ht(e)&&e.type==="public"}function dn(){return Math.floor(Date.now()/1e3)}async function rt(e,t,r,n,o,i){let s=e?.privateKey,a=e?.publicKey;if(!fn(s))throw new TypeError('"keypair.privateKey" must be a private CryptoKey');if(!ln(a))throw new TypeError('"keypair.publicKey" must be a public CryptoKey');if(a.extractable!==!0)throw new TypeError('"keypair.publicKey.extractable" must be true');if(typeof t!="string")throw new TypeError('"htu" must be a string');if(typeof r!="string")throw new TypeError('"htm" must be a string');if(n!==void 0&&typeof n!="string")throw new TypeError('"nonce" must be a string or undefined');if(o!==void 0&&typeof o!="string")throw new TypeError('"accessToken" must be a string or undefined');if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new TypeError('"additional" must be an object');return on({alg:un(s),typ:"dpop+jwt",jwk:await pn(a)},Object.assign(Object.assign({},i),{iat:dn(),jti:crypto.randomUUID(),htm:r,nonce:n,htu:t,ath:o?Pe(await crypto.subtle.digest("SHA-256",xe(o))):void 0}),s)}async function pn(e){let{kty:t,e:r,n,x:o,y:i,crv:s}=await crypto.subtle.exportKey("jwk",e);return{kty:t,crv:s,e:r,n,x:o,y:i}}async function Mt(e,t){var r;let n;if(typeof e!="string"||e.length===0)throw new TypeError('"alg" must be a non-empty string');switch(e){case"PS256":n={name:"RSA-PSS",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"RS256":n={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"ES256":n={name:"ECDSA",namedCurve:"P-256"};break;case"Ed25519":n={name:"Ed25519"};break;default:throw new z}return crypto.subtle.generateKey(n,(r=t?.extractable)!==null&&r!==void 0?r:!1,["sign","verify"])}function nt(){return new Promise((e,t)=>{let r=globalThis.indexedDB.open("metro",1);r.onupgradeneeded=()=>r.result.createObjectStore("keyPairs",{keyPath:"domain"}),r.onerror=n=>{t(n)},r.onsuccess=n=>{let o=n.target.result;e({set:function(i,s){return new Promise((a,p)=>{let d=o.transaction("keyPairs","readwrite",{durability:"strict"}),y=d.objectStore("keyPairs");d.oncomplete=()=>{a()},d.onerror=p,y.put(i,s)})},get:function(i){return new Promise((s,a)=>{let p=o.transaction("keyPairs","readonly"),y=p.objectStore("keyPairs").get(i);y.onsuccess=()=>{s(y.result)},y.onerror=a,p.onerror=a})},clear:function(){return new Promise((i,s)=>{let a=o.transaction("keyPairs","readwrite"),d=a.objectStore("keyPairs").clear();d.onsuccess=()=>{i()},d.onerror=s,a.onerror=s})}})}})}var zt=new Map;function ot(e){return k(e,{site:b(_),token_endpoint:b(_),dpop_signing_alg_values_supported:u([])}),async(n,o)=>{let i=await mn(e.site),s=S(n.url).origin,a=await o(await r(n,i));return jt(s,a),t(n)&&await _n(a)&&(a=await o(await r(n,i)),jt(s,a)),a};function t(n){return n.url.startsWith(e.token_endpoint)||wn(n.headers.get("Authorization"))}async function r(n,o){if(!t(n))return n;let i=zt.get(S(n.url).origin),s=yn(n.url);if(n.url.startsWith(e.token_endpoint)){let d=await rt(o,s,n.method,i);return n.with({headers:{DPoP:d}})}let a=n.headers.get("Authorization").split(" ")[1],p=await rt(o,s,n.method,i,a);return n.with({headers:{Authorization:"DPoP "+a,DPoP:p}})}}async function mn(e){let t=await nt(),r=await t.get(e);if(!r){let n=await Mt("ES256");r={domain:e,keyPair:n},await t.set(r)}return r.keyPair}function yn(e){let t=new URL(e);return t.search="",t.hash="",t.href}function jt(e,t){let r=t.headers.get("DPoP-Nonce");r&&zt.set(e,r)}async function _n(e){return e.headers.get("DPoP-Nonce")?e.status==401?Qe(e.headers.get("WWW-Authenticate"))?.error=="use_dpop_nonce":e.status==400?(await e.clone().json().catch(()=>null))?.error=="use_dpop_nonce":!1:!1}function wn(e){return/^DPoP\s/i.test(e||"")}function H(e){return e=Object.assign({contentType:"application/json",reviver:null,replacer:null,space:""},e),async function(r,n){if(r.headers.get("Accept")||(r=r.with({headers:{Accept:e.accept??e.contentType}})),r.method!=="GET"&&r.method!=="HEAD"&&r.data&&typeof r.data=="object"&&!(r.data instanceof ReadableStream)){let i=r.headers.get("Content-Type");(!i||Sn(i))&&(r=r.with({headers:{"Content-Type":e.contentType}})),$t(r.headers.get("Content-Type"))&&(r=r.with({body:JSON.stringify(r.data,e.replacer,e.space)}))}let o=await n(r);if(o&&$t(o.headers?.get("Content-Type"))){let s=await o.clone().text();if(s==="")return o;try{let a=JSON.parse(s,e.reviver);return o.with({body:a})}catch(a){if(!o.ok)return o;throw gn(r,o,a)}}return o}}function gn(e,t,r){let n="jsonmw: could not parse "+t.headers.get("Content-Type")+" response from "+e.url,o=new Error(n,{cause:r});return o.request=e,o.response=t,o}var bn=/^application\/([a-zA-Z0-9\-_]+\+)?json\b/;function $t(e){return bn.exec(e)}function Sn(e){return/^text\/plain\b/.exec(e)}function M(e){return async function(r,n){let o=await n(r);if(!o.ok)if(e&&typeof e[o.status]=="function")o=e[o.status].apply(o,r);else throw new Error(o.status+": "+o.statusText,{cause:o});return o}}var ye=(...e)=>(t,r)=>e.filter(n=>r.hasOwnKey(n)).length>0?!1:g("root data must have all of",r,e),$=(...e)=>t=>Array.isArray(t)&&e.filter(r=>!t.includes(r)).length==0?!1:g("data must be an array which includes",t,e);var J=["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"],Re=["none","client_secret_post","client_secret_basic","client_secret_jwt","private_key_jwt"];async function ne(e={}){k(e,{client:u(Y(I().constructor)),issuer:b(_)});let t={client:I().with(M()).with(H()),requireDynamicRegistration:!1};e=Object.assign({},t,e),e.client=e.client.with(M()).with(H()),ke("issuer",e.issuer);function r(a){return Ft(a)?!1:g("url must use https",a)}let n={issuer:b(Fe(e.issuer,r)),authorization_endpoint:b(_),token_endpoint:b(_),userinfo_endpoint:te(_),jwks_uri:b(_),registration_endpoint:e.requireDynamicRegistration?b(_):te(_),scopes_supported:te($("openid")),response_types_supported:e.requireDynamicRegistration?b($("code","id_token","id_token token")):b([]),response_modes_supported:u([]),grant_types_supported:e.requireDynamicRegistration?u($("authorization_code")):u([]),acr_values_supported:u([]),subject_types_supported:b([]),id_token_signing_alg_values_supported:b($("RS256")),id_token_encryption_alg_values_supported:u([]),id_token_encryption_enc_values_supported:u([]),userinfo_signing_alg_values_supported:u([]),userinfo_encryption_alg_values_supported:u([]),userinfo_encryption_enc_values_supported:u([]),request_object_signing_alg_values_supported:u($("RS256")),request_object_encryption_alg_values_supported:u([]),request_object_encryption_enc_values_supported:u([]),token_endpoint_auth_methods_supported:u(X(...Re)),token_endpoint_auth_signing_alg_values_supported:u($("RS256"),re($("none"))),display_values_supported:u(X("page","popup","touch","wap")),claim_types_supported:u(X("normal","aggregated","distributed")),claims_supported:te([]),service_documentation:u(_),claims_locales_supported:u([]),ui_locales_supported:u([]),claims_parameter_supported:u(Boolean),request_parameter_supported:u(Boolean),request_uri_parameter_supported:u(Boolean),op_policy_uri:u(_),op_tos_uri:u(_)},o=S(e.issuer,".well-known/openid-configuration"),s=(await e.client.get(o)).data;return k(s,n),An(s,e.issuer),s}var En=["authorization_endpoint","token_endpoint","jwks_uri"];function An(e,t){if(!e||typeof e!="object")throw l("metro.oidc.discovery: openid-configuration for "+t+" is not a JSON object");if(!xn(e.issuer,t))throw l("metro.oidc.discovery: openid-configuration is for issuer "+e.issuer+", expected "+t);ke("issuer",e.issuer);for(let r of En){if(!e[r])throw l("metro.oidc.discovery: openid-configuration for "+t+" has no "+r);ke(r,e[r])}e.registration_endpoint&&ke("registration_endpoint",e.registration_endpoint)}function xn(e,t){return typeof e!="string"?!1:Bt(e)===Bt(String(t))}function Bt(e){return e.replace(/\/$/,"")}function ke(e,t){if(!Ft(t))throw l("metro.oidc.discovery: "+e+" must use https: "+t)}function Ft(e){let t;try{t=new URL(String(e))}catch{return!1}return t.protocol=="https:"?!0:t.protocol=="http:"&&Pn(t.hostname)}function Pn(e){return e=="localhost"||e.endsWith(".localhost")||e=="127.0.0.1"||e=="[::1]"}async function oe(e){let t={redirect_uris:b([_]),response_types:u([]),grant_types:u(X("authorization_code","refresh_token")),application_type:u(T("native","web")),contacts:u([Ve]),client_name:u(String),logo_uri:u(_),client_uri:u(_),policy_uri:u(_),tos_uri:u(_),jwks_uri:u(_,re(ye("jwks"))),jwks:u(_,re(ye("jwks_uri"))),sector_identifier_uri:u(_),subject_type:u(String),id_token_signed_response_alg:u(T(...J)),id_token_encrypted_response_alg:u(T(...J)),id_token_encrypted_response_enc:u(T(...J),ye("id_token_encrypted_response_alg")),userinfo_signed_response_alg:u(T(...J)),userinfo_encrypted_response_alg:u(T(...J)),userinfo_encrypted_response_enc:u(T(...J),ye("userinfo_encrypted_response_alg")),request_object_signing_alg:u(T(...J)),request_object_encryption_alg:u(T(...J)),request_object_encryption_enc:u(T(...J)),token_endpoint_auth_method:u(T(...Re)),token_endpoint_auth_signing_alg:u(T(...J)),default_max_age:u(Number),require_auth_time:u(Boolean),default_acr_values:u([String]),initiate_login_uri:u([_]),request_uris:u([_])};k(e,{client:u(Y(I().constructor)),registration_endpoint:_,client_info:t});let r={client:I().with(M()).with(H()),client_info:{redirect_uris:[globalThis.document?.location.href]}};e=Object.assign({},r,e),e.client=e.client.with(M()).with(H()),e.client_info||(e.client_info={}),e.client_info.redirect_uris||(e.client_info.redirect_uris=[globalThis.document?.location.href]);let n=await e.client.post(e.registration_endpoint,{body:e.client_info}),o=n.data;if(!o.client_id)throw l("metro.oidc: Error: dynamic registration of client failed, no client_id returned",n);return e.client_info=Object.assign(e.client_info,o),e.client_info}function Z(e){let t;if(typeof localStorage<"u")t={get:r=>JSON.parse(localStorage.getItem("metro/oidc:"+e+":"+r)),set:(r,n)=>localStorage.setItem("metro/oidc:"+e+":"+r,JSON.stringify(n)),has:r=>localStorage.getItem("metro/oidc:"+e+":"+r)!==null};else{let r=new Map;t={get:n=>JSON.parse(r.get("metro/oidc:"+e+":"+n)||null),set:(n,o)=>r.set("metro/oidc:"+e+":"+n,JSON.stringify(o)),has:n=>r.has("metro/oidc:"+e+":"+n)}}return t}var _e=new TextEncoder,j=new TextDecoder,Uo=2**32;function Vt(...e){let t=e.reduce((o,{length:i})=>o+i,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function Te(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function Gt(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function B(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:j.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=j.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return Gt(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}var F=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),ie=(e,t)=>e.name===t;function Rn(e){return parseInt(e.name.slice(4),10)}function it(e,t){if(Rn(e.hash)!==t)throw F(`SHA-${t}`,"algorithm.hash")}function kn(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Tn(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function qt(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ie(e.algorithm,"HMAC"))throw F("HMAC");it(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!ie(e.algorithm,"RSASSA-PKCS1-v1_5"))throw F("RSASSA-PKCS1-v1_5");it(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!ie(e.algorithm,"RSA-PSS"))throw F("RSA-PSS");it(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!ie(e.algorithm,"Ed25519"))throw F("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!ie(e.algorithm,t))throw F(t);break}case"ES256":case"ES384":case"ES512":{if(!ie(e.algorithm,"ECDSA"))throw F("ECDSA");let n=kn(t);if(e.algorithm.namedCurve!==n)throw F(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Tn(e,r)}function Xt(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Yt=(e,...t)=>Xt("Key must be ",e,...t),st=(e,t,...r)=>Xt(`Key for the ${e} algorithm must be `,t,...r);var W=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},C=class extends W{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},we=class extends W{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},Ke=class extends W{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},x=class extends W{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"};var E=class extends W{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},se=class extends W{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"};var ge=class extends W{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},Oe=class extends W{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r)}},ve=class extends W{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r)}};var Ce=class extends W{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r)}};var at=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},ct=e=>e?.[Symbol.toStringTag]==="KeyObject",ut=e=>at(e)||ct(e);function ft(e,t,r){try{return B(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}var Kn=e=>typeof e=="object"&&e!==null;function U(e){if(!Kn(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Zt(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let i of o){if(r.has(i))return!1;r.add(i)}}return!0}var be=e=>U(e)&&typeof e.kty=="string",Qt=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),er=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,tr=e=>e.kty==="oct"&&typeof e.k=="string";function vn(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function Cn(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new x(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function In(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Yt(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return qt(t,e,r),t}async function rr(e,t,r,n){let o=await In(e,t,"verify");vn(e,o);let i=Cn(e,o.algorithm);try{return await crypto.subtle.verify(i,o,r,n)}catch{return!1}}var Ie='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function Wn(e){let t,r;switch(e.kty){case"AKP":{switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new x(Ie)}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new x(Ie)}break}case"EC":{switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new x(Ie)}break}case"OKP":{switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new x(Ie)}break}default:throw new x('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function ae(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=Wn(e),n={...e};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!(e.d||e.priv),e.key_ops??r)}var ce="given KeyObject instance cannot be used for this algorithm",ue,nr=async(e,t,r,n=!1)=>{ue||=new WeakMap;let o=ue.get(e);if(o?.[r])return o[r];let i=await ae({...t,alg:r});return n&&Object.freeze(e),o?o[r]=i:ue.set(e,{[r]:i}),i},Dn=(e,t)=>{ue||=new WeakMap;let r=ue.get(e);if(r?.[t])return r[t];let n=e.type==="public",o=!!n,i;if(e.asymmetricKeyType==="x25519"){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(ce)}i=e.toCryptoKey(e.asymmetricKeyType,o,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(ce);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError(ce);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}}if(e.asymmetricKeyType==="rsa"){let s;switch(t){case"RSA-OAEP":s="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":s="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":s="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":s="SHA-512";break;default:throw new TypeError(ce)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:s},o,n?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:s},o,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(ce);let p={ES256:"P-256",ES384:"P-384",ES512:"P-521"};p[t]&&a===p[t]&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:a},o,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:a},o,n?[]:["deriveBits"]))}if(!i)throw new TypeError(ce);return r?r[t]=i:ue.set(e,{[t]:i}),i};async function or(e,t){if(e instanceof Uint8Array||at(e))return e;if(ct(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return Dn(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return nr(e,r,t)}if(be(e))return e.k?B(e.k):nr(e,e,t,!0);throw new Error("unreachable")}async function ir(e,t,r){if(!U(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return B(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new x('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return ae({...e,alg:t,ext:n});case"AKP":{if(typeof e.alg!="string"||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==void 0&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return ae({...e,ext:n})}case"EC":case"OKP":return ae({...e,alg:t,ext:n});default:throw new x('Unsupported "kty" (Key Type) Parameter value')}}function sr(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(let s of n.crit){if(!i.has(s))throw new x(`Extension Header Parameter "${s}" is not recognized`);if(o[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}function ar(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}var fe=e=>e?.[Symbol.toStringTag],lt=(e,t,r)=>{if(t.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case e==="dir":case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):!e.includes("GCM")&&e.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&e.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=e.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&t.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Jn=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(be(t)){if(tr(t)&&lt(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ut(t))throw new TypeError(st(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${fe(t)} instances for symmetric algorithms must be of type "secret"`)}},Un=(e,t,r)=>{if(be(t))switch(r){case"decrypt":case"sign":if(Qt(t)&&lt(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(er(t)&&lt(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!ut(t))throw new TypeError(st(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${fe(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${fe(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${fe(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${fe(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${fe(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function cr(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Jn(e,t,r);break;default:Un(e,t,r)}}async function ur(e,t,r){if(!U(e))throw new E("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new E('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new E("JWS Protected Header incorrect type");if(e.payload===void 0)throw new E("JWS Payload missing");if(typeof e.signature!="string")throw new E("JWS Signature missing or incorrect type");if(e.header!==void 0&&!U(e.header))throw new E("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let V=B(e.protected);n=JSON.parse(j.decode(V))}catch{throw new E("JWS Protected Header is invalid")}if(!Zt(n,e.header))throw new E("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...n,...e.header},i=sr(E,new Map([["b64",!0]]),r?.crit,n,o),s=!0;if(i.has("b64")&&(s=n.b64,typeof s!="boolean"))throw new E('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=o;if(typeof a!="string"||!a)throw new E('JWS "alg" (Algorithm) Header Parameter missing or invalid');let p=r&&ar("algorithms",r.algorithms);if(p&&!p.has(a))throw new Ke('"alg" (Algorithm) Header Parameter value not allowed');if(s){if(typeof e.payload!="string")throw new E("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new E("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof t=="function"&&(t=await t(n,e),d=!0),cr(a,t,"verify");let y=Vt(e.protected!==void 0?Te(e.protected):new Uint8Array,Te("."),typeof e.payload=="string"?s?Te(e.payload):_e.encode(e.payload):e.payload),h=ft(e.signature,"signature",E),A=await or(t,a);if(!await rr(a,A,h,y))throw new Ce;let P;s?P=ft(e.payload,"payload",E):typeof e.payload=="string"?P=_e.encode(e.payload):P=e.payload;let D={payload:P};return e.protected!==void 0&&(D.protectedHeader=n),e.header!==void 0&&(D.unprotectedHeader=e.header),d?{...D,key:A}:D}async function fr(e,t,r){if(e instanceof Uint8Array&&(e=j.decode(e)),typeof e!="string")throw new E("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:i,length:s}=e.split(".");if(s!==3)throw new E("Invalid Compact JWS");let a=await ur({payload:o,protected:n,signature:i},t,r),p={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...p,key:a.key}:p}var Ln=e=>Math.floor(e.getTime()/1e3),pr=60,hr=pr*60,dt=hr*24,Nn=dt*7,Hn=dt*365.25,Mn=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function lr(e){let t=Mn.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*pr);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*hr);break;case"day":case"days":case"d":o=Math.round(r*dt);break;case"week":case"weeks":case"w":o=Math.round(r*Nn);break;default:o=Math.round(r*Hn);break}return t[1]==="-"||t[4]==="ago"?-o:o}var dr=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,jn=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function mr(e,t,r={}){let n;try{n=JSON.parse(j.decode(t))}catch{}if(!U(n))throw new se("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||dr(e.typ)!==dr(o)))throw new C('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:i=[],issuer:s,subject:a,audience:p,maxTokenAge:d}=r,y=[...i];d!==void 0&&y.push("iat"),p!==void 0&&y.push("aud"),a!==void 0&&y.push("sub"),s!==void 0&&y.push("iss");for(let P of new Set(y.reverse()))if(!(P in n))throw new C(`missing required "${P}" claim`,n,P,"missing");if(s&&!(Array.isArray(s)?s:[s]).includes(n.iss))throw new C('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new C('unexpected "sub" claim value',n,"sub","check_failed");if(p&&!jn(n.aud,typeof p=="string"?[p]:p))throw new C('unexpected "aud" claim value',n,"aud","check_failed");let h;switch(typeof r.clockTolerance){case"string":h=lr(r.clockTolerance);break;case"number":h=r.clockTolerance;break;case"undefined":h=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:A}=r,K=Ln(A||new Date);if((n.iat!==void 0||d)&&typeof n.iat!="number")throw new C('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new C('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>K+h)throw new C('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new C('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=K-h)throw new we('"exp" claim timestamp check failed',n,"exp","check_failed")}if(d){let P=K-n.iat,D=typeof d=="number"?d:lr(d);if(P-h>D)throw new we('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(P<0-h)throw new C('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}async function pt(e,t,r){let n=await fr(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new se("JWTs MUST NOT use unencoded payload");let i={payload:mr(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...i,key:n.key}:i}function zn(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new x('Unsupported "alg" value for a JSON Web Key Set')}}function $n(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(Bn)}function Bn(e){return U(e)}var ht=class{#e;#t=new WeakMap;constructor(t){if(!$n(t))throw new ge("JSON Web Key Set malformed");this.#e=structuredClone(t)}jwks(){return this.#e}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},i=zn(n),s=this.#e.keys.filter(d=>{let y=i===d.kty;if(y&&typeof o=="string"&&(y=o===d.kid),y&&(typeof d.alg=="string"||i==="AKP")&&(y=n===d.alg),y&&typeof d.use=="string"&&(y=d.use==="sig"),y&&Array.isArray(d.key_ops)&&(y=d.key_ops.includes("verify")),y)switch(n){case"ES256":y=d.crv==="P-256";break;case"ES384":y=d.crv==="P-384";break;case"ES512":y=d.crv==="P-521";break;case"Ed25519":case"EdDSA":y=d.crv==="Ed25519";break}return y}),{0:a,length:p}=s;if(p===0)throw new Oe;if(p!==1){let d=new ve,y=this.#t;throw d[Symbol.asyncIterator]=async function*(){for(let h of s)try{yield await yr(y,h,n)}catch{}},d}return yr(this.#t,a,n)}};async function yr(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await ir({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new ge("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function mt(e){let t=new ht(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var yt=new WeakMap;function Fn(e){if(!e||!Array.isArray(e.keys))throw l("metro.oidc: Error: jwks must be an object with a keys array");return yt.has(e)||yt.set(e,mt(e)),yt.get(e)}function Vn(e={}){let t=e.id_token_signing_alg_values_supported;return Array.isArray(t)&&t.length?t.filter(r=>r!=="none"):["RS256"]}async function _t(e,t={}){if(!e)throw l("metro.oidc: Error: token response did not include an id_token");if(!t.jwks)throw l("metro.oidc: Error: cannot validate id_token without jwks");if(!t.issuer)throw l("metro.oidc: Error: cannot validate id_token without issuer");if(!t.client_id)throw l("metro.oidc: Error: cannot validate id_token without client_id");let{payload:r,protectedHeader:n}=await pt(e,Fn(t.jwks),{issuer:t.issuer,audience:t.client_id,algorithms:t.algorithms||Vn(t.openid_configuration),clockTolerance:t.clockTolerance??60,requiredClaims:["iss","sub","aud","exp","iat"]});if(t.nonce!==void 0&&r.nonce!==t.nonce)throw l("metro.oidc: Error: id_token nonce mismatch");return{header:n,claims:r}}var We=new Map,Gn={token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"]};function qn(e,t){if(!We.has(e)){let r=t().finally(()=>{We.delete(e)});We.set(e,r)}return We.get(e)}function De(e={}){let t={client:I(),force_authorization:!1,use_dpop:!0,authorize_callback:async h=>(window.location.href!=h.href&&window.location.replace(h.href),!1)};e=Object.assign({},t,e);let r=e.client_info;k(e,{client:b(Y(I().constructor)),client_info:b(),issuer:b(_),oauth2:u({}),openid_configuration:u()});let n=wt(e),o=Yn(e),i=gt(e.issuer,n),s=e.issuer+" "+JSON.stringify(r?.redirect_uris??null),a=e.store;if(e.store||(e.store=Z(e.issuer),a=Z(i)),!e.openid_configuration&&e.store.has("openid_configuration")&&(e.openid_configuration=e.store.get("openid_configuration")),!e.client_info?.client_id&&e.store.has("client_info")){let h=e.store.get("client_info");Xn(h,r)&&(e.client_info=h)}async function p(){if(e.openid_configuration&&e.client_info?.client_id)return;let h=await qn(s,d);e.openid_configuration=h.openid_configuration,e.client_info=h.client_info,e.store.set("openid_configuration",e.openid_configuration),e.store.set("client_info",e.client_info)}async function d(){let h=e.openid_configuration;h||(h=await ne({issuer:e.issuer,client:e.client.with(e.issuer)}));let A=e.client_info;if(!A?.client_id){if(!h.registration_endpoint)throw l("metro.oidcmw: Error: issuer "+e.issuer+" does not support dynamic client registration, but you haven't specified a client_id");A=await oe({registration_endpoint:h.registration_endpoint,client:e.client,client_info:Object.assign({},Gn,A)}),A.token_endpoint_auth_method=="none"&&delete A.client_secret}return{openid_configuration:h,client_info:A}}function y(h){return typeof h!="function"?h:async A=>(a.set("pending_nonce",A.searchParams.get("nonce")),h(A))}return async(h,A)=>{let K;if(!e.force_authorization&&(K=await A(h),K.ok||K.status!=401&&K.status!=403))return K;await p();let P=e.scope||Zn(e),D=e.nonce||Ye(32),V=Object.assign({site:i,client:e.client,force_authorization:!0,authorize_callback:y(e.authorize_callback),oauth2_configuration:{client_id:e.client_info?.client_id,client_secret:e.client_info?.client_secret,token_endpoint_auth_method:e.client_info?.token_endpoint_auth_method,grant_type:"authorization_code",response_type:"code",response_mode:"query",authorization_endpoint:e.openid_configuration.authorization_endpoint,token_endpoint:e.openid_configuration.token_endpoint,scope:P,redirect_uri:e.client_info.redirect_uris[0],login_hint:e.login_hint??e.webid,issuer:e.openid_configuration.issuer,authorization_response_iss_parameter_supported:e.openid_configuration.authorization_response_iss_parameter_supported,token_type:e.use_dpop?"DPoP":void 0,nonce:D}}),c=async(w,R)=>{let v=await R(w),le=S(e.openid_configuration.token_endpoint,{hash:""}).href;if(S(w.url,{hash:""}).href!==le)return v;let Se=v.headers.get("content-type");if(!v.ok||!Se?.startsWith("application/json"))return v;let Ee=v.data&&typeof v.data=="object"?v.data:null;Ee||(Ee=await v.clone().json());let Ue=Ee?.id_token,Le=await eo(w)=="refresh_token";if(Le&&!Ue)return v;let _r=await f(),Ne=await _t(Ue,{issuer:e.openid_configuration.issuer,client_id:e.client_info.client_id,jwks:_r,openid_configuration:e.openid_configuration,nonce:Le?void 0:a.get("pending_nonce")});return Le&&to(Ne.claims,a.get("id_token_claims")),Qn(Ne.claims,o),a.set("id_token",Ue),a.set("id_token_claims",Ne.claims),v},f=async()=>{if(!e.jwks){let R=await e.client.with(M()).with(H()).get(e.openid_configuration.jwks_uri);e.jwks=R.data}return e.jwks},m=e.client.with(e.issuer).with(c);if(e.use_dpop){let w={site:e.issuer,token_endpoint:e.openid_configuration.token_endpoint,dpop_signing_alg_values_supported:e.openid_configuration.dpop_signing_alg_values_supported};m=m.with(ot(w))}return V.client=m,m=m.with(Xe(V)),K=await m.fetch(h),K}}function Xn(e,t){if(!e?.client_id)return!1;if(!Array.isArray(t?.redirect_uris))return!0;let r=new Set(e.redirect_uris||[]);return t.redirect_uris.every(n=>r.has(n))}function wt(e){return e.webid??e.login_hint}function Yn(e){return e.webid?Object.assign({webid:e.webid},e.expected_claims):e.expected_claims||{}}function Zn(e){let t=e.openid_configuration?.scopes_supported,r=Array.isArray(t)&&t.includes("webid");return e.webid||r?"openid webid":"openid"}function gt(e,t){return t?e+"|"+t:e}function Qn(e,t){for(let[r,n]of Object.entries(t)){let o=ro(e,r);if(o!==n)throw l("metro.oidcmw: id_token is for a different user: expected "+r+" "+n+", got "+o)}}async function eo(e){let t=await e.clone().text();return new URLSearchParams(t).get("grant_type")}function to(e,t){if(t&&e.sub!==t.sub)throw l("metro.oidcmw: refreshed id_token is for a different user: expected sub "+t.sub+", got "+e.sub)}function ro(e,t){return t=="webid"&&e.webid===void 0?e.sub:e[t]}function bt(){return Lt()}function St(e){if(!e.store){if(!e.issuer)throw l("Must supply options.issuer or options.store to get the id_token");e.store=Z(gt(e.issuer,wt(e)))}return e.store.get("id_token")}function Et(e){if(!e.store){if(!e.issuer)throw l("Must supply options.issuer or options.store to get the id_token claims");e.store=Z(gt(e.issuer,wt(e)))}return e.store.get("id_token_claims")}var no={oidcmw:De,discover:ne,register:oe,isRedirected:bt,idToken:St,idTokenClaims:Et},At=no;var xt=Object.assign({},N,globalThis.metro||{});xt.oidc||(xt.oidc=At);globalThis.metro=xt;var gs=At;})();
3
+ `);throw console.error("\u{1F170}\uFE0F "+i),new Error(i,{cause:{problems:r,issues:n,source:e}})}}}function u(e){return function(r,n,o){if(typeof r<"u"&&r!=null&&typeof e<"u")return O(r,e,n,o)}}function b(e){return function(r,n,o){return r==null||typeof r>"u"?g("data is required",r,e||"any value",o):typeof e<"u"?O(r,e,n,o):!1}}function re(e){return function(r,n,o){return r==null||typeof r>"u"?(It("data does not contain recommended value",r,e,o),!1):O(r,e,n,o)}}function T(...e){return function(r,n,o){for(let i of e)if(!O(r,i,n,o))return!1;return g("data does not match oneOf patterns",r,e,o)}}function Y(...e){return function(r,n,o){if(!Array.isArray(r))return g("data is not an array",r,"anyOf",o);for(let[i,s]of r.entries()){let a=G(o,i);if(T(...e)(s,n,a))return g("data does not match anyOf patterns",s,e,a)}return!1}}function Be(...e){return function(r,n,o){let i=[];for(let s of e)i=i.concat(O(r,s,n,o));if(i=i.filter(Boolean),i.length)return g("data does not match all given patterns",r,e,o,i)}}function w(e,t,r){try{e instanceof URL&&(e=e.href);let n=new URL(e);if(n.href!=e&&!(n.href+"/"==e||n.href==e+"/"))return g("data is not a valid url",e,"validURL",r)}catch{return g("data is not a valid url",e,"validURL",r)}}function Fe(e,t,r){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e))return g("data is not a valid email",e,"validEmail",r)}function q(e){return function(r,n,o){if(!(r instanceof e))return g("data is not an instanceof pattern",r,e,o)}}function ne(e){return function(r,n,o){if(!O(r,e,n,o))return g("data matches pattern, when required not to",r,e,o)}}function Mr(e,t,r){let n=O(e,t,r);return n?$e(n):!1}function O(e,t,r,n=""){typeof r>"u"&&(r=e);let o=[];if(t===Boolean)typeof e!="boolean"&&!(e instanceof Boolean)&&o.push(g("data is not a boolean",e,t,n));else if(t===Number)typeof e!="number"&&!(e instanceof Number)&&o.push(g("data is not a number",e,t,n));else if(t===String)typeof e!="string"&&!(e instanceof String)&&o.push(g("data is not a string",e,t,n)),e==""&&o.push(g("data is an empty string, which is not allowed",e,t,n));else if(t instanceof RegExp)if(Array.isArray(e)){let i=e.findIndex((s,a)=>O(s,t,r,G(n,a)));i>-1&&o.push(g("data["+i+"] does not match pattern",e[i],t,G(n,i)))}else typeof e>"u"?o.push(g("data is undefined, should match pattern",e,t,n)):t.test(e)||o.push(g("data does not match pattern",e,t,n));else if(t instanceof Function){let i=t(e,r,n);i&&(Array.isArray(i)?o=o.concat(i):o.push(i))}else if(Array.isArray(t))if(!Array.isArray(e))o.push(g("data is not an array",e,[],n));else for(let i of t)for(let s of e.keys()){let a=O(e[s],i,r,G(n,s));Array.isArray(a)?o=o.concat(a):a&&o.push(a)}else if(t&&typeof t=="object")if(Array.isArray(e)){let i=e.findIndex((s,a)=>O(s,t,r,G(n,a)));i>-1&&o.push(g("data["+i+"] does not match pattern",e[i],t,G(n,i)))}else if(!e||typeof e!="object")o.push(g("data is not an object, pattern is",e,t,n));else if(e instanceof URLSearchParams&&(e=Object.fromEntries(e)),t instanceof Function){let i=O(e,t,r,n);i&&(o=o.concat(i))}else for(let[i,s]of Object.entries(t)){let a=O(e[i],s,r,G(n,i));a&&(o=o.concat(a))}else t!=e&&o.push(g("data and pattern are not equal",e,t,n));return o.length?o:!1}function g(e,t,r,n="",o){let i=Kt(n),s={path:n,pathString:ze(i),pathParts:i,message:e,found:t,expected:r};return o&&(s.problems=o),s}function It(e,t,r,n){console.warn("\u{1F170}\uFE0F Assert: "+n,e,r,t)}globalThis.assert={...Ve};function Wt(e){let t,r;if(typeof localStorage<"u")t={get:()=>localStorage.getItem("metro/state:"+e),set:n=>localStorage.setItem("metro/state:"+e,n),has:()=>localStorage.getItem("metro/state:"+e)!==null,delete:()=>localStorage.removeItem("metro/state:"+e)},r={get:n=>JSON.parse(localStorage.getItem(e+":"+n)),set:(n,o)=>localStorage.setItem(e+":"+n,JSON.stringify(o)),has:n=>localStorage.getItem(e+":"+n)!==null,delete:n=>localStorage.removeItem(e+":"+n)};else{let n=new Map;t={get:()=>n.get("metro/state:"+e),set:o=>n.set("metro/state:"+e,o),has:()=>n.has("metro/state:"+e),delete:()=>n.delete("metro/state:"+e)},r=new Map}return{state:t,tokens:r}}var xe=new Map,jr=new Map([["bearer","Bearer"],["dpop","DPoP"]]),zr=new Set(["none","client_secret_post","client_secret_basic"]);function Xe(e){let t={client:C(),force_authorization:!1,site:"default",oauth2_configuration:{authorization_endpoint:"/authorize",token_endpoint:"/token",redirect_uri:globalThis.document?.location.href,grant_type:"authorization_code",code_verifier:Ye(64)},authorize_callback:async c=>(window.location.href!=c.href&&window.location.replace(c.href),!1)};k(e,{});let r=Object.assign({},t.oauth2_configuration,e?.oauth2_configuration);e=Object.assign({},t,e),e.oauth2_configuration=r;let n=e.tokens??"site:"+e.site,o=Wt(e.site);e.tokens||(e.tokens=o.tokens),e.state||(e.state=o.state),k(e,{oauth2_configuration:{client_id:b(/.+/),grant_type:"authorization_code",authorization_endpoint:b(w),token_endpoint:b(w),redirect_uri:b(w)}});for(let c in r)switch(c){case"access_token":case"authorization_code":case"refresh_token":e.tokens.set(c,$r(c,r[c]));break}return async function(c,f){if(e.force_authorization)return i(c,f);let m=await f(c);return m.ok||!Dt(m)?m:i(c,f)};async function i(c,f,m={}){a();let _=e.tokens.get("access_token"),P=e.tokens.get("refresh_token"),Ee=Yr(_);if(!_||Ee&&!P){if(!await s(p))throw Ge(c);return i(c,f)}else if(Ee&&P){if(!await s(d))throw Ge(c);return i(c,f)}else{let Ae=L(c,{headers:{Authorization:_.type+" "+_.value}}),Q=await f(Ae);if(!Dt(Q)||m.handledRejectedToken)return Q;if(e.tokens.get("access_token")?.value!==_.value)return i(c,f,{handledRejectedToken:!0});e.tokens.delete("access_token");let J=p;if(P&&(J=d),!await s(J))throw Ge(c);return i(c,f,{handledRejectedToken:!0})}}function s(c){if(!xe.has(n)){let f=c().finally(()=>{xe.delete(n)});xe.set(n,f)}return xe.get(n)}function a(){if(typeof window<"u"&&window?.location){let c=S(window.location),f,m,_;if(c.searchParams.has("code")||c.searchParams.has("error"))_=c.searchParams,c=c.with({search:""}),history.pushState({},"",c.href);else if(c.hash){let P=c.hash.substr(1);_=new URLSearchParams("?"+P),c=c.with({hash:""}),history.pushState({},"",c.href)}if(_){if(R(_.get("iss")),_.has("error"))throw l("oauth2mw: authorization failed: "+_.get("error")+(_.get("error_description")?" ("+_.get("error_description")+")":""));f=_.get("code"),m=_.get("state"),W(m),f&&e.tokens.set("authorization_code",f)}}}async function p(){if(r.grant_type==="authorization_code"&&!e.tokens.has("authorization_code")){let _=await y();if(!e.authorize_callback||typeof e.authorize_callback!="function")throw l("oauth2mw: oauth2 with grant_type:authorization_code requires a callback function in client options.authorize_callback");let P=await e.authorize_callback(_);if(P)K(P);else return!1}let c=h(),f=await e.client.post(c);if(!f.ok){let _=await f.text();throw l("OAuth2mw: fetch access_token: "+f.status+": "+f.statusText+" ("+_+")",{cause:c})}let m=await f.json();return V(m),e.tokens.delete("authorization_code"),m}async function d(){let c=h("refresh_token"),f=await e.client.post(c);if(!f.ok){let _=await f.text();throw l("OAuth2mw: refresh access_token: "+f.status+": "+f.statusText+" ("+_+")",{cause:c})}let m=await f.json();return V(m),m}async function y(){if(!r.authorization_endpoint)throw l("oauth2mw: Missing options.oauth2_configuration.authorization_endpoint");let c=S(r.authorization_endpoint,{hash:""});k(r,{client_id:/.+/,redirect_uri:/.+/,scope:/.*/});let f={response_type:"code",client_id:r.client_id,redirect_uri:r.redirect_uri,state:r.state||Qr(40)};return r.response_type&&(f.response_type=r.response_type),r.response_mode&&(f.response_mode=r.response_mode),e.state.set(f.state),r.code_verifier&&(e.tokens.set("code_verifier",r.code_verifier),f.code_challenge=await Zr(r.code_verifier),f.code_challenge_method="S256"),r.scope&&(f.scope=r.scope),r.prompt&&(f.prompt=r.prompt),r.login_hint&&(f.login_hint=r.login_hint),r.nonce&&(f.nonce=r.nonce),S(c,{search:f})}function h(c=null){if(k(r,{client_id:/.+/,redirect_uri:/.+/}),!r.token_endpoint)throw l("oauth2mw: Missing options.endpoints.token url");let f=S(r.token_endpoint,{hash:""}),m={grant_type:c||r.grant_type},_={};switch(A(m,_),r.scope&&(m.scope=r.scope),m.grant_type){case"authorization_code":m.redirect_uri=r.redirect_uri,m.code=e.tokens.get("authorization_code");let P=e.tokens.get("code_verifier");P&&(m.code_verifier=P);break;case"client_credentials":break;case"refresh_token":m.refresh_token=Xr(e.tokens.get("refresh_token"));break;default:throw new Error("Unknown grant_type: "+m.grant_type)}return L(f,{method:"POST",headers:_,body:new URLSearchParams(m)})}function A(c,f){let m=Fr(r);if(m==="none"){c.client_id=r.client_id;return}if(!r.client_secret)throw l("oauth2mw: token_endpoint_auth_method "+m+" requires oauth2_configuration.client_secret");if(m==="client_secret_post"){c.client_id=r.client_id,c.client_secret=r.client_secret;return}if(m==="client_secret_basic"){f.Authorization=Vr(r.client_id,r.client_secret);return}}function K(c){let f=c;if(c&&typeof c=="object"){if(R(c.iss),c.error)throw l("oauth2mw: authorization failed: "+c.error);W(c.state),f=c.authorization_code||c.code}if(!f)throw l("oauth2mw: authorization callback did not return an authorization code");e.tokens.set("authorization_code",f)}function R(c){if(r.issuer){if(!c){if(r.authorization_response_iss_parameter_supported)throw l("oauth2mw: authorization response is missing iss, expected "+r.issuer);return}if(c!==r.issuer)throw l("oauth2mw: authorization response is from issuer "+c+", expected "+r.issuer)}}function W(c){let f=e.state.get();if(!c||c!==f)throw l("oauth2mw: authorization state mismatch")}function V(c){let f=Br(c,r.token_type);e.tokens.set("access_token",f),c.refresh_token&&e.tokens.set("refresh_token",{value:c.refresh_token})}}function Dt(e){if(!e)return!1;let t=Ze(e.headers?.get("WWW-Authenticate"));return e.status===400?t?.error==="invalid_token":t?.error==="insufficient_scope"?!1:e.status===401}function $r(e,t){return e==="access_token"&&t&&typeof t=="object"?t:e==="access_token"?{value:t,type:"Bearer",expires:null}:t}function Br(e,t){if(!e||typeof e!="object")throw l("OAuth2mw: token endpoint did not return a JSON object");if(!e.access_token)throw l("OAuth2mw: token response did not include access_token");if(!e.token_type)throw l("OAuth2mw: token response did not include token_type");let r=Jt(e.token_type);if(t&&r!==Jt(t))throw l("OAuth2mw: token endpoint returned a "+r+" token, but "+t+" is required");return{value:e.access_token,expires:e.expires_in===void 0?null:qr(e.expires_in),type:r,scope:e.scope}}function Jt(e){let t=jr.get(String(e).toLowerCase());if(!t)throw l("OAuth2mw: unsupported token_type "+e);return t}function Fr(e){let t=e.token_endpoint_auth_method||(e.client_secret?"client_secret_post":"none");if(!zr.has(t))throw l("oauth2mw: unsupported token_endpoint_auth_method "+t);return t}function Vr(e,t){let r=Ut(e)+":"+Ut(t);return"Basic "+Gr(r)}function Ut(e){return encodeURIComponent(e).replace(/%20/g,"+")}function Gr(e){return typeof btoa=="function"?btoa(e):Buffer.from(e,"binary").toString("base64")}function Xr(e){return e&&typeof e=="object"?e.value:e}function Yr(e){if(!e)return!0;if(!e.expires)return!1;let t=new Date(e.expires);return new Date().getTime()>t.getTime()}function qr(e){if(e instanceof Date)return new Date(e.getTime());if(typeof e=="number"){let t=new Date;return t.setSeconds(t.getSeconds()+e),t}throw new TypeError("Unknown expires type "+e)}function Ye(e=64){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),qe(t)}async function Zr(e){let r=new TextEncoder().encode(e),n=await globalThis.crypto.subtle.digest("SHA-256",r);return qe(n)}function qe(e){let t=Array.from(new Uint8Array(e),r=>String.fromCharCode(r)).join("");return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Qr(e){let t=new Uint8Array(Math.ceil(e*3/4)+1);if(globalThis.crypto?.getRandomValues)return globalThis.crypto.getRandomValues(t),qe(t).slice(0,e);let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="",o=0;for(;o<e;)n+=r.charAt(Math.floor(Math.random()*r.length)),o++;return n}function Ge(e){let t=new Error("oauth2mw: authorization was not completed for "+e.url+"; no access token was obtained");return t.code="authorization_not_completed",t.request=e,t}function Lt(){let e=new URL(document.location.href);if(!e.searchParams.has("code")){if(e.hash){let t=e.hash.substr(1);if(new URLSearchParams("?"+t).has("code"))return!0}return!1}return!0}function Ze(e){if(!e||typeof e!="string")return null;let t=e.trim(),r=t.search(/\s/),n=r<0?t:t.slice(0,r),o=r<0?"":t.slice(r+1);if(!["bearer","dpop"].includes(n.toLowerCase()))return null;let i={scheme:n},s=/([A-Za-z][A-Za-z0-9_-]*)=("(?:[^"\\]|\\.)*"|[^,\s]*)/g,a;for(;a=s.exec(o);){let p=a[2];p.startsWith('"')&&p.endsWith('"')&&(p=p.slice(1,-1).replace(/\\"/g,'"')),i[a[1]]=p}return i}var tn=new TextEncoder,rn=new TextDecoder;function Re(e){return typeof e=="string"?tn.encode(e):rn.decode(e)}function Nt(e){if(typeof e.modulusLength!="number"||e.modulusLength<2048)throw new et(`${e.name} modulusLength must be at least 2048 bits`)}function nn(e){switch(e.algorithm.name){case"ECDSA":return{name:e.algorithm.name,hash:"SHA-256"};case"RSA-PSS":return Nt(e.algorithm),{name:e.algorithm.name,saltLength:32};case"RSASSA-PKCS1-v1_5":return Nt(e.algorithm),{name:e.algorithm.name};case"Ed25519":return{name:e.algorithm.name}}throw new z}async function on(e,t,r){if(r.usages.includes("sign")===!1)throw new TypeError('private CryptoKey instances used for signing assertions must include "sign" in their "usages"');let n=`${Pe(Re(JSON.stringify(e)))}.${Pe(Re(JSON.stringify(t)))}`,o=Pe(await crypto.subtle.sign(nn(r),r,Re(n)));return`${n}.${o}`}var Qe;Uint8Array.prototype.toBase64?Qe=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):Qe=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let r=[];for(let n=0;n<t.byteLength;n+=32768)r.push(String.fromCharCode.apply(null,t.subarray(n,n+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};function Pe(e){return Qe(e)}var z=class extends Error{constructor(t){var r;super(t??"operation not supported"),this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}},et=class extends Error{constructor(t){var r;super(t),this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}};function sn(e){if(e.algorithm.hash.name==="SHA-256")return"PS256";throw new z("unsupported RsaHashedKeyAlgorithm hash name")}function an(e){if(e.algorithm.hash.name==="SHA-256")return"RS256";throw new z("unsupported RsaHashedKeyAlgorithm hash name")}function cn(e){if(e.algorithm.namedCurve==="P-256")return"ES256";throw new z("unsupported EcKeyAlgorithm namedCurve")}function un(e){switch(e.algorithm.name){case"RSA-PSS":return sn(e);case"RSASSA-PKCS1-v1_5":return an(e);case"ECDSA":return cn(e);case"Ed25519":return"Ed25519";default:throw new z("unsupported CryptoKey algorithm name")}}function Ht(e){return e instanceof CryptoKey}function fn(e){return Ht(e)&&e.type==="private"}function ln(e){return Ht(e)&&e.type==="public"}function dn(){return Math.floor(Date.now()/1e3)}async function tt(e,t,r,n,o,i){let s=e?.privateKey,a=e?.publicKey;if(!fn(s))throw new TypeError('"keypair.privateKey" must be a private CryptoKey');if(!ln(a))throw new TypeError('"keypair.publicKey" must be a public CryptoKey');if(a.extractable!==!0)throw new TypeError('"keypair.publicKey.extractable" must be true');if(typeof t!="string")throw new TypeError('"htu" must be a string');if(typeof r!="string")throw new TypeError('"htm" must be a string');if(n!==void 0&&typeof n!="string")throw new TypeError('"nonce" must be a string or undefined');if(o!==void 0&&typeof o!="string")throw new TypeError('"accessToken" must be a string or undefined');if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new TypeError('"additional" must be an object');return on({alg:un(s),typ:"dpop+jwt",jwk:await pn(a)},Object.assign(Object.assign({},i),{iat:dn(),jti:crypto.randomUUID(),htm:r,nonce:n,htu:t,ath:o?Pe(await crypto.subtle.digest("SHA-256",Re(o))):void 0}),s)}async function pn(e){let{kty:t,e:r,n,x:o,y:i,crv:s}=await crypto.subtle.exportKey("jwk",e);return{kty:t,crv:s,e:r,n,x:o,y:i}}async function Mt(e,t){var r;let n;if(typeof e!="string"||e.length===0)throw new TypeError('"alg" must be a non-empty string');switch(e){case"PS256":n={name:"RSA-PSS",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"RS256":n={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"ES256":n={name:"ECDSA",namedCurve:"P-256"};break;case"Ed25519":n={name:"Ed25519"};break;default:throw new z}return crypto.subtle.generateKey(n,(r=t?.extractable)!==null&&r!==void 0?r:!1,["sign","verify"])}function rt(){return new Promise((e,t)=>{let r=globalThis.indexedDB.open("metro",1);r.onupgradeneeded=()=>r.result.createObjectStore("keyPairs",{keyPath:"domain"}),r.onerror=n=>{t(n)},r.onsuccess=n=>{let o=n.target.result;e({set:function(i,s){return new Promise((a,p)=>{let d=o.transaction("keyPairs","readwrite",{durability:"strict"}),y=d.objectStore("keyPairs");d.oncomplete=()=>{a()},d.onerror=p,y.put(i,s)})},get:function(i){return new Promise((s,a)=>{let p=o.transaction("keyPairs","readonly"),y=p.objectStore("keyPairs").get(i);y.onsuccess=()=>{s(y.result)},y.onerror=a,p.onerror=a})},clear:function(){return new Promise((i,s)=>{let a=o.transaction("keyPairs","readwrite"),d=a.objectStore("keyPairs").clear();d.onsuccess=()=>{i()},d.onerror=s,a.onerror=s})}})}})}var zt=new Map;function nt(e){return k(e,{site:b(w),token_endpoint:b(w),dpop_signing_alg_values_supported:u([])}),async(n,o)=>{let i=await mn(e.site),s=S(n.url).origin,a=await o(await r(n,i));return jt(s,a),t(n)&&await _n(a)&&(a=await o(await r(n,i)),jt(s,a)),a};function t(n){return n.url.startsWith(e.token_endpoint)||wn(n.headers.get("Authorization"))}async function r(n,o){if(!t(n))return n;let i=zt.get(S(n.url).origin),s=yn(n.url);if(n.url.startsWith(e.token_endpoint)){let d=await tt(o,s,n.method,i);return n.with({headers:{DPoP:d}})}let a=n.headers.get("Authorization").split(" ")[1],p=await tt(o,s,n.method,i,a);return n.with({headers:{Authorization:"DPoP "+a,DPoP:p}})}}async function mn(e){let t=await rt(),r=await t.get(e);if(!r){let n=await Mt("ES256");r={domain:e,keyPair:n},await t.set(r)}return r.keyPair}function yn(e){let t=new URL(e);return t.search="",t.hash="",t.href}function jt(e,t){let r=t.headers.get("DPoP-Nonce");r&&zt.set(e,r)}async function _n(e){return e.headers.get("DPoP-Nonce")?e.status==401?Ze(e.headers.get("WWW-Authenticate"))?.error=="use_dpop_nonce":e.status==400?(await e.clone().json().catch(()=>null))?.error=="use_dpop_nonce":!1:!1}function wn(e){return/^DPoP\s/i.test(e||"")}function H(e){return e=Object.assign({contentType:"application/json",reviver:null,replacer:null,space:""},e),async function(r,n){if(r.headers.get("Accept")||(r=r.with({headers:{Accept:e.accept??e.contentType}})),r.method!=="GET"&&r.method!=="HEAD"&&r.data&&typeof r.data=="object"&&!(r.data instanceof ReadableStream)){let i=r.headers.get("Content-Type");(!i||Sn(i))&&(r=r.with({headers:{"Content-Type":e.contentType}})),$t(r.headers.get("Content-Type"))&&(r=r.with({body:JSON.stringify(r.data,e.replacer,e.space)}))}let o=await n(r);if(o&&$t(o.headers?.get("Content-Type"))){let s=await o.clone().text();if(s==="")return o;try{let a=JSON.parse(s,e.reviver);return o.with({body:a})}catch(a){if(!o.ok)return o;throw gn(r,o,a)}}return o}}function gn(e,t,r){let n="jsonmw: could not parse "+t.headers.get("Content-Type")+" response from "+e.url,o=new Error(n,{cause:r});return o.request=e,o.response=t,o}var bn=/^application\/([a-zA-Z0-9\-_]+\+)?json\b/;function $t(e){return bn.exec(e)}function Sn(e){return/^text\/plain\b/.exec(e)}function M(e){return async function(r,n){let o=await n(r);if(!o.ok)if(e&&typeof e[o.status]=="function")o=e[o.status].apply(o,r);else throw new Error(o.status+": "+o.statusText,{cause:o});return o}}var _e=(...e)=>(t,r)=>e.filter(n=>r.hasOwnKey(n)).length>0?!1:g("root data must have all of",r,e),$=(...e)=>t=>Array.isArray(t)&&e.filter(r=>!t.includes(r)).length==0?!1:g("data must be an array which includes",t,e);var D=["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"],ke=["none","client_secret_post","client_secret_basic","client_secret_jwt","private_key_jwt"];async function oe(e={}){k(e,{client:u(q(C().constructor)),issuer:b(w)});let t={client:C().with(M()).with(H()),requireDynamicRegistration:!1};e=Object.assign({},t,e),e.client=e.client.with(M()).with(H()),Te("issuer",e.issuer);function r(a){return Ft(a)?!1:g("url must use https",a)}let n={issuer:b(Be(e.issuer,r)),authorization_endpoint:b(w),token_endpoint:b(w),userinfo_endpoint:re(w),jwks_uri:b(w),registration_endpoint:e.requireDynamicRegistration?b(w):re(w),scopes_supported:re($("openid")),response_types_supported:e.requireDynamicRegistration?b($("code","id_token","id_token token")):b([]),response_modes_supported:u([]),grant_types_supported:e.requireDynamicRegistration?u($("authorization_code")):u([]),acr_values_supported:u([]),subject_types_supported:b([]),id_token_signing_alg_values_supported:b($("RS256")),id_token_encryption_alg_values_supported:u([]),id_token_encryption_enc_values_supported:u([]),userinfo_signing_alg_values_supported:u([]),userinfo_encryption_alg_values_supported:u([]),userinfo_encryption_enc_values_supported:u([]),request_object_signing_alg_values_supported:u($("RS256")),request_object_encryption_alg_values_supported:u([]),request_object_encryption_enc_values_supported:u([]),token_endpoint_auth_methods_supported:u(Y(...ke)),token_endpoint_auth_signing_alg_values_supported:u($("RS256"),ne($("none"))),display_values_supported:u(Y("page","popup","touch","wap")),claim_types_supported:u(Y("normal","aggregated","distributed")),claims_supported:re([]),service_documentation:u(w),claims_locales_supported:u([]),ui_locales_supported:u([]),claims_parameter_supported:u(Boolean),request_parameter_supported:u(Boolean),request_uri_parameter_supported:u(Boolean),op_policy_uri:u(w),op_tos_uri:u(w)},o=S(e.issuer,".well-known/openid-configuration"),s=(await e.client.get(o)).data;return k(s,n),An(s,e.issuer),s}var En=["authorization_endpoint","token_endpoint","jwks_uri"];function An(e,t){if(!e||typeof e!="object")throw l("metro.oidc.discovery: openid-configuration for "+t+" is not a JSON object");if(!xn(e.issuer,t))throw l("metro.oidc.discovery: openid-configuration is for issuer "+e.issuer+", expected "+t);Te("issuer",e.issuer);for(let r of En){if(!e[r])throw l("metro.oidc.discovery: openid-configuration for "+t+" has no "+r);Te(r,e[r])}e.registration_endpoint&&Te("registration_endpoint",e.registration_endpoint)}function xn(e,t){return typeof e!="string"?!1:Bt(e)===Bt(String(t))}function Bt(e){return e.replace(/\/$/,"")}function Te(e,t){if(!Ft(t))throw l("metro.oidc.discovery: "+e+" must use https: "+t)}function Ft(e){let t;try{t=new URL(String(e))}catch{return!1}return t.protocol=="https:"?!0:t.protocol=="http:"&&Rn(t.hostname)}function Rn(e){return e=="localhost"||e.endsWith(".localhost")||e=="127.0.0.1"||e=="[::1]"}async function ie(e){let t={redirect_uris:b([w]),response_types:u([]),grant_types:u(Y("authorization_code","refresh_token")),application_type:u(T("native","web")),contacts:u([Fe]),client_name:u(String),logo_uri:u(w),client_uri:u(w),policy_uri:u(w),tos_uri:u(w),jwks_uri:u(w,ne(_e("jwks"))),jwks:u(w,ne(_e("jwks_uri"))),sector_identifier_uri:u(w),subject_type:u(String),id_token_signed_response_alg:u(T(...D)),id_token_encrypted_response_alg:u(T(...D)),id_token_encrypted_response_enc:u(T(...D),_e("id_token_encrypted_response_alg")),userinfo_signed_response_alg:u(T(...D)),userinfo_encrypted_response_alg:u(T(...D)),userinfo_encrypted_response_enc:u(T(...D),_e("userinfo_encrypted_response_alg")),request_object_signing_alg:u(T(...D)),request_object_encryption_alg:u(T(...D)),request_object_encryption_enc:u(T(...D)),token_endpoint_auth_method:u(T(...ke)),token_endpoint_auth_signing_alg:u(T(...D)),default_max_age:u(Number),require_auth_time:u(Boolean),default_acr_values:u([String]),initiate_login_uri:u([w]),request_uris:u([w])};k(e,{client:u(q(C().constructor)),registration_endpoint:w,client_info:t});let r={client:C().with(M()).with(H()),client_info:{redirect_uris:[globalThis.document?.location.href]}};e=Object.assign({},r,e),e.client=e.client.with(M()).with(H()),e.client_info||(e.client_info={}),e.client_info.redirect_uris||(e.client_info.redirect_uris=[globalThis.document?.location.href]);let n=await e.client.post(e.registration_endpoint,{body:e.client_info}),o=n.data;if(!o.client_id)throw l("metro.oidc: Error: dynamic registration of client failed, no client_id returned",n);return e.client_info=Object.assign(e.client_info,o),e.client_info}function Z(e){let t;if(typeof localStorage<"u")t={get:r=>JSON.parse(localStorage.getItem("metro/oidc:"+e+":"+r)),set:(r,n)=>localStorage.setItem("metro/oidc:"+e+":"+r,JSON.stringify(n)),has:r=>localStorage.getItem("metro/oidc:"+e+":"+r)!==null};else{let r=new Map;t={get:n=>JSON.parse(r.get("metro/oidc:"+e+":"+n)||null),set:(n,o)=>r.set("metro/oidc:"+e+":"+n,JSON.stringify(o)),has:n=>r.has("metro/oidc:"+e+":"+n)}}return t}var we=new TextEncoder,j=new TextDecoder,Uo=2**32;function Vt(...e){let t=e.reduce((o,{length:i})=>o+i,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function Ke(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function Gt(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function B(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:j.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=j.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return Gt(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}var F=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),se=(e,t)=>e.name===t;function Pn(e){return parseInt(e.name.slice(4),10)}function ot(e,t){if(Pn(e.hash)!==t)throw F(`SHA-${t}`,"algorithm.hash")}function kn(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Tn(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Xt(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!se(e.algorithm,"HMAC"))throw F("HMAC");ot(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!se(e.algorithm,"RSASSA-PKCS1-v1_5"))throw F("RSASSA-PKCS1-v1_5");ot(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!se(e.algorithm,"RSA-PSS"))throw F("RSA-PSS");ot(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!se(e.algorithm,"Ed25519"))throw F("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!se(e.algorithm,t))throw F(t);break}case"ES256":case"ES384":case"ES512":{if(!se(e.algorithm,"ECDSA"))throw F("ECDSA");let n=kn(t);if(e.algorithm.namedCurve!==n)throw F(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Tn(e,r)}function Yt(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var qt=(e,...t)=>Yt("Key must be ",e,...t),it=(e,t,...r)=>Yt(`Key for the ${e} algorithm must be `,t,...r);var I=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},v=class extends I{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},ge=class extends I{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},Oe=class extends I{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},x=class extends I{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"};var E=class extends I{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},ae=class extends I{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"};var be=class extends I{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},ve=class extends I{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r)}},Ce=class extends I{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r)}};var Ie=class extends I{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r)}};var st=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},at=e=>e?.[Symbol.toStringTag]==="KeyObject",ct=e=>st(e)||at(e);function ut(e,t,r){try{return B(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}var Kn=e=>typeof e=="object"&&e!==null;function U(e){if(!Kn(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Zt(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let i of o){if(r.has(i))return!1;r.add(i)}}return!0}var Se=e=>U(e)&&typeof e.kty=="string",Qt=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),er=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,tr=e=>e.kty==="oct"&&typeof e.k=="string";function vn(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function Cn(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new x(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function In(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(qt(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return Xt(t,e,r),t}async function rr(e,t,r,n){let o=await In(e,t,"verify");vn(e,o);let i=Cn(e,o.algorithm);try{return await crypto.subtle.verify(i,o,r,n)}catch{return!1}}var We='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function Wn(e){let t,r;switch(e.kty){case"AKP":{switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new x(We)}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new x(We)}break}case"EC":{switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new x(We)}break}case"OKP":{switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new x(We)}break}default:throw new x('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function ce(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=Wn(e),n={...e};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!(e.d||e.priv),e.key_ops??r)}var ue="given KeyObject instance cannot be used for this algorithm",fe,nr=async(e,t,r,n=!1)=>{fe||=new WeakMap;let o=fe.get(e);if(o?.[r])return o[r];let i=await ce({...t,alg:r});return n&&Object.freeze(e),o?o[r]=i:fe.set(e,{[r]:i}),i},Dn=(e,t)=>{fe||=new WeakMap;let r=fe.get(e);if(r?.[t])return r[t];let n=e.type==="public",o=!!n,i;if(e.asymmetricKeyType==="x25519"){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(ue)}i=e.toCryptoKey(e.asymmetricKeyType,o,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(ue);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError(ue);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}}if(e.asymmetricKeyType==="rsa"){let s;switch(t){case"RSA-OAEP":s="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":s="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":s="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":s="SHA-512";break;default:throw new TypeError(ue)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:s},o,n?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:s},o,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(ue);let p={ES256:"P-256",ES384:"P-384",ES512:"P-521"};p[t]&&a===p[t]&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:a},o,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:a},o,n?[]:["deriveBits"]))}if(!i)throw new TypeError(ue);return r?r[t]=i:fe.set(e,{[t]:i}),i};async function or(e,t){if(e instanceof Uint8Array||st(e))return e;if(at(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return Dn(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return nr(e,r,t)}if(Se(e))return e.k?B(e.k):nr(e,e,t,!0);throw new Error("unreachable")}async function ir(e,t,r){if(!U(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return B(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new x('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return ce({...e,alg:t,ext:n});case"AKP":{if(typeof e.alg!="string"||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==void 0&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return ce({...e,ext:n})}case"EC":case"OKP":return ce({...e,alg:t,ext:n});default:throw new x('Unsupported "kty" (Key Type) Parameter value')}}function sr(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(let s of n.crit){if(!i.has(s))throw new x(`Extension Header Parameter "${s}" is not recognized`);if(o[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}function ar(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}var le=e=>e?.[Symbol.toStringTag],ft=(e,t,r)=>{if(t.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case e==="dir":case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):!e.includes("GCM")&&e.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&e.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=e.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&t.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Jn=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(Se(t)){if(tr(t)&&ft(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ct(t))throw new TypeError(it(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${le(t)} instances for symmetric algorithms must be of type "secret"`)}},Un=(e,t,r)=>{if(Se(t))switch(r){case"decrypt":case"sign":if(Qt(t)&&ft(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(er(t)&&ft(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!ct(t))throw new TypeError(it(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${le(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${le(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${le(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${le(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${le(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function cr(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Jn(e,t,r);break;default:Un(e,t,r)}}async function ur(e,t,r){if(!U(e))throw new E("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new E('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new E("JWS Protected Header incorrect type");if(e.payload===void 0)throw new E("JWS Payload missing");if(typeof e.signature!="string")throw new E("JWS Signature missing or incorrect type");if(e.header!==void 0&&!U(e.header))throw new E("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let V=B(e.protected);n=JSON.parse(j.decode(V))}catch{throw new E("JWS Protected Header is invalid")}if(!Zt(n,e.header))throw new E("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...n,...e.header},i=sr(E,new Map([["b64",!0]]),r?.crit,n,o),s=!0;if(i.has("b64")&&(s=n.b64,typeof s!="boolean"))throw new E('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=o;if(typeof a!="string"||!a)throw new E('JWS "alg" (Algorithm) Header Parameter missing or invalid');let p=r&&ar("algorithms",r.algorithms);if(p&&!p.has(a))throw new Oe('"alg" (Algorithm) Header Parameter value not allowed');if(s){if(typeof e.payload!="string")throw new E("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new E("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof t=="function"&&(t=await t(n,e),d=!0),cr(a,t,"verify");let y=Vt(e.protected!==void 0?Ke(e.protected):new Uint8Array,Ke("."),typeof e.payload=="string"?s?Ke(e.payload):we.encode(e.payload):e.payload),h=ut(e.signature,"signature",E),A=await or(t,a);if(!await rr(a,A,h,y))throw new Ie;let R;s?R=ut(e.payload,"payload",E):typeof e.payload=="string"?R=we.encode(e.payload):R=e.payload;let W={payload:R};return e.protected!==void 0&&(W.protectedHeader=n),e.header!==void 0&&(W.unprotectedHeader=e.header),d?{...W,key:A}:W}async function fr(e,t,r){if(e instanceof Uint8Array&&(e=j.decode(e)),typeof e!="string")throw new E("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:i,length:s}=e.split(".");if(s!==3)throw new E("Invalid Compact JWS");let a=await ur({payload:o,protected:n,signature:i},t,r),p={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...p,key:a.key}:p}var Ln=e=>Math.floor(e.getTime()/1e3),pr=60,hr=pr*60,lt=hr*24,Nn=lt*7,Hn=lt*365.25,Mn=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function lr(e){let t=Mn.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*pr);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*hr);break;case"day":case"days":case"d":o=Math.round(r*lt);break;case"week":case"weeks":case"w":o=Math.round(r*Nn);break;default:o=Math.round(r*Hn);break}return t[1]==="-"||t[4]==="ago"?-o:o}var dr=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,jn=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function mr(e,t,r={}){let n;try{n=JSON.parse(j.decode(t))}catch{}if(!U(n))throw new ae("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||dr(e.typ)!==dr(o)))throw new v('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:i=[],issuer:s,subject:a,audience:p,maxTokenAge:d}=r,y=[...i];d!==void 0&&y.push("iat"),p!==void 0&&y.push("aud"),a!==void 0&&y.push("sub"),s!==void 0&&y.push("iss");for(let R of new Set(y.reverse()))if(!(R in n))throw new v(`missing required "${R}" claim`,n,R,"missing");if(s&&!(Array.isArray(s)?s:[s]).includes(n.iss))throw new v('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new v('unexpected "sub" claim value',n,"sub","check_failed");if(p&&!jn(n.aud,typeof p=="string"?[p]:p))throw new v('unexpected "aud" claim value',n,"aud","check_failed");let h;switch(typeof r.clockTolerance){case"string":h=lr(r.clockTolerance);break;case"number":h=r.clockTolerance;break;case"undefined":h=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:A}=r,K=Ln(A||new Date);if((n.iat!==void 0||d)&&typeof n.iat!="number")throw new v('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new v('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>K+h)throw new v('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new v('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=K-h)throw new ge('"exp" claim timestamp check failed',n,"exp","check_failed")}if(d){let R=K-n.iat,W=typeof d=="number"?d:lr(d);if(R-h>W)throw new ge('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(R<0-h)throw new v('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}async function dt(e,t,r){let n=await fr(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new ae("JWTs MUST NOT use unencoded payload");let i={payload:mr(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...i,key:n.key}:i}function zn(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new x('Unsupported "alg" value for a JSON Web Key Set')}}function $n(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(Bn)}function Bn(e){return U(e)}var pt=class{#e;#t=new WeakMap;constructor(t){if(!$n(t))throw new be("JSON Web Key Set malformed");this.#e=structuredClone(t)}jwks(){return this.#e}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},i=zn(n),s=this.#e.keys.filter(d=>{let y=i===d.kty;if(y&&typeof o=="string"&&(y=o===d.kid),y&&(typeof d.alg=="string"||i==="AKP")&&(y=n===d.alg),y&&typeof d.use=="string"&&(y=d.use==="sig"),y&&Array.isArray(d.key_ops)&&(y=d.key_ops.includes("verify")),y)switch(n){case"ES256":y=d.crv==="P-256";break;case"ES384":y=d.crv==="P-384";break;case"ES512":y=d.crv==="P-521";break;case"Ed25519":case"EdDSA":y=d.crv==="Ed25519";break}return y}),{0:a,length:p}=s;if(p===0)throw new ve;if(p!==1){let d=new Ce,y=this.#t;throw d[Symbol.asyncIterator]=async function*(){for(let h of s)try{yield await yr(y,h,n)}catch{}},d}return yr(this.#t,a,n)}};async function yr(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await ir({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new be("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function ht(e){let t=new pt(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var mt=new WeakMap;function Fn(e){if(!e||!Array.isArray(e.keys))throw l("metro.oidc: Error: jwks must be an object with a keys array");return mt.has(e)||mt.set(e,ht(e)),mt.get(e)}function Vn(e={}){let t=e.id_token_signing_alg_values_supported;return Array.isArray(t)&&t.length?t.filter(r=>r!=="none"):["RS256"]}async function yt(e,t={}){if(!e)throw l("metro.oidc: Error: token response did not include an id_token");if(!t.jwks)throw l("metro.oidc: Error: cannot validate id_token without jwks");if(!t.issuer)throw l("metro.oidc: Error: cannot validate id_token without issuer");if(!t.client_id)throw l("metro.oidc: Error: cannot validate id_token without client_id");let{payload:r,protectedHeader:n}=await dt(e,Fn(t.jwks),{issuer:t.issuer,audience:t.client_id,algorithms:t.algorithms||Vn(t.openid_configuration),clockTolerance:t.clockTolerance??60,requiredClaims:["iss","sub","aud","exp","iat"]});if(t.nonce!==void 0&&r.nonce!==t.nonce)throw l("metro.oidc: Error: id_token nonce mismatch");return{header:n,claims:r}}var De=new Map,Gn={token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"]};function Xn(e,t){if(!De.has(e)){let r=t().finally(()=>{De.delete(e)});De.set(e,r)}return De.get(e)}function Je(e={}){let t={client:C(),force_authorization:!1,use_dpop:!0,authorize_callback:async h=>(window.location.href!=h.href&&window.location.replace(h.href),!1)};e=Object.assign({},t,e);let r=e.client_info;k(e,{client:b(q(C().constructor)),client_info:b(),issuer:b(w),oauth2:u({}),openid_configuration:u()});let n=_t(e),o=qn(e),i=wt(e.issuer,n),s=e.issuer+" "+JSON.stringify(r?.redirect_uris??null),a=e.store;if(e.store||(e.store=Z(e.issuer),a=Z(i)),!e.openid_configuration&&e.store.has("openid_configuration")&&(e.openid_configuration=e.store.get("openid_configuration")),!e.client_info?.client_id&&e.store.has("client_info")){let h=e.store.get("client_info");Yn(h,r)&&(e.client_info=h)}async function p(){if(e.openid_configuration&&e.client_info?.client_id)return;let h=await Xn(s,d);e.openid_configuration=h.openid_configuration,e.client_info=h.client_info,e.store.set("openid_configuration",e.openid_configuration),e.store.set("client_info",e.client_info)}async function d(){let h=e.openid_configuration;h||(h=await oe({issuer:e.issuer,client:e.client.with(e.issuer)}));let A=e.client_info;if(!A?.client_id){if(!h.registration_endpoint)throw l("metro.oidcmw: Error: issuer "+e.issuer+" does not support dynamic client registration, but you haven't specified a client_id");A=await ie({registration_endpoint:h.registration_endpoint,client:e.client,client_info:Object.assign({},Gn,A)}),A.token_endpoint_auth_method=="none"&&delete A.client_secret}return{openid_configuration:h,client_info:A}}function y(h){return typeof h!="function"?h:async A=>(a.set("pending_nonce",A.searchParams.get("nonce")),h(A))}return async(h,A)=>{let K;if(!e.force_authorization&&(K=await A(h),K.ok||K.status!=401&&K.status!=403))return K;await p();let R=e.scope||Zn(e),W=e.nonce||Ye(32),V=Object.assign({site:i,client:e.client,force_authorization:!0,authorize_callback:y(e.authorize_callback),oauth2_configuration:{client_id:e.client_info?.client_id,client_secret:e.client_info?.client_secret,token_endpoint_auth_method:e.client_info?.token_endpoint_auth_method,grant_type:"authorization_code",response_type:"code",response_mode:"query",authorization_endpoint:e.openid_configuration.authorization_endpoint,token_endpoint:e.openid_configuration.token_endpoint,scope:R,redirect_uri:e.client_info.redirect_uris[0],login_hint:e.login_hint??e.webid,issuer:e.openid_configuration.issuer,authorization_response_iss_parameter_supported:e.openid_configuration.authorization_response_iss_parameter_supported,token_type:e.use_dpop?"DPoP":void 0,nonce:W}}),c=async(_,P)=>{let Ee=S(e.openid_configuration.token_endpoint,{hash:""}).href;if(S(_.url,{hash:""}).href!==Ee)return P(_);let Q=await eo(_)=="refresh_token",J=await P(_),xt=J.headers.get("content-type");if(!J.ok||!xt?.startsWith("application/json"))return J;let de=J.data;(!de||typeof de!="object"||de instanceof ReadableStream)&&(de=await J.clone().json());let Ue=de?.id_token;if(Q&&!Ue)return J;let _r=await f(),Le=await yt(Ue,{issuer:e.openid_configuration.issuer,client_id:e.client_info.client_id,jwks:_r,openid_configuration:e.openid_configuration,nonce:Q?void 0:a.get("pending_nonce")});return Q&&to(Le.claims,a.get("id_token_claims")),Qn(Le.claims,o),a.set("id_token",Ue),a.set("id_token_claims",Le.claims),J},f=async()=>{if(!e.jwks){let P=await e.client.with(M()).with(H()).get(e.openid_configuration.jwks_uri);e.jwks=P.data}return e.jwks},m=e.client.with(e.issuer).with(c);if(e.use_dpop){let _={site:e.issuer,token_endpoint:e.openid_configuration.token_endpoint,dpop_signing_alg_values_supported:e.openid_configuration.dpop_signing_alg_values_supported};m=m.with(nt(_))}return V.client=m,m=m.with(Xe(V)),K=await m.fetch(h),K}}function Yn(e,t){if(!e?.client_id)return!1;if(!Array.isArray(t?.redirect_uris))return!0;let r=new Set(e.redirect_uris||[]);return t.redirect_uris.every(n=>r.has(n))}function _t(e){return e.webid??e.login_hint}function qn(e){return e.webid?Object.assign({webid:e.webid},e.expected_claims):e.expected_claims||{}}function Zn(e){let t=e.openid_configuration?.scopes_supported,r=Array.isArray(t)&&t.includes("webid");return e.webid||r?"openid webid":"openid"}function wt(e,t){return t?e+"|"+t:e}function Qn(e,t){for(let[r,n]of Object.entries(t)){let o=ro(e,r);if(o!==n)throw l("metro.oidcmw: id_token is for a different user: expected "+r+" "+n+", got "+o)}}async function eo(e){let t=await e.clone().text();return new URLSearchParams(t).get("grant_type")}function to(e,t){if(t&&e.sub!==t.sub)throw l("metro.oidcmw: refreshed id_token is for a different user: expected sub "+t.sub+", got "+e.sub)}function ro(e,t){return t=="webid"&&e.webid===void 0?e.sub:e[t]}function gt(){return Lt()}function bt(e){if(!e.store){if(!e.issuer)throw l("Must supply options.issuer or options.store to get the id_token");e.store=Z(wt(e.issuer,_t(e)))}return e.store.get("id_token")}function St(e){if(!e.store){if(!e.issuer)throw l("Must supply options.issuer or options.store to get the id_token claims");e.store=Z(wt(e.issuer,_t(e)))}return e.store.get("id_token_claims")}var no={oidcmw:Je,discover:oe,register:ie,isRedirected:gt,idToken:bt,idTokenClaims:St},Et=no;var At=Object.assign({},N,globalThis.metro||{});At.oidc||(At.oidc=Et);globalThis.metro=At;var gs=Et;})();
4
4
  //# sourceMappingURL=browser.min.js.map