zudoku 0.3.0-dev.53 → 0.3.0-dev.55

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.
Files changed (124) hide show
  1. package/dist/lib/components/Bootstrap.js +1 -1
  2. package/dist/lib/components/Bootstrap.js.map +1 -1
  3. package/lib/AnchorLink-BaXHjhF-.js +989 -0
  4. package/lib/{AnchorLink-BCN_a_Uz.js.map → AnchorLink-BaXHjhF-.js.map} +1 -1
  5. package/lib/Combination-BfufJFkX.js +1365 -0
  6. package/lib/{Combination-B0Iu6mhJ.js.map → Combination-BfufJFkX.js.map} +1 -1
  7. package/lib/DevPortalProvider-GjdO0Xr-.js +1610 -0
  8. package/lib/{DevPortalProvider-Do9oJqme.js.map → DevPortalProvider-GjdO0Xr-.js.map} +1 -1
  9. package/lib/Markdown-B8nPVql1.js +19708 -0
  10. package/lib/Markdown-B8nPVql1.js.map +1 -0
  11. package/lib/MdxPage-Dlujuj-J.js +223 -0
  12. package/lib/{MdxPage-Bsc79cD-.js.map → MdxPage-Dlujuj-J.js.map} +1 -1
  13. package/lib/OperationList-krPgt6sE.js +8041 -0
  14. package/lib/{OperationList-K-JWBxau.js.map → OperationList-krPgt6sE.js.map} +1 -1
  15. package/lib/Playground-DOHxca0P.js +539 -0
  16. package/lib/{Playground-Czy7ha9z.js.map → Playground-DOHxca0P.js.map} +1 -1
  17. package/lib/Route-CR6TEwVC.js +13 -0
  18. package/lib/{Route-D-egsGHx.js.map → Route-CR6TEwVC.js.map} +1 -1
  19. package/lib/Select-Boi_pe3L.js +5298 -0
  20. package/lib/{Select-CcBbwJ2R.js.map → Select-Boi_pe3L.js.map} +1 -1
  21. package/lib/Spinner-oU0QJmi_.js +16 -0
  22. package/lib/{Spinner-C9_Opdev.js.map → Spinner-oU0QJmi_.js.map} +1 -1
  23. package/lib/_commonjsHelpers-BxmBWJD2.js +34 -0
  24. package/lib/_commonjsHelpers-BxmBWJD2.js.map +1 -0
  25. package/lib/assets/index-CpIig0AX.js +6341 -0
  26. package/lib/{index-pI9JkN46.js.map → assets/index-CpIig0AX.js.map} +1 -1
  27. package/lib/assets/worker-B5k2aBV9.js +18921 -0
  28. package/lib/assets/{worker-BjPv-hjP.js.map → worker-B5k2aBV9.js.map} +1 -1
  29. package/lib/context-BoN_3uxi.js +17 -0
  30. package/lib/{context-_fYfJFgk.js.map → context-BoN_3uxi.js.map} +1 -1
  31. package/lib/hook-CIuFuyBT.js +90 -0
  32. package/lib/{hook-CKqQERWo.js.map → hook-CIuFuyBT.js.map} +1 -1
  33. package/lib/index-BL1P4Gqq.js +280 -0
  34. package/lib/{index-ByHya67R.js.map → index-BL1P4Gqq.js.map} +1 -1
  35. package/lib/index-Bn03IPZt.js +6341 -0
  36. package/lib/{assets/index-BPdJm2ty.js.map → index-Bn03IPZt.js.map} +1 -1
  37. package/lib/{index-jsFBaizC.js → index-Dih8IAqw.js} +103 -83
  38. package/lib/{index-jsFBaizC.js.map → index-Dih8IAqw.js.map} +1 -1
  39. package/lib/index-FprhHF51.js +253 -0
  40. package/lib/{index-DseBZFJ-.js.map → index-FprhHF51.js.map} +1 -1
  41. package/lib/jsx-runtime-DvZ6OKMM.js +2110 -0
  42. package/lib/{jsx-runtime-CJZJivg2.js.map → jsx-runtime-DvZ6OKMM.js.map} +1 -1
  43. package/lib/mutation-DWY9x2Uc.js +250 -0
  44. package/lib/{mutation-DjbQSHzT.js.map → mutation-DWY9x2Uc.js.map} +1 -1
  45. package/lib/prism-bash.min-BtBk0onv.js +7 -0
  46. package/lib/{prism-bash.min-DadFsM4Z.js.map → prism-bash.min-BtBk0onv.js.map} +1 -1
  47. package/lib/prism-csharp.min-Cv7D49bv.js +30 -0
  48. package/lib/{prism-csharp.min-Yizuc34Y.js.map → prism-csharp.min-Cv7D49bv.js.map} +1 -1
  49. package/lib/prism-java.min-tNK-JX6x.js +7 -0
  50. package/lib/{prism-java.min-d5iT_mOd.js.map → prism-java.min-tNK-JX6x.js.map} +1 -1
  51. package/lib/prism-json.min-Cdtv-CME.js +2 -0
  52. package/lib/{prism-json.min-B1GJqK1k.js.map → prism-json.min-Cdtv-CME.js.map} +1 -1
  53. package/lib/prism-markup-templating-iotg2sCU.js +94 -0
  54. package/lib/{prism-markup-templating-DZrrEs0A.js.map → prism-markup-templating-iotg2sCU.js.map} +1 -1
  55. package/lib/prism-objectivec.min-CY4WGixz.js +2 -0
  56. package/lib/{prism-objectivec.min-BXSWqpJJ.js.map → prism-objectivec.min-CY4WGixz.js.map} +1 -1
  57. package/lib/prism-php.min-T6sIVgED.js +11 -0
  58. package/lib/{prism-php.min-o7FpoMP_.js.map → prism-php.min-T6sIVgED.js.map} +1 -1
  59. package/lib/prism-ruby.min-B-2KAa4y.js +8 -0
  60. package/lib/{prism-ruby.min-C7LwcKyz.js.map → prism-ruby.min-B-2KAa4y.js.map} +1 -1
  61. package/lib/router-ButO1QyY.js +4062 -0
  62. package/lib/{router-CBw2vqJE.js.map → router-ButO1QyY.js.map} +1 -1
  63. package/lib/slugify-CmS97Vy8.js +50 -0
  64. package/lib/{slugify-CiPVjteN.js.map → slugify-CmS97Vy8.js.map} +1 -1
  65. package/lib/state-CmGfNKhR.js +436 -0
  66. package/lib/{state-DKdaQzvh.js.map → state-CmGfNKhR.js.map} +1 -1
  67. package/lib/urql-DtVKPBx_.js +2567 -0
  68. package/lib/{urql-DEKdguFl.js.map → urql-DtVKPBx_.js.map} +1 -1
  69. package/lib/util-B5KX4h4M.js +55 -0
  70. package/lib/{util-_jwUlTBU.js.map → util-B5KX4h4M.js.map} +1 -1
  71. package/lib/zudoku.auth-auth0.js +24 -18
  72. package/lib/zudoku.auth-auth0.js.map +1 -1
  73. package/lib/zudoku.auth-clerk.js +43 -34
  74. package/lib/zudoku.auth-clerk.js.map +1 -1
  75. package/lib/zudoku.auth-openid.js +1121 -734
  76. package/lib/zudoku.auth-openid.js.map +1 -1
  77. package/lib/zudoku.components.js +1076 -823
  78. package/lib/zudoku.components.js.map +1 -1
  79. package/lib/zudoku.openapi-worker.js +13776 -9681
  80. package/lib/zudoku.openapi-worker.js.map +1 -1
  81. package/lib/zudoku.plugin-api-keys.js +206 -165
  82. package/lib/zudoku.plugin-api-keys.js.map +1 -1
  83. package/lib/zudoku.plugin-markdown.js +41 -33
  84. package/lib/zudoku.plugin-markdown.js.map +1 -1
  85. package/lib/zudoku.plugin-openapi.js +6 -6
  86. package/lib/zudoku.plugin-redirect.js +10 -8
  87. package/lib/zudoku.plugin-redirect.js.map +1 -1
  88. package/package.json +1 -1
  89. package/src/lib/components/Bootstrap.tsx +1 -1
  90. package/lib/AnchorLink-BCN_a_Uz.js +0 -705
  91. package/lib/Combination-B0Iu6mhJ.js +0 -915
  92. package/lib/DevPortalProvider-Do9oJqme.js +0 -1081
  93. package/lib/Markdown-aE_XoLNs.js +0 -15030
  94. package/lib/Markdown-aE_XoLNs.js.map +0 -1
  95. package/lib/MdxPage-Bsc79cD-.js +0 -190
  96. package/lib/OperationList-K-JWBxau.js +0 -5091
  97. package/lib/Playground-Czy7ha9z.js +0 -502
  98. package/lib/Route-D-egsGHx.js +0 -13
  99. package/lib/Select-CcBbwJ2R.js +0 -3667
  100. package/lib/Spinner-C9_Opdev.js +0 -15
  101. package/lib/_commonjsHelpers-BVfed4GL.js +0 -29
  102. package/lib/_commonjsHelpers-BVfed4GL.js.map +0 -1
  103. package/lib/assets/index-BPdJm2ty.js +0 -4765
  104. package/lib/assets/worker-BjPv-hjP.js +0 -14897
  105. package/lib/context-_fYfJFgk.js +0 -14
  106. package/lib/hook-CKqQERWo.js +0 -77
  107. package/lib/index-ByHya67R.js +0 -207
  108. package/lib/index-DseBZFJ-.js +0 -170
  109. package/lib/index-pI9JkN46.js +0 -4765
  110. package/lib/jsx-runtime-CJZJivg2.js +0 -1526
  111. package/lib/mutation-DjbQSHzT.js +0 -208
  112. package/lib/prism-bash.min-DadFsM4Z.js +0 -7
  113. package/lib/prism-csharp.min-Yizuc34Y.js +0 -35
  114. package/lib/prism-java.min-d5iT_mOd.js +0 -7
  115. package/lib/prism-json.min-B1GJqK1k.js +0 -2
  116. package/lib/prism-markup-templating-DZrrEs0A.js +0 -62
  117. package/lib/prism-objectivec.min-BXSWqpJJ.js +0 -2
  118. package/lib/prism-php.min-o7FpoMP_.js +0 -11
  119. package/lib/prism-ruby.min-C7LwcKyz.js +0 -10
  120. package/lib/router-CBw2vqJE.js +0 -2973
  121. package/lib/slugify-CiPVjteN.js +0 -28
  122. package/lib/state-DKdaQzvh.js +0 -288
  123. package/lib/urql-DEKdguFl.js +0 -1592
  124. package/lib/util-_jwUlTBU.js +0 -41
@@ -1,348 +1,529 @@
1
- var Re = Object.defineProperty;
2
- var xe = (e, t, n) => t in e ? Re(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
- var S = (e, t, n) => xe(e, typeof t != "symbol" ? t + "" : t, n);
4
- import { a as Pe, j as T } from "./jsx-runtime-CJZJivg2.js";
5
- import { c as Le, a as Ue } from "./_commonjsHelpers-BVfed4GL.js";
6
- import { useRef as Ce, useState as je, useEffect as ze } from "react";
7
- import { u as re } from "./state-DKdaQzvh.js";
8
- var he = { exports: {} };
9
- (function(e) {
10
- (function(t, n) {
11
- e.exports ? e.exports = n() : t.log = n();
12
- })(Le, function() {
13
- var t = function() {
14
- }, n = "undefined", o = typeof window !== n && typeof window.navigator !== n && /Trident\/|MSIE /.test(window.navigator.userAgent), s = [
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+ var _a, _b;
5
+ import { a as useNavigate, j as jsxRuntimeExports } from "./jsx-runtime-DvZ6OKMM.js";
6
+ import { c as commonjsGlobal, a as getDefaultExportFromCjs } from "./_commonjsHelpers-BxmBWJD2.js";
7
+ import { useRef, useState, useEffect } from "react";
8
+ import { u as useAuthState } from "./state-CmGfNKhR.js";
9
+ var loglevel = { exports: {} };
10
+ (function(module) {
11
+ (function(root, definition) {
12
+ if (module.exports) {
13
+ module.exports = definition();
14
+ } else {
15
+ root.log = definition();
16
+ }
17
+ })(commonjsGlobal, function() {
18
+ var noop = function() {
19
+ };
20
+ var undefinedType = "undefined";
21
+ var isIE = typeof window !== undefinedType && typeof window.navigator !== undefinedType && /Trident\/|MSIE /.test(window.navigator.userAgent);
22
+ var logMethods = [
15
23
  "trace",
16
24
  "debug",
17
25
  "info",
18
26
  "warn",
19
27
  "error"
20
- ], r = {}, i = null;
21
- function d(u, f) {
22
- var c = u[f];
23
- if (typeof c.bind == "function")
24
- return c.bind(u);
25
- try {
26
- return Function.prototype.bind.call(c, u);
27
- } catch {
28
- return function() {
29
- return Function.prototype.apply.apply(c, [u, arguments]);
30
- };
28
+ ];
29
+ var _loggersByName = {};
30
+ var defaultLogger = null;
31
+ function bindMethod(obj, methodName) {
32
+ var method = obj[methodName];
33
+ if (typeof method.bind === "function") {
34
+ return method.bind(obj);
35
+ } else {
36
+ try {
37
+ return Function.prototype.bind.call(method, obj);
38
+ } catch (e) {
39
+ return function() {
40
+ return Function.prototype.apply.apply(method, [obj, arguments]);
41
+ };
42
+ }
31
43
  }
32
44
  }
33
- function g() {
34
- console.log && (console.log.apply ? console.log.apply(console, arguments) : Function.prototype.apply.apply(console.log, [console, arguments])), console.trace && console.trace();
45
+ function traceForIE() {
46
+ if (console.log) {
47
+ if (console.log.apply) {
48
+ console.log.apply(console, arguments);
49
+ } else {
50
+ Function.prototype.apply.apply(console.log, [console, arguments]);
51
+ }
52
+ }
53
+ if (console.trace) console.trace();
35
54
  }
36
- function m(u) {
37
- return u === "debug" && (u = "log"), typeof console === n ? !1 : u === "trace" && o ? g : console[u] !== void 0 ? d(console, u) : console.log !== void 0 ? d(console, "log") : t;
55
+ function realMethod(methodName) {
56
+ if (methodName === "debug") {
57
+ methodName = "log";
58
+ }
59
+ if (typeof console === undefinedType) {
60
+ return false;
61
+ } else if (methodName === "trace" && isIE) {
62
+ return traceForIE;
63
+ } else if (console[methodName] !== void 0) {
64
+ return bindMethod(console, methodName);
65
+ } else if (console.log !== void 0) {
66
+ return bindMethod(console, "log");
67
+ } else {
68
+ return noop;
69
+ }
38
70
  }
39
- function _() {
40
- for (var u = this.getLevel(), f = 0; f < s.length; f++) {
41
- var c = s[f];
42
- this[c] = f < u ? t : this.methodFactory(c, u, this.name);
71
+ function replaceLoggingMethods() {
72
+ var level = this.getLevel();
73
+ for (var i = 0; i < logMethods.length; i++) {
74
+ var methodName = logMethods[i];
75
+ this[methodName] = i < level ? noop : this.methodFactory(methodName, level, this.name);
43
76
  }
44
- if (this.log = this.debug, typeof console === n && u < this.levels.SILENT)
77
+ this.log = this.debug;
78
+ if (typeof console === undefinedType && level < this.levels.SILENT) {
45
79
  return "No console available for logging";
80
+ }
46
81
  }
47
- function y(u) {
82
+ function enableLoggingWhenConsoleArrives(methodName) {
48
83
  return function() {
49
- typeof console !== n && (_.call(this), this[u].apply(this, arguments));
84
+ if (typeof console !== undefinedType) {
85
+ replaceLoggingMethods.call(this);
86
+ this[methodName].apply(this, arguments);
87
+ }
50
88
  };
51
89
  }
52
- function h(u, f, c) {
53
- return m(u) || y.apply(this, arguments);
90
+ function defaultMethodFactory(methodName, _level, _loggerName) {
91
+ return realMethod(methodName) || enableLoggingWhenConsoleArrives.apply(this, arguments);
54
92
  }
55
- function L(u, f) {
56
- var c = this, J, $, x, b = "loglevel";
57
- typeof u == "string" ? b += ":" + u : typeof u == "symbol" && (b = void 0);
58
- function ke(l) {
59
- var p = (s[l] || "silent").toUpperCase();
60
- if (!(typeof window === n || !b)) {
61
- try {
62
- window.localStorage[b] = p;
63
- return;
64
- } catch {
65
- }
66
- try {
67
- window.document.cookie = encodeURIComponent(b) + "=" + p + ";";
68
- } catch {
69
- }
93
+ function Logger(name, factory) {
94
+ var self = this;
95
+ var inheritedLevel;
96
+ var defaultLevel;
97
+ var userLevel;
98
+ var storageKey = "loglevel";
99
+ if (typeof name === "string") {
100
+ storageKey += ":" + name;
101
+ } else if (typeof name === "symbol") {
102
+ storageKey = void 0;
103
+ }
104
+ function persistLevelIfPossible(levelNum) {
105
+ var levelName = (logMethods[levelNum] || "silent").toUpperCase();
106
+ if (typeof window === undefinedType || !storageKey) return;
107
+ try {
108
+ window.localStorage[storageKey] = levelName;
109
+ return;
110
+ } catch (ignore) {
111
+ }
112
+ try {
113
+ window.document.cookie = encodeURIComponent(storageKey) + "=" + levelName + ";";
114
+ } catch (ignore) {
70
115
  }
71
116
  }
72
- function ee() {
73
- var l;
74
- if (!(typeof window === n || !b)) {
117
+ function getPersistedLevel() {
118
+ var storedLevel;
119
+ if (typeof window === undefinedType || !storageKey) return;
120
+ try {
121
+ storedLevel = window.localStorage[storageKey];
122
+ } catch (ignore) {
123
+ }
124
+ if (typeof storedLevel === undefinedType) {
75
125
  try {
76
- l = window.localStorage[b];
77
- } catch {
78
- }
79
- if (typeof l === n)
80
- try {
81
- var p = window.document.cookie, O = encodeURIComponent(b), ne = p.indexOf(O + "=");
82
- ne !== -1 && (l = /^([^;]+)/.exec(
83
- p.slice(ne + O.length + 1)
84
- )[1]);
85
- } catch {
126
+ var cookie = window.document.cookie;
127
+ var cookieName = encodeURIComponent(storageKey);
128
+ var location2 = cookie.indexOf(cookieName + "=");
129
+ if (location2 !== -1) {
130
+ storedLevel = /^([^;]+)/.exec(
131
+ cookie.slice(location2 + cookieName.length + 1)
132
+ )[1];
86
133
  }
87
- return c.levels[l] === void 0 && (l = void 0), l;
134
+ } catch (ignore) {
135
+ }
136
+ }
137
+ if (self.levels[storedLevel] === void 0) {
138
+ storedLevel = void 0;
88
139
  }
140
+ return storedLevel;
89
141
  }
90
- function Te() {
91
- if (!(typeof window === n || !b)) {
92
- try {
93
- window.localStorage.removeItem(b);
94
- } catch {
95
- }
96
- try {
97
- window.document.cookie = encodeURIComponent(b) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
98
- } catch {
99
- }
142
+ function clearPersistedLevel() {
143
+ if (typeof window === undefinedType || !storageKey) return;
144
+ try {
145
+ window.localStorage.removeItem(storageKey);
146
+ } catch (ignore) {
147
+ }
148
+ try {
149
+ window.document.cookie = encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
150
+ } catch (ignore) {
100
151
  }
101
152
  }
102
- function U(l) {
103
- var p = l;
104
- if (typeof p == "string" && c.levels[p.toUpperCase()] !== void 0 && (p = c.levels[p.toUpperCase()]), typeof p == "number" && p >= 0 && p <= c.levels.SILENT)
105
- return p;
106
- throw new TypeError("log.setLevel() called with invalid level: " + l);
153
+ function normalizeLevel(input) {
154
+ var level = input;
155
+ if (typeof level === "string" && self.levels[level.toUpperCase()] !== void 0) {
156
+ level = self.levels[level.toUpperCase()];
157
+ }
158
+ if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
159
+ return level;
160
+ } else {
161
+ throw new TypeError("log.setLevel() called with invalid level: " + input);
162
+ }
107
163
  }
108
- c.name = u, c.levels = {
109
- TRACE: 0,
110
- DEBUG: 1,
111
- INFO: 2,
112
- WARN: 3,
113
- ERROR: 4,
114
- SILENT: 5
115
- }, c.methodFactory = f || h, c.getLevel = function() {
116
- return x ?? $ ?? J;
117
- }, c.setLevel = function(l, p) {
118
- return x = U(l), p !== !1 && ke(x), _.call(c);
119
- }, c.setDefaultLevel = function(l) {
120
- $ = U(l), ee() || c.setLevel(l, !1);
121
- }, c.resetLevel = function() {
122
- x = null, Te(), _.call(c);
123
- }, c.enableAll = function(l) {
124
- c.setLevel(c.levels.TRACE, l);
125
- }, c.disableAll = function(l) {
126
- c.setLevel(c.levels.SILENT, l);
127
- }, c.rebuild = function() {
128
- if (i !== c && (J = U(i.getLevel())), _.call(c), i === c)
129
- for (var l in r)
130
- r[l].rebuild();
131
- }, J = U(
132
- i ? i.getLevel() : "WARN"
164
+ self.name = name;
165
+ self.levels = {
166
+ "TRACE": 0,
167
+ "DEBUG": 1,
168
+ "INFO": 2,
169
+ "WARN": 3,
170
+ "ERROR": 4,
171
+ "SILENT": 5
172
+ };
173
+ self.methodFactory = factory || defaultMethodFactory;
174
+ self.getLevel = function() {
175
+ if (userLevel != null) {
176
+ return userLevel;
177
+ } else if (defaultLevel != null) {
178
+ return defaultLevel;
179
+ } else {
180
+ return inheritedLevel;
181
+ }
182
+ };
183
+ self.setLevel = function(level, persist) {
184
+ userLevel = normalizeLevel(level);
185
+ if (persist !== false) {
186
+ persistLevelIfPossible(userLevel);
187
+ }
188
+ return replaceLoggingMethods.call(self);
189
+ };
190
+ self.setDefaultLevel = function(level) {
191
+ defaultLevel = normalizeLevel(level);
192
+ if (!getPersistedLevel()) {
193
+ self.setLevel(level, false);
194
+ }
195
+ };
196
+ self.resetLevel = function() {
197
+ userLevel = null;
198
+ clearPersistedLevel();
199
+ replaceLoggingMethods.call(self);
200
+ };
201
+ self.enableAll = function(persist) {
202
+ self.setLevel(self.levels.TRACE, persist);
203
+ };
204
+ self.disableAll = function(persist) {
205
+ self.setLevel(self.levels.SILENT, persist);
206
+ };
207
+ self.rebuild = function() {
208
+ if (defaultLogger !== self) {
209
+ inheritedLevel = normalizeLevel(defaultLogger.getLevel());
210
+ }
211
+ replaceLoggingMethods.call(self);
212
+ if (defaultLogger === self) {
213
+ for (var childName in _loggersByName) {
214
+ _loggersByName[childName].rebuild();
215
+ }
216
+ }
217
+ };
218
+ inheritedLevel = normalizeLevel(
219
+ defaultLogger ? defaultLogger.getLevel() : "WARN"
133
220
  );
134
- var te = ee();
135
- te != null && (x = U(te)), _.call(c);
221
+ var initialLevel = getPersistedLevel();
222
+ if (initialLevel != null) {
223
+ userLevel = normalizeLevel(initialLevel);
224
+ }
225
+ replaceLoggingMethods.call(self);
136
226
  }
137
- i = new L(), i.getLogger = function(f) {
138
- if (typeof f != "symbol" && typeof f != "string" || f === "")
227
+ defaultLogger = new Logger();
228
+ defaultLogger.getLogger = function getLogger(name) {
229
+ if (typeof name !== "symbol" && typeof name !== "string" || name === "") {
139
230
  throw new TypeError("You must supply a name when creating a logger.");
140
- var c = r[f];
141
- return c || (c = r[f] = new L(
142
- f,
143
- i.methodFactory
144
- )), c;
231
+ }
232
+ var logger2 = _loggersByName[name];
233
+ if (!logger2) {
234
+ logger2 = _loggersByName[name] = new Logger(
235
+ name,
236
+ defaultLogger.methodFactory
237
+ );
238
+ }
239
+ return logger2;
240
+ };
241
+ var _log = typeof window !== undefinedType ? window.log : void 0;
242
+ defaultLogger.noConflict = function() {
243
+ if (typeof window !== undefinedType && window.log === defaultLogger) {
244
+ window.log = _log;
245
+ }
246
+ return defaultLogger;
145
247
  };
146
- var R = typeof window !== n ? window.log : void 0;
147
- return i.noConflict = function() {
148
- return typeof window !== n && window.log === i && (window.log = R), i;
149
- }, i.getLoggers = function() {
150
- return r;
151
- }, i.default = i, i;
248
+ defaultLogger.getLoggers = function getLoggers() {
249
+ return _loggersByName;
250
+ };
251
+ defaultLogger["default"] = defaultLogger;
252
+ return defaultLogger;
152
253
  });
153
- })(he);
154
- var Je = he.exports;
155
- const oe = /* @__PURE__ */ Ue(Je);
156
- let M;
157
- var I, de;
158
- (typeof navigator > "u" || !((de = (I = navigator.userAgent) == null ? void 0 : I.startsWith) != null && de.call(I, "Mozilla/5.0 "))) && (M = "oauth4webapi/v2.11.1");
159
- function q(e, t) {
160
- if (e == null)
161
- return !1;
254
+ })(loglevel);
255
+ var loglevelExports = loglevel.exports;
256
+ const logger = /* @__PURE__ */ getDefaultExportFromCjs(loglevelExports);
257
+ let USER_AGENT;
258
+ if (typeof navigator === "undefined" || !((_b = (_a = navigator.userAgent) == null ? void 0 : _a.startsWith) == null ? void 0 : _b.call(_a, "Mozilla/5.0 "))) {
259
+ const NAME = "oauth4webapi";
260
+ const VERSION = "v2.11.1";
261
+ USER_AGENT = `${NAME}/${VERSION}`;
262
+ }
263
+ function looseInstanceOf(input, expected) {
264
+ if (input == null) {
265
+ return false;
266
+ }
162
267
  try {
163
- return e instanceof t || Object.getPrototypeOf(e)[Symbol.toStringTag] === t.prototype[Symbol.toStringTag];
268
+ return input instanceof expected || Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag];
164
269
  } catch {
165
- return !1;
270
+ return false;
166
271
  }
167
272
  }
168
- const K = Symbol(), Oe = Symbol(), V = Symbol(), Ie = new TextEncoder(), Ne = new TextDecoder();
169
- function A(e) {
170
- return typeof e == "string" ? Ie.encode(e) : Ne.decode(e);
273
+ const clockSkew = Symbol();
274
+ const clockTolerance = Symbol();
275
+ const customFetch = Symbol();
276
+ const encoder = new TextEncoder();
277
+ const decoder = new TextDecoder();
278
+ function buf(input) {
279
+ if (typeof input === "string") {
280
+ return encoder.encode(input);
281
+ }
282
+ return decoder.decode(input);
171
283
  }
172
- const ie = 32768;
173
- function Ke(e) {
174
- e instanceof ArrayBuffer && (e = new Uint8Array(e));
175
- const t = [];
176
- for (let n = 0; n < e.byteLength; n += ie)
177
- t.push(String.fromCharCode.apply(null, e.subarray(n, n + ie)));
178
- return btoa(t.join("")).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
284
+ const CHUNK_SIZE = 32768;
285
+ function encodeBase64Url(input) {
286
+ if (input instanceof ArrayBuffer) {
287
+ input = new Uint8Array(input);
288
+ }
289
+ const arr = [];
290
+ for (let i = 0; i < input.byteLength; i += CHUNK_SIZE) {
291
+ arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
292
+ }
293
+ return btoa(arr.join("")).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
179
294
  }
180
- function We(e) {
295
+ function decodeBase64Url(input) {
181
296
  try {
182
- const t = atob(e.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "")), n = new Uint8Array(t.length);
183
- for (let o = 0; o < t.length; o++)
184
- n[o] = t.charCodeAt(o);
185
- return n;
186
- } catch (t) {
187
- throw new a("The input to be decoded is not correctly encoded.", { cause: t });
297
+ const binary = atob(input.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""));
298
+ const bytes = new Uint8Array(binary.length);
299
+ for (let i = 0; i < binary.length; i++) {
300
+ bytes[i] = binary.charCodeAt(i);
301
+ }
302
+ return bytes;
303
+ } catch (cause) {
304
+ throw new OPE("The input to be decoded is not correctly encoded.", { cause });
188
305
  }
189
306
  }
190
- function k(e) {
191
- return typeof e == "string" ? We(e) : Ke(e);
307
+ function b64u(input) {
308
+ if (typeof input === "string") {
309
+ return decodeBase64Url(input);
310
+ }
311
+ return encodeBase64Url(input);
192
312
  }
193
- class De {
194
- constructor(t) {
195
- this.cache = /* @__PURE__ */ new Map(), this._cache = /* @__PURE__ */ new Map(), this.maxSize = t;
313
+ class LRU {
314
+ constructor(maxSize) {
315
+ this.cache = /* @__PURE__ */ new Map();
316
+ this._cache = /* @__PURE__ */ new Map();
317
+ this.maxSize = maxSize;
196
318
  }
197
- get(t) {
198
- let n = this.cache.get(t);
199
- if (n)
200
- return n;
201
- if (n = this._cache.get(t))
202
- return this.update(t, n), n;
319
+ get(key) {
320
+ let v = this.cache.get(key);
321
+ if (v) {
322
+ return v;
323
+ }
324
+ if (v = this._cache.get(key)) {
325
+ this.update(key, v);
326
+ return v;
327
+ }
328
+ return void 0;
203
329
  }
204
- has(t) {
205
- return this.cache.has(t) || this._cache.has(t);
330
+ has(key) {
331
+ return this.cache.has(key) || this._cache.has(key);
206
332
  }
207
- set(t, n) {
208
- return this.cache.has(t) ? this.cache.set(t, n) : this.update(t, n), this;
333
+ set(key, value) {
334
+ if (this.cache.has(key)) {
335
+ this.cache.set(key, value);
336
+ } else {
337
+ this.update(key, value);
338
+ }
339
+ return this;
209
340
  }
210
- delete(t) {
211
- return this.cache.has(t) ? this.cache.delete(t) : this._cache.has(t) ? this._cache.delete(t) : !1;
341
+ delete(key) {
342
+ if (this.cache.has(key)) {
343
+ return this.cache.delete(key);
344
+ }
345
+ if (this._cache.has(key)) {
346
+ return this._cache.delete(key);
347
+ }
348
+ return false;
212
349
  }
213
- update(t, n) {
214
- this.cache.set(t, n), this.cache.size >= this.maxSize && (this._cache = this.cache, this.cache = /* @__PURE__ */ new Map());
350
+ update(key, value) {
351
+ this.cache.set(key, value);
352
+ if (this.cache.size >= this.maxSize) {
353
+ this._cache = this.cache;
354
+ this.cache = /* @__PURE__ */ new Map();
355
+ }
215
356
  }
216
357
  }
217
- class v extends Error {
218
- constructor(t) {
219
- var n;
220
- super(t ?? "operation not supported"), this.name = this.constructor.name, (n = Error.captureStackTrace) == null || n.call(Error, this, this.constructor);
358
+ class UnsupportedOperationError extends Error {
359
+ constructor(message) {
360
+ var _a2;
361
+ super(message ?? "operation not supported");
362
+ this.name = this.constructor.name;
363
+ (_a2 = Error.captureStackTrace) == null ? void 0 : _a2.call(Error, this, this.constructor);
221
364
  }
222
365
  }
223
- class He extends Error {
224
- constructor(t, n) {
225
- var o;
226
- super(t, n), this.name = this.constructor.name, (o = Error.captureStackTrace) == null || o.call(Error, this, this.constructor);
366
+ class OperationProcessingError extends Error {
367
+ constructor(message, options) {
368
+ var _a2;
369
+ super(message, options);
370
+ this.name = this.constructor.name;
371
+ (_a2 = Error.captureStackTrace) == null ? void 0 : _a2.call(Error, this, this.constructor);
227
372
  }
228
373
  }
229
- const a = He, fe = new De(100);
230
- function pe(e) {
231
- return e instanceof CryptoKey;
374
+ const OPE = OperationProcessingError;
375
+ const dpopNonces = new LRU(100);
376
+ function isCryptoKey(key) {
377
+ return key instanceof CryptoKey;
232
378
  }
233
- function we(e) {
234
- return pe(e) && e.type === "private";
379
+ function isPrivateKey(key) {
380
+ return isCryptoKey(key) && key.type === "private";
235
381
  }
236
- function $e(e) {
237
- return pe(e) && e.type === "public";
382
+ function isPublicKey(key) {
383
+ return isCryptoKey(key) && key.type === "public";
238
384
  }
239
- function Y(e) {
385
+ function processDpopNonce(response) {
240
386
  try {
241
- const t = e.headers.get("dpop-nonce");
242
- t && fe.set(new URL(e.url).origin, t);
387
+ const nonce = response.headers.get("dpop-nonce");
388
+ if (nonce) {
389
+ dpopNonces.set(new URL(response.url).origin, nonce);
390
+ }
243
391
  } catch {
244
392
  }
245
- return e;
393
+ return response;
246
394
  }
247
- function C(e) {
248
- return !(e === null || typeof e != "object" || Array.isArray(e));
395
+ function isJsonObject(input) {
396
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
397
+ return false;
398
+ }
399
+ return true;
249
400
  }
250
- function W(e) {
251
- q(e, Headers) && (e = Object.fromEntries(e.entries()));
252
- const t = new Headers(e);
253
- if (M && !t.has("user-agent") && t.set("user-agent", M), t.has("authorization"))
401
+ function prepareHeaders(input) {
402
+ if (looseInstanceOf(input, Headers)) {
403
+ input = Object.fromEntries(input.entries());
404
+ }
405
+ const headers = new Headers(input);
406
+ if (USER_AGENT && !headers.has("user-agent")) {
407
+ headers.set("user-agent", USER_AGENT);
408
+ }
409
+ if (headers.has("authorization")) {
254
410
  throw new TypeError('"options.headers" must not include the "authorization" header name');
255
- if (t.has("dpop"))
411
+ }
412
+ if (headers.has("dpop")) {
256
413
  throw new TypeError('"options.headers" must not include the "dpop" header name');
257
- return t;
414
+ }
415
+ return headers;
258
416
  }
259
- function Z(e) {
260
- if (typeof e == "function" && (e = e()), !(e instanceof AbortSignal))
417
+ function signal(value) {
418
+ if (typeof value === "function") {
419
+ value = value();
420
+ }
421
+ if (!(value instanceof AbortSignal)) {
261
422
  throw new TypeError('"options.signal" must return or be an instance of AbortSignal');
262
- return e;
423
+ }
424
+ return value;
263
425
  }
264
- async function Fe(e, t) {
265
- if (!(e instanceof URL))
426
+ async function discoveryRequest(issuerIdentifier, options) {
427
+ if (!(issuerIdentifier instanceof URL)) {
266
428
  throw new TypeError('"issuerIdentifier" must be an instance of URL');
267
- if (e.protocol !== "https:" && e.protocol !== "http:")
429
+ }
430
+ if (issuerIdentifier.protocol !== "https:" && issuerIdentifier.protocol !== "http:") {
268
431
  throw new TypeError('"issuer.protocol" must be "https:" or "http:"');
269
- const n = new URL(e.href);
270
- switch (t == null ? void 0 : t.algorithm) {
432
+ }
433
+ const url = new URL(issuerIdentifier.href);
434
+ switch (options == null ? void 0 : options.algorithm) {
271
435
  case void 0:
272
436
  case "oidc":
273
- n.pathname = `${n.pathname}/.well-known/openid-configuration`.replace("//", "/");
437
+ url.pathname = `${url.pathname}/.well-known/openid-configuration`.replace("//", "/");
274
438
  break;
275
439
  case "oauth2":
276
- n.pathname === "/" ? n.pathname = ".well-known/oauth-authorization-server" : n.pathname = `.well-known/oauth-authorization-server/${n.pathname}`.replace("//", "/");
440
+ if (url.pathname === "/") {
441
+ url.pathname = ".well-known/oauth-authorization-server";
442
+ } else {
443
+ url.pathname = `.well-known/oauth-authorization-server/${url.pathname}`.replace("//", "/");
444
+ }
277
445
  break;
278
446
  default:
279
447
  throw new TypeError('"options.algorithm" must be "oidc" (default), or "oauth2"');
280
448
  }
281
- const o = W(t == null ? void 0 : t.headers);
282
- return o.set("accept", "application/json"), ((t == null ? void 0 : t[V]) || fetch)(n.href, {
283
- headers: Object.fromEntries(o.entries()),
449
+ const headers = prepareHeaders(options == null ? void 0 : options.headers);
450
+ headers.set("accept", "application/json");
451
+ return ((options == null ? void 0 : options[customFetch]) || fetch)(url.href, {
452
+ headers: Object.fromEntries(headers.entries()),
284
453
  method: "GET",
285
454
  redirect: "manual",
286
- signal: t != null && t.signal ? Z(t.signal) : null
287
- }).then(Y);
455
+ signal: (options == null ? void 0 : options.signal) ? signal(options.signal) : null
456
+ }).then(processDpopNonce);
288
457
  }
289
- function w(e) {
290
- return typeof e == "string" && e.length !== 0;
458
+ function validateString(input) {
459
+ return typeof input === "string" && input.length !== 0;
291
460
  }
292
- async function Me(e, t) {
293
- if (!(e instanceof URL))
461
+ async function processDiscoveryResponse(expectedIssuerIdentifier, response) {
462
+ if (!(expectedIssuerIdentifier instanceof URL)) {
294
463
  throw new TypeError('"expectedIssuer" must be an instance of URL');
295
- if (!q(t, Response))
464
+ }
465
+ if (!looseInstanceOf(response, Response)) {
296
466
  throw new TypeError('"response" must be an instance of Response');
297
- if (t.status !== 200)
298
- throw new a('"response" is not a conform Authorization Server Metadata response');
299
- X(t);
300
- let n;
467
+ }
468
+ if (response.status !== 200) {
469
+ throw new OPE('"response" is not a conform Authorization Server Metadata response');
470
+ }
471
+ assertReadableResponse(response);
472
+ let json;
301
473
  try {
302
- n = await t.json();
303
- } catch (o) {
304
- throw new a('failed to parse "response" body as JSON', { cause: o });
474
+ json = await response.json();
475
+ } catch (cause) {
476
+ throw new OPE('failed to parse "response" body as JSON', { cause });
477
+ }
478
+ if (!isJsonObject(json)) {
479
+ throw new OPE('"response" body must be a top level object');
480
+ }
481
+ if (!validateString(json.issuer)) {
482
+ throw new OPE('"response" body "issuer" property must be a non-empty string');
305
483
  }
306
- if (!C(n))
307
- throw new a('"response" body must be a top level object');
308
- if (!w(n.issuer))
309
- throw new a('"response" body "issuer" property must be a non-empty string');
310
- if (new URL(n.issuer).href !== e.href)
311
- throw new a('"response" body "issuer" does not match "expectedIssuer"');
312
- return n;
484
+ if (new URL(json.issuer).href !== expectedIssuerIdentifier.href) {
485
+ throw new OPE('"response" body "issuer" does not match "expectedIssuer"');
486
+ }
487
+ return json;
313
488
  }
314
- function D() {
315
- return k(crypto.getRandomValues(new Uint8Array(32)));
489
+ function randomBytes() {
490
+ return b64u(crypto.getRandomValues(new Uint8Array(32)));
316
491
  }
317
- function Be() {
318
- return D();
492
+ function generateRandomCodeVerifier() {
493
+ return randomBytes();
319
494
  }
320
- function Ge() {
321
- return D();
495
+ function generateRandomState() {
496
+ return randomBytes();
322
497
  }
323
- async function qe(e) {
324
- if (!w(e))
498
+ async function calculatePKCECodeChallenge(codeVerifier) {
499
+ if (!validateString(codeVerifier)) {
325
500
  throw new TypeError('"codeVerifier" must be a non-empty string');
326
- return k(await crypto.subtle.digest("SHA-256", A(e)));
501
+ }
502
+ return b64u(await crypto.subtle.digest("SHA-256", buf(codeVerifier)));
327
503
  }
328
- function Ve(e) {
329
- if (e instanceof CryptoKey)
330
- return { key: e };
331
- if (!((e == null ? void 0 : e.key) instanceof CryptoKey))
504
+ function getKeyAndKid(input) {
505
+ if (input instanceof CryptoKey) {
506
+ return { key: input };
507
+ }
508
+ if (!((input == null ? void 0 : input.key) instanceof CryptoKey)) {
332
509
  return {};
333
- if (e.kid !== void 0 && !w(e.kid))
510
+ }
511
+ if (input.kid !== void 0 && !validateString(input.kid)) {
334
512
  throw new TypeError('"kid" must be a non-empty string');
335
- return { key: e.key, kid: e.kid };
513
+ }
514
+ return { key: input.key, kid: input.kid };
336
515
  }
337
- function se(e) {
338
- return encodeURIComponent(e).replace(/%20/g, "+");
516
+ function formUrlEncode(token) {
517
+ return encodeURIComponent(token).replace(/%20/g, "+");
339
518
  }
340
- function Ye(e, t) {
341
- const n = se(e), o = se(t);
342
- return `Basic ${btoa(`${n}:${o}`)}`;
519
+ function clientSecretBasic(clientId, clientSecret) {
520
+ const username = formUrlEncode(clientId);
521
+ const password = formUrlEncode(clientSecret);
522
+ const credentials = btoa(`${username}:${password}`);
523
+ return `Basic ${credentials}`;
343
524
  }
344
- function Ze(e) {
345
- switch (e.algorithm.hash.name) {
525
+ function psAlg(key) {
526
+ switch (key.algorithm.hash.name) {
346
527
  case "SHA-256":
347
528
  return "PS256";
348
529
  case "SHA-384":
@@ -350,11 +531,11 @@ function Ze(e) {
350
531
  case "SHA-512":
351
532
  return "PS512";
352
533
  default:
353
- throw new v("unsupported RsaHashedKeyAlgorithm hash name");
534
+ throw new UnsupportedOperationError("unsupported RsaHashedKeyAlgorithm hash name");
354
535
  }
355
536
  }
356
- function Qe(e) {
357
- switch (e.algorithm.hash.name) {
537
+ function rsAlg(key) {
538
+ switch (key.algorithm.hash.name) {
358
539
  case "SHA-256":
359
540
  return "RS256";
360
541
  case "SHA-384":
@@ -362,11 +543,11 @@ function Qe(e) {
362
543
  case "SHA-512":
363
544
  return "RS512";
364
545
  default:
365
- throw new v("unsupported RsaHashedKeyAlgorithm hash name");
546
+ throw new UnsupportedOperationError("unsupported RsaHashedKeyAlgorithm hash name");
366
547
  }
367
548
  }
368
- function Xe(e) {
369
- switch (e.algorithm.namedCurve) {
549
+ function esAlg(key) {
550
+ switch (key.algorithm.namedCurve) {
370
551
  case "P-256":
371
552
  return "ES256";
372
553
  case "P-384":
@@ -374,281 +555,367 @@ function Xe(e) {
374
555
  case "P-521":
375
556
  return "ES512";
376
557
  default:
377
- throw new v("unsupported EcKeyAlgorithm namedCurve");
558
+ throw new UnsupportedOperationError("unsupported EcKeyAlgorithm namedCurve");
378
559
  }
379
560
  }
380
- function ge(e) {
381
- switch (e.algorithm.name) {
561
+ function keyToJws(key) {
562
+ switch (key.algorithm.name) {
382
563
  case "RSA-PSS":
383
- return Ze(e);
564
+ return psAlg(key);
384
565
  case "RSASSA-PKCS1-v1_5":
385
- return Qe(e);
566
+ return rsAlg(key);
386
567
  case "ECDSA":
387
- return Xe(e);
568
+ return esAlg(key);
388
569
  case "Ed25519":
389
570
  case "Ed448":
390
571
  return "EdDSA";
391
572
  default:
392
- throw new v("unsupported CryptoKey algorithm name");
573
+ throw new UnsupportedOperationError("unsupported CryptoKey algorithm name");
393
574
  }
394
575
  }
395
- function H(e) {
396
- const t = e == null ? void 0 : e[K];
397
- return typeof t == "number" && Number.isFinite(t) ? t : 0;
576
+ function getClockSkew(client) {
577
+ const skew = client == null ? void 0 : client[clockSkew];
578
+ return typeof skew === "number" && Number.isFinite(skew) ? skew : 0;
398
579
  }
399
- function et(e) {
400
- const t = e == null ? void 0 : e[Oe];
401
- return typeof t == "number" && Number.isFinite(t) && Math.sign(t) !== -1 ? t : 30;
580
+ function getClockTolerance(client) {
581
+ const tolerance = client == null ? void 0 : client[clockTolerance];
582
+ return typeof tolerance === "number" && Number.isFinite(tolerance) && Math.sign(tolerance) !== -1 ? tolerance : 30;
402
583
  }
403
- function Q() {
584
+ function epochTime() {
404
585
  return Math.floor(Date.now() / 1e3);
405
586
  }
406
- function tt(e, t) {
407
- const n = Q() + H(t);
587
+ function clientAssertion(as, client) {
588
+ const now = epochTime() + getClockSkew(client);
408
589
  return {
409
- jti: D(),
410
- aud: [e.issuer, e.token_endpoint],
411
- exp: n + 60,
412
- iat: n,
413
- nbf: n,
414
- iss: t.client_id,
415
- sub: t.client_id
590
+ jti: randomBytes(),
591
+ aud: [as.issuer, as.token_endpoint],
592
+ exp: now + 60,
593
+ iat: now,
594
+ nbf: now,
595
+ iss: client.client_id,
596
+ sub: client.client_id
416
597
  };
417
598
  }
418
- async function nt(e, t, n, o) {
419
- return me({
420
- alg: ge(n),
421
- kid: o
422
- }, tt(e, t), n);
599
+ async function privateKeyJwt(as, client, key, kid) {
600
+ return jwt({
601
+ alg: keyToJws(key),
602
+ kid
603
+ }, clientAssertion(as, client), key);
423
604
  }
424
- function j(e) {
425
- if (typeof e != "object" || e === null)
605
+ function assertAs(as) {
606
+ if (typeof as !== "object" || as === null) {
426
607
  throw new TypeError('"as" must be an object');
427
- if (!w(e.issuer))
608
+ }
609
+ if (!validateString(as.issuer)) {
428
610
  throw new TypeError('"as.issuer" property must be a non-empty string');
429
- return !0;
611
+ }
612
+ return true;
430
613
  }
431
- function z(e) {
432
- if (typeof e != "object" || e === null)
614
+ function assertClient(client) {
615
+ if (typeof client !== "object" || client === null) {
433
616
  throw new TypeError('"client" must be an object');
434
- if (!w(e.client_id))
617
+ }
618
+ if (!validateString(client.client_id)) {
435
619
  throw new TypeError('"client.client_id" property must be a non-empty string');
436
- return !0;
620
+ }
621
+ return true;
437
622
  }
438
- function ae(e) {
439
- if (!w(e))
623
+ function assertClientSecret(clientSecret) {
624
+ if (!validateString(clientSecret)) {
440
625
  throw new TypeError('"client.client_secret" property must be a non-empty string');
441
- return e;
626
+ }
627
+ return clientSecret;
442
628
  }
443
- function F(e, t) {
444
- if (t !== void 0)
445
- throw new TypeError(`"options.clientPrivateKey" property must not be provided when ${e} client authentication method is used.`);
629
+ function assertNoClientPrivateKey(clientAuthMethod, clientPrivateKey) {
630
+ if (clientPrivateKey !== void 0) {
631
+ throw new TypeError(`"options.clientPrivateKey" property must not be provided when ${clientAuthMethod} client authentication method is used.`);
632
+ }
446
633
  }
447
- function ce(e, t) {
448
- if (t !== void 0)
449
- throw new TypeError(`"client.client_secret" property must not be provided when ${e} client authentication method is used.`);
634
+ function assertNoClientSecret(clientAuthMethod, clientSecret) {
635
+ if (clientSecret !== void 0) {
636
+ throw new TypeError(`"client.client_secret" property must not be provided when ${clientAuthMethod} client authentication method is used.`);
637
+ }
450
638
  }
451
- async function rt(e, t, n, o, s) {
452
- switch (n.delete("client_secret"), n.delete("client_assertion_type"), n.delete("client_assertion"), t.token_endpoint_auth_method) {
639
+ async function clientAuthentication(as, client, body, headers, clientPrivateKey) {
640
+ body.delete("client_secret");
641
+ body.delete("client_assertion_type");
642
+ body.delete("client_assertion");
643
+ switch (client.token_endpoint_auth_method) {
453
644
  case void 0:
454
645
  case "client_secret_basic": {
455
- F("client_secret_basic", s), o.set("authorization", Ye(t.client_id, ae(t.client_secret)));
646
+ assertNoClientPrivateKey("client_secret_basic", clientPrivateKey);
647
+ headers.set("authorization", clientSecretBasic(client.client_id, assertClientSecret(client.client_secret)));
456
648
  break;
457
649
  }
458
650
  case "client_secret_post": {
459
- F("client_secret_post", s), n.set("client_id", t.client_id), n.set("client_secret", ae(t.client_secret));
651
+ assertNoClientPrivateKey("client_secret_post", clientPrivateKey);
652
+ body.set("client_id", client.client_id);
653
+ body.set("client_secret", assertClientSecret(client.client_secret));
460
654
  break;
461
655
  }
462
656
  case "private_key_jwt": {
463
- if (ce("private_key_jwt", t.client_secret), s === void 0)
657
+ assertNoClientSecret("private_key_jwt", client.client_secret);
658
+ if (clientPrivateKey === void 0) {
464
659
  throw new TypeError('"options.clientPrivateKey" must be provided when "client.token_endpoint_auth_method" is "private_key_jwt"');
465
- const { key: r, kid: i } = Ve(s);
466
- if (!we(r))
660
+ }
661
+ const { key, kid } = getKeyAndKid(clientPrivateKey);
662
+ if (!isPrivateKey(key)) {
467
663
  throw new TypeError('"options.clientPrivateKey.key" must be a private CryptoKey');
468
- n.set("client_id", t.client_id), n.set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"), n.set("client_assertion", await nt(e, t, r, i));
664
+ }
665
+ body.set("client_id", client.client_id);
666
+ body.set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
667
+ body.set("client_assertion", await privateKeyJwt(as, client, key, kid));
469
668
  break;
470
669
  }
471
670
  case "tls_client_auth":
472
671
  case "self_signed_tls_client_auth":
473
672
  case "none": {
474
- ce(t.token_endpoint_auth_method, t.client_secret), F(t.token_endpoint_auth_method, s), n.set("client_id", t.client_id);
673
+ assertNoClientSecret(client.token_endpoint_auth_method, client.client_secret);
674
+ assertNoClientPrivateKey(client.token_endpoint_auth_method, clientPrivateKey);
675
+ body.set("client_id", client.client_id);
475
676
  break;
476
677
  }
477
678
  default:
478
- throw new v("unsupported client token_endpoint_auth_method");
679
+ throw new UnsupportedOperationError("unsupported client token_endpoint_auth_method");
479
680
  }
480
681
  }
481
- async function me(e, t, n) {
482
- if (!n.usages.includes("sign"))
682
+ async function jwt(header, claimsSet, key) {
683
+ if (!key.usages.includes("sign")) {
483
684
  throw new TypeError('CryptoKey instances used for signing assertions must include "sign" in their "usages"');
484
- const o = `${k(A(JSON.stringify(e)))}.${k(A(JSON.stringify(t)))}`, s = k(await crypto.subtle.sign(Se(n), n, A(o)));
485
- return `${o}.${s}`;
685
+ }
686
+ const input = `${b64u(buf(JSON.stringify(header)))}.${b64u(buf(JSON.stringify(claimsSet)))}`;
687
+ const signature = b64u(await crypto.subtle.sign(keyToSubtle(key), key, buf(input)));
688
+ return `${input}.${signature}`;
486
689
  }
487
- async function ot(e, t, n, o, s, r) {
488
- const { privateKey: i, publicKey: d, nonce: g = fe.get(n.origin) } = t;
489
- if (!we(i))
690
+ async function dpopProofJwt(headers, options, url, htm, clockSkew2, accessToken) {
691
+ const { privateKey, publicKey, nonce = dpopNonces.get(url.origin) } = options;
692
+ if (!isPrivateKey(privateKey)) {
490
693
  throw new TypeError('"DPoP.privateKey" must be a private CryptoKey');
491
- if (!$e(d))
694
+ }
695
+ if (!isPublicKey(publicKey)) {
492
696
  throw new TypeError('"DPoP.publicKey" must be a public CryptoKey');
493
- if (g !== void 0 && !w(g))
697
+ }
698
+ if (nonce !== void 0 && !validateString(nonce)) {
494
699
  throw new TypeError('"DPoP.nonce" must be a non-empty string or undefined');
495
- if (!d.extractable)
700
+ }
701
+ if (!publicKey.extractable) {
496
702
  throw new TypeError('"DPoP.publicKey.extractable" must be true');
497
- const m = Q() + s, _ = await me({
498
- alg: ge(i),
703
+ }
704
+ const now = epochTime() + clockSkew2;
705
+ const proof = await jwt({
706
+ alg: keyToJws(privateKey),
499
707
  typ: "dpop+jwt",
500
- jwk: await st(d)
708
+ jwk: await publicJwk(publicKey)
501
709
  }, {
502
- iat: m,
503
- jti: D(),
504
- htm: o,
505
- nonce: g,
506
- htu: `${n.origin}${n.pathname}`,
507
- ath: r ? k(await crypto.subtle.digest("SHA-256", A(r))) : void 0
508
- }, i);
509
- e.set("dpop", _);
510
- }
511
- let N;
512
- async function it(e) {
513
- const { kty: t, e: n, n: o, x: s, y: r, crv: i } = await crypto.subtle.exportKey("jwk", e), d = { kty: t, e: n, n: o, x: s, y: r, crv: i };
514
- return N.set(e, d), d;
515
- }
516
- async function st(e) {
517
- return N || (N = /* @__PURE__ */ new WeakMap()), N.get(e) || it(e);
518
- }
519
- function at(e, t, n) {
520
- if (typeof e != "string")
521
- throw new TypeError(`"as.${t}" must be a string`);
522
- return new URL(e);
523
- }
524
- function ye(e, t, n) {
525
- return at(e[t], t);
526
- }
527
- function B(e) {
528
- const t = e;
529
- return typeof t != "object" || Array.isArray(t) || t === null ? !1 : t.error !== void 0;
530
- }
531
- async function ct(e, t, n, o, s, r) {
532
- if (!w(e))
710
+ iat: now,
711
+ jti: randomBytes(),
712
+ htm,
713
+ nonce,
714
+ htu: `${url.origin}${url.pathname}`,
715
+ ath: accessToken ? b64u(await crypto.subtle.digest("SHA-256", buf(accessToken))) : void 0
716
+ }, privateKey);
717
+ headers.set("dpop", proof);
718
+ }
719
+ let jwkCache;
720
+ async function getSetPublicJwkCache(key) {
721
+ const { kty, e, n, x, y, crv } = await crypto.subtle.exportKey("jwk", key);
722
+ const jwk = { kty, e, n, x, y, crv };
723
+ jwkCache.set(key, jwk);
724
+ return jwk;
725
+ }
726
+ async function publicJwk(key) {
727
+ jwkCache || (jwkCache = /* @__PURE__ */ new WeakMap());
728
+ return jwkCache.get(key) || getSetPublicJwkCache(key);
729
+ }
730
+ function validateEndpoint(value, endpoint, options) {
731
+ if (typeof value !== "string") {
732
+ throw new TypeError(`"as.${endpoint}" must be a string`);
733
+ }
734
+ return new URL(value);
735
+ }
736
+ function resolveEndpoint(as, endpoint, options) {
737
+ return validateEndpoint(as[endpoint], endpoint);
738
+ }
739
+ function isOAuth2Error(input) {
740
+ const value = input;
741
+ if (typeof value !== "object" || Array.isArray(value) || value === null) {
742
+ return false;
743
+ }
744
+ return value.error !== void 0;
745
+ }
746
+ async function protectedResourceRequest(accessToken, method, url, headers, body, options) {
747
+ if (!validateString(accessToken)) {
533
748
  throw new TypeError('"accessToken" must be a non-empty string');
534
- if (!(n instanceof URL))
749
+ }
750
+ if (!(url instanceof URL)) {
535
751
  throw new TypeError('"url" must be an instance of URL');
536
- return o = W(o), (r == null ? void 0 : r.DPoP) === void 0 ? o.set("authorization", `Bearer ${e}`) : (await ot(o, r.DPoP, n, "GET", H({ [K]: r == null ? void 0 : r[K] }), e), o.set("authorization", `DPoP ${e}`)), ((r == null ? void 0 : r[V]) || fetch)(n.href, {
537
- body: s,
538
- headers: Object.fromEntries(o.entries()),
539
- method: t,
752
+ }
753
+ headers = prepareHeaders(headers);
754
+ if ((options == null ? void 0 : options.DPoP) === void 0) {
755
+ headers.set("authorization", `Bearer ${accessToken}`);
756
+ } else {
757
+ await dpopProofJwt(headers, options.DPoP, url, "GET", getClockSkew({ [clockSkew]: options == null ? void 0 : options[clockSkew] }), accessToken);
758
+ headers.set("authorization", `DPoP ${accessToken}`);
759
+ }
760
+ return ((options == null ? void 0 : options[customFetch]) || fetch)(url.href, {
761
+ body,
762
+ headers: Object.fromEntries(headers.entries()),
763
+ method,
540
764
  redirect: "manual",
541
- signal: r != null && r.signal ? Z(r.signal) : null
542
- }).then(Y);
543
- }
544
- async function ut(e, t, n, o) {
545
- j(e), z(t);
546
- const s = ye(e, "userinfo_endpoint"), r = W(o == null ? void 0 : o.headers);
547
- return t.userinfo_signed_response_alg ? r.set("accept", "application/jwt") : (r.set("accept", "application/json"), r.append("accept", "application/jwt")), ct(n, "GET", s, r, null, {
548
- ...o,
549
- [K]: H(t)
765
+ signal: (options == null ? void 0 : options.signal) ? signal(options.signal) : null
766
+ }).then(processDpopNonce);
767
+ }
768
+ async function userInfoRequest(as, client, accessToken, options) {
769
+ assertAs(as);
770
+ assertClient(client);
771
+ const url = resolveEndpoint(as, "userinfo_endpoint");
772
+ const headers = prepareHeaders(options == null ? void 0 : options.headers);
773
+ if (client.userinfo_signed_response_alg) {
774
+ headers.set("accept", "application/jwt");
775
+ } else {
776
+ headers.set("accept", "application/json");
777
+ headers.append("accept", "application/jwt");
778
+ }
779
+ return protectedResourceRequest(accessToken, "GET", url, headers, null, {
780
+ ...options,
781
+ [clockSkew]: getClockSkew(client)
550
782
  });
551
783
  }
552
- async function lt(e, t, n, o, s, r, i) {
553
- return await rt(e, t, s, r, i == null ? void 0 : i.clientPrivateKey), r.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8"), ((i == null ? void 0 : i[V]) || fetch)(o.href, {
554
- body: s,
555
- headers: Object.fromEntries(r.entries()),
556
- method: n,
784
+ async function authenticatedRequest(as, client, method, url, body, headers, options) {
785
+ await clientAuthentication(as, client, body, headers, options == null ? void 0 : options.clientPrivateKey);
786
+ headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
787
+ return ((options == null ? void 0 : options[customFetch]) || fetch)(url.href, {
788
+ body,
789
+ headers: Object.fromEntries(headers.entries()),
790
+ method,
557
791
  redirect: "manual",
558
- signal: i != null && i.signal ? Z(i.signal) : null
559
- }).then(Y);
560
- }
561
- async function _e(e, t, n, o, s) {
562
- const r = ye(e, "token_endpoint");
563
- o.set("grant_type", n);
564
- const i = W(s == null ? void 0 : s.headers);
565
- return i.set("accept", "application/json"), lt(e, t, "POST", r, o, i, s);
566
- }
567
- async function dt(e, t, n, o) {
568
- if (j(e), z(t), !w(n))
792
+ signal: (options == null ? void 0 : options.signal) ? signal(options.signal) : null
793
+ }).then(processDpopNonce);
794
+ }
795
+ async function tokenEndpointRequest(as, client, grantType, parameters, options) {
796
+ const url = resolveEndpoint(as, "token_endpoint");
797
+ parameters.set("grant_type", grantType);
798
+ const headers = prepareHeaders(options == null ? void 0 : options.headers);
799
+ headers.set("accept", "application/json");
800
+ return authenticatedRequest(as, client, "POST", url, parameters, headers, options);
801
+ }
802
+ async function refreshTokenGrantRequest(as, client, refreshToken, options) {
803
+ assertAs(as);
804
+ assertClient(client);
805
+ if (!validateString(refreshToken)) {
569
806
  throw new TypeError('"refreshToken" must be a non-empty string');
570
- const s = new URLSearchParams(o == null ? void 0 : o.additionalParameters);
571
- return s.set("refresh_token", n), _e(e, t, "refresh_token", s, o);
572
- }
573
- const ht = /* @__PURE__ */ new WeakMap();
574
- async function be(e, t, n, o = !1, s = !1) {
575
- if (j(e), z(t), !q(n, Response))
807
+ }
808
+ const parameters = new URLSearchParams(options == null ? void 0 : options.additionalParameters);
809
+ parameters.set("refresh_token", refreshToken);
810
+ return tokenEndpointRequest(as, client, "refresh_token", parameters, options);
811
+ }
812
+ const idTokenClaims = /* @__PURE__ */ new WeakMap();
813
+ async function processGenericAccessTokenResponse(as, client, response, ignoreIdToken = false, ignoreRefreshToken = false) {
814
+ assertAs(as);
815
+ assertClient(client);
816
+ if (!looseInstanceOf(response, Response)) {
576
817
  throw new TypeError('"response" must be an instance of Response');
577
- if (n.status !== 200) {
578
- let i;
579
- if (i = await vt(n))
580
- return i;
581
- throw new a('"response" is not a conform Token Endpoint response');
582
- }
583
- X(n);
584
- let r;
818
+ }
819
+ if (response.status !== 200) {
820
+ let err;
821
+ if (err = await handleOAuthBodyError(response)) {
822
+ return err;
823
+ }
824
+ throw new OPE('"response" is not a conform Token Endpoint response');
825
+ }
826
+ assertReadableResponse(response);
827
+ let json;
585
828
  try {
586
- r = await n.json();
587
- } catch (i) {
588
- throw new a('failed to parse "response" body as JSON', { cause: i });
589
- }
590
- if (!C(r))
591
- throw new a('"response" body must be a top level object');
592
- if (!w(r.access_token))
593
- throw new a('"response" body "access_token" property must be a non-empty string');
594
- if (!w(r.token_type))
595
- throw new a('"response" body "token_type" property must be a non-empty string');
596
- if (r.token_type = r.token_type.toLowerCase(), r.token_type !== "dpop" && r.token_type !== "bearer")
597
- throw new v("unsupported `token_type` value");
598
- if (r.expires_in !== void 0 && (typeof r.expires_in != "number" || r.expires_in <= 0))
599
- throw new a('"response" body "expires_in" property must be a positive number');
600
- if (!s && r.refresh_token !== void 0 && !w(r.refresh_token))
601
- throw new a('"response" body "refresh_token" property must be a non-empty string');
602
- if (r.scope !== void 0 && typeof r.scope != "string")
603
- throw new a('"response" body "scope" property must be a string');
604
- if (!o) {
605
- if (r.id_token !== void 0 && !w(r.id_token))
606
- throw new a('"response" body "id_token" property must be a non-empty string');
607
- if (r.id_token) {
608
- const { claims: i } = await Et(r.id_token, kt.bind(void 0, t.id_token_signed_response_alg, e.id_token_signing_alg_values_supported), Ee, H(t), et(t)).then(_t.bind(void 0, ["aud", "exp", "iat", "iss", "sub"])).then(wt.bind(void 0, e.issuer)).then(pt.bind(void 0, t.client_id));
609
- if (Array.isArray(i.aud) && i.aud.length !== 1 && i.azp !== t.client_id)
610
- throw new a('unexpected ID Token "azp" (authorized party) claim value');
611
- if (i.auth_time !== void 0 && (!Number.isFinite(i.auth_time) || Math.sign(i.auth_time) !== 1))
612
- throw new a('ID Token "auth_time" (authentication time) must be a positive number');
613
- ht.set(r, i);
829
+ json = await response.json();
830
+ } catch (cause) {
831
+ throw new OPE('failed to parse "response" body as JSON', { cause });
832
+ }
833
+ if (!isJsonObject(json)) {
834
+ throw new OPE('"response" body must be a top level object');
835
+ }
836
+ if (!validateString(json.access_token)) {
837
+ throw new OPE('"response" body "access_token" property must be a non-empty string');
838
+ }
839
+ if (!validateString(json.token_type)) {
840
+ throw new OPE('"response" body "token_type" property must be a non-empty string');
841
+ }
842
+ json.token_type = json.token_type.toLowerCase();
843
+ if (json.token_type !== "dpop" && json.token_type !== "bearer") {
844
+ throw new UnsupportedOperationError("unsupported `token_type` value");
845
+ }
846
+ if (json.expires_in !== void 0 && (typeof json.expires_in !== "number" || json.expires_in <= 0)) {
847
+ throw new OPE('"response" body "expires_in" property must be a positive number');
848
+ }
849
+ if (!ignoreRefreshToken && json.refresh_token !== void 0 && !validateString(json.refresh_token)) {
850
+ throw new OPE('"response" body "refresh_token" property must be a non-empty string');
851
+ }
852
+ if (json.scope !== void 0 && typeof json.scope !== "string") {
853
+ throw new OPE('"response" body "scope" property must be a string');
854
+ }
855
+ if (!ignoreIdToken) {
856
+ if (json.id_token !== void 0 && !validateString(json.id_token)) {
857
+ throw new OPE('"response" body "id_token" property must be a non-empty string');
858
+ }
859
+ if (json.id_token) {
860
+ const { claims } = await validateJwt(json.id_token, checkSigningAlgorithm.bind(void 0, client.id_token_signed_response_alg, as.id_token_signing_alg_values_supported), noSignatureCheck, getClockSkew(client), getClockTolerance(client)).then(validatePresence.bind(void 0, ["aud", "exp", "iat", "iss", "sub"])).then(validateIssuer.bind(void 0, as.issuer)).then(validateAudience.bind(void 0, client.client_id));
861
+ if (Array.isArray(claims.aud) && claims.aud.length !== 1 && claims.azp !== client.client_id) {
862
+ throw new OPE('unexpected ID Token "azp" (authorized party) claim value');
863
+ }
864
+ if (claims.auth_time !== void 0 && (!Number.isFinite(claims.auth_time) || Math.sign(claims.auth_time) !== 1)) {
865
+ throw new OPE('ID Token "auth_time" (authentication time) must be a positive number');
866
+ }
867
+ idTokenClaims.set(json, claims);
614
868
  }
615
869
  }
616
- return r;
870
+ return json;
617
871
  }
618
- async function ft(e, t, n) {
619
- return be(e, t, n);
872
+ async function processRefreshTokenResponse(as, client, response) {
873
+ return processGenericAccessTokenResponse(as, client, response);
620
874
  }
621
- function pt(e, t) {
622
- if (Array.isArray(t.claims.aud)) {
623
- if (!t.claims.aud.includes(e))
624
- throw new a('unexpected JWT "aud" (audience) claim value');
625
- } else if (t.claims.aud !== e)
626
- throw new a('unexpected JWT "aud" (audience) claim value');
627
- return t;
875
+ function validateAudience(expected, result) {
876
+ if (Array.isArray(result.claims.aud)) {
877
+ if (!result.claims.aud.includes(expected)) {
878
+ throw new OPE('unexpected JWT "aud" (audience) claim value');
879
+ }
880
+ } else if (result.claims.aud !== expected) {
881
+ throw new OPE('unexpected JWT "aud" (audience) claim value');
882
+ }
883
+ return result;
628
884
  }
629
- function wt(e, t) {
630
- if (t.claims.iss !== e)
631
- throw new a('unexpected JWT "iss" (issuer) claim value');
632
- return t;
885
+ function validateIssuer(expected, result) {
886
+ if (result.claims.iss !== expected) {
887
+ throw new OPE('unexpected JWT "iss" (issuer) claim value');
888
+ }
889
+ return result;
633
890
  }
634
- const ve = /* @__PURE__ */ new WeakSet();
635
- function gt(e) {
636
- return ve.add(e), e;
891
+ const branded = /* @__PURE__ */ new WeakSet();
892
+ function brand(searchParams) {
893
+ branded.add(searchParams);
894
+ return searchParams;
637
895
  }
638
- async function mt(e, t, n, o, s, r) {
639
- if (j(e), z(t), !ve.has(n))
896
+ async function authorizationCodeGrantRequest(as, client, callbackParameters, redirectUri, codeVerifier, options) {
897
+ assertAs(as);
898
+ assertClient(client);
899
+ if (!branded.has(callbackParameters)) {
640
900
  throw new TypeError('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()');
641
- if (!w(o))
901
+ }
902
+ if (!validateString(redirectUri)) {
642
903
  throw new TypeError('"redirectUri" must be a non-empty string');
643
- if (!w(s))
904
+ }
905
+ if (!validateString(codeVerifier)) {
644
906
  throw new TypeError('"codeVerifier" must be a non-empty string');
645
- const i = E(n, "code");
646
- if (!i)
647
- throw new a('no authorization code in "callbackParameters"');
648
- const d = new URLSearchParams(r == null ? void 0 : r.additionalParameters);
649
- return d.set("redirect_uri", o), d.set("code_verifier", s), d.set("code", i), _e(e, t, "authorization_code", d, r);
907
+ }
908
+ const code = getURLSearchParameter(callbackParameters, "code");
909
+ if (!code) {
910
+ throw new OPE('no authorization code in "callbackParameters"');
911
+ }
912
+ const parameters = new URLSearchParams(options == null ? void 0 : options.additionalParameters);
913
+ parameters.set("redirect_uri", redirectUri);
914
+ parameters.set("code_verifier", codeVerifier);
915
+ parameters.set("code", code);
916
+ return tokenEndpointRequest(as, client, "authorization_code", parameters, options);
650
917
  }
651
- const yt = {
918
+ const jwtClaimNames = {
652
919
  aud: "audience",
653
920
  c_hash: "code hash",
654
921
  client_id: "client id",
@@ -664,44 +931,64 @@ const yt = {
664
931
  htu: "http uri",
665
932
  cnf: "confirmation"
666
933
  };
667
- function _t(e, t) {
668
- for (const n of e)
669
- if (t.claims[n] === void 0)
670
- throw new a(`JWT "${n}" (${yt[n]}) claim missing`);
671
- return t;
672
- }
673
- async function bt(e, t, n) {
674
- const o = await be(e, t, n, !0);
675
- if (B(o))
676
- return o;
677
- if (o.id_token !== void 0) {
678
- if (typeof o.id_token == "string" && o.id_token.length)
679
- throw new a("Unexpected ID Token returned, use processAuthorizationCodeOpenIDResponse() for OpenID Connect callback processing");
680
- delete o.id_token;
681
- }
682
- return o;
683
- }
684
- function X(e) {
685
- if (e.bodyUsed)
934
+ function validatePresence(required, result) {
935
+ for (const claim of required) {
936
+ if (result.claims[claim] === void 0) {
937
+ throw new OPE(`JWT "${claim}" (${jwtClaimNames[claim]}) claim missing`);
938
+ }
939
+ }
940
+ return result;
941
+ }
942
+ async function processAuthorizationCodeOAuth2Response(as, client, response) {
943
+ const result = await processGenericAccessTokenResponse(as, client, response, true);
944
+ if (isOAuth2Error(result)) {
945
+ return result;
946
+ }
947
+ if (result.id_token !== void 0) {
948
+ if (typeof result.id_token === "string" && result.id_token.length) {
949
+ throw new OPE("Unexpected ID Token returned, use processAuthorizationCodeOpenIDResponse() for OpenID Connect callback processing");
950
+ }
951
+ delete result.id_token;
952
+ }
953
+ return result;
954
+ }
955
+ function assertReadableResponse(response) {
956
+ if (response.bodyUsed) {
686
957
  throw new TypeError('"response" body has been used already');
958
+ }
687
959
  }
688
- async function vt(e) {
689
- if (e.status > 399 && e.status < 500) {
690
- X(e);
960
+ async function handleOAuthBodyError(response) {
961
+ if (response.status > 399 && response.status < 500) {
962
+ assertReadableResponse(response);
691
963
  try {
692
- const t = await e.json();
693
- if (C(t) && typeof t.error == "string" && t.error.length)
694
- return t.error_description !== void 0 && typeof t.error_description != "string" && delete t.error_description, t.error_uri !== void 0 && typeof t.error_uri != "string" && delete t.error_uri, t.algs !== void 0 && typeof t.algs != "string" && delete t.algs, t.scope !== void 0 && typeof t.scope != "string" && delete t.scope, t;
964
+ const json = await response.json();
965
+ if (isJsonObject(json) && typeof json.error === "string" && json.error.length) {
966
+ if (json.error_description !== void 0 && typeof json.error_description !== "string") {
967
+ delete json.error_description;
968
+ }
969
+ if (json.error_uri !== void 0 && typeof json.error_uri !== "string") {
970
+ delete json.error_uri;
971
+ }
972
+ if (json.algs !== void 0 && typeof json.algs !== "string") {
973
+ delete json.algs;
974
+ }
975
+ if (json.scope !== void 0 && typeof json.scope !== "string") {
976
+ delete json.scope;
977
+ }
978
+ return json;
979
+ }
695
980
  } catch {
696
981
  }
697
982
  }
983
+ return void 0;
698
984
  }
699
- function ue(e) {
700
- if (typeof e.modulusLength != "number" || e.modulusLength < 2048)
701
- throw new a(`${e.name} modulusLength must be at least 2048 bits`);
985
+ function checkRsaKeyAlgorithm(algorithm) {
986
+ if (typeof algorithm.modulusLength !== "number" || algorithm.modulusLength < 2048) {
987
+ throw new OPE(`${algorithm.name} modulusLength must be at least 2048 bits`);
988
+ }
702
989
  }
703
- function St(e) {
704
- switch (e) {
990
+ function ecdsaHashName(namedCurve) {
991
+ switch (namedCurve) {
705
992
  case "P-256":
706
993
  return "SHA-256";
707
994
  case "P-384":
@@ -709,353 +996,453 @@ function St(e) {
709
996
  case "P-521":
710
997
  return "SHA-512";
711
998
  default:
712
- throw new v();
999
+ throw new UnsupportedOperationError();
713
1000
  }
714
1001
  }
715
- function Se(e) {
716
- switch (e.algorithm.name) {
1002
+ function keyToSubtle(key) {
1003
+ switch (key.algorithm.name) {
717
1004
  case "ECDSA":
718
1005
  return {
719
- name: e.algorithm.name,
720
- hash: St(e.algorithm.namedCurve)
1006
+ name: key.algorithm.name,
1007
+ hash: ecdsaHashName(key.algorithm.namedCurve)
721
1008
  };
722
- case "RSA-PSS":
723
- switch (ue(e.algorithm), e.algorithm.hash.name) {
1009
+ case "RSA-PSS": {
1010
+ checkRsaKeyAlgorithm(key.algorithm);
1011
+ switch (key.algorithm.hash.name) {
724
1012
  case "SHA-256":
725
1013
  case "SHA-384":
726
1014
  case "SHA-512":
727
1015
  return {
728
- name: e.algorithm.name,
729
- saltLength: parseInt(e.algorithm.hash.name.slice(-3), 10) >> 3
1016
+ name: key.algorithm.name,
1017
+ saltLength: parseInt(key.algorithm.hash.name.slice(-3), 10) >> 3
730
1018
  };
731
1019
  default:
732
- throw new v();
1020
+ throw new UnsupportedOperationError();
733
1021
  }
1022
+ }
734
1023
  case "RSASSA-PKCS1-v1_5":
735
- return ue(e.algorithm), e.algorithm.name;
1024
+ checkRsaKeyAlgorithm(key.algorithm);
1025
+ return key.algorithm.name;
736
1026
  case "Ed448":
737
1027
  case "Ed25519":
738
- return e.algorithm.name;
739
- }
740
- throw new v();
741
- }
742
- const Ee = Symbol();
743
- async function Et(e, t, n, o, s) {
744
- const { 0: r, 1: i, 2: d, length: g } = e.split(".");
745
- if (g === 5)
746
- throw new v("JWE structure JWTs are not supported");
747
- if (g !== 3)
748
- throw new a("Invalid JWT");
749
- let m;
1028
+ return key.algorithm.name;
1029
+ }
1030
+ throw new UnsupportedOperationError();
1031
+ }
1032
+ const noSignatureCheck = Symbol();
1033
+ async function validateJwt(jws, checkAlg, getKey, clockSkew2, clockTolerance2) {
1034
+ const { 0: protectedHeader, 1: payload, 2: encodedSignature, length } = jws.split(".");
1035
+ if (length === 5) {
1036
+ throw new UnsupportedOperationError("JWE structure JWTs are not supported");
1037
+ }
1038
+ if (length !== 3) {
1039
+ throw new OPE("Invalid JWT");
1040
+ }
1041
+ let header;
750
1042
  try {
751
- m = JSON.parse(A(k(r)));
752
- } catch (R) {
753
- throw new a("failed to parse JWT Header body as base64url encoded JSON", { cause: R });
754
- }
755
- if (!C(m))
756
- throw new a("JWT Header must be a top level object");
757
- if (t(m), m.crit !== void 0)
758
- throw new a('unexpected JWT "crit" header parameter');
759
- const _ = k(d);
760
- let y;
761
- if (n !== Ee) {
762
- y = await n(m);
763
- const R = `${r}.${i}`;
764
- if (!await crypto.subtle.verify(Se(y), y, _, A(R)))
765
- throw new a("JWT signature verification failed");
766
- }
767
- let h;
1043
+ header = JSON.parse(buf(b64u(protectedHeader)));
1044
+ } catch (cause) {
1045
+ throw new OPE("failed to parse JWT Header body as base64url encoded JSON", { cause });
1046
+ }
1047
+ if (!isJsonObject(header)) {
1048
+ throw new OPE("JWT Header must be a top level object");
1049
+ }
1050
+ checkAlg(header);
1051
+ if (header.crit !== void 0) {
1052
+ throw new OPE('unexpected JWT "crit" header parameter');
1053
+ }
1054
+ const signature = b64u(encodedSignature);
1055
+ let key;
1056
+ if (getKey !== noSignatureCheck) {
1057
+ key = await getKey(header);
1058
+ const input = `${protectedHeader}.${payload}`;
1059
+ const verified = await crypto.subtle.verify(keyToSubtle(key), key, signature, buf(input));
1060
+ if (!verified) {
1061
+ throw new OPE("JWT signature verification failed");
1062
+ }
1063
+ }
1064
+ let claims;
768
1065
  try {
769
- h = JSON.parse(A(k(i)));
770
- } catch (R) {
771
- throw new a("failed to parse JWT Payload body as base64url encoded JSON", { cause: R });
772
- }
773
- if (!C(h))
774
- throw new a("JWT Payload must be a top level object");
775
- const L = Q() + o;
776
- if (h.exp !== void 0) {
777
- if (typeof h.exp != "number")
778
- throw new a('unexpected JWT "exp" (expiration time) claim type');
779
- if (h.exp <= L - s)
780
- throw new a('unexpected JWT "exp" (expiration time) claim value, timestamp is <= now()');
781
- }
782
- if (h.iat !== void 0 && typeof h.iat != "number")
783
- throw new a('unexpected JWT "iat" (issued at) claim type');
784
- if (h.iss !== void 0 && typeof h.iss != "string")
785
- throw new a('unexpected JWT "iss" (issuer) claim type');
786
- if (h.nbf !== void 0) {
787
- if (typeof h.nbf != "number")
788
- throw new a('unexpected JWT "nbf" (not before) claim type');
789
- if (h.nbf > L + s)
790
- throw new a('unexpected JWT "nbf" (not before) claim value, timestamp is > now()');
791
- }
792
- if (h.aud !== void 0 && typeof h.aud != "string" && !Array.isArray(h.aud))
793
- throw new a('unexpected JWT "aud" (audience) claim type');
794
- return { header: m, claims: h, signature: _, key: y };
795
- }
796
- function kt(e, t, n) {
797
- if (e !== void 0) {
798
- if (n.alg !== e)
799
- throw new a('unexpected JWT "alg" header parameter');
1066
+ claims = JSON.parse(buf(b64u(payload)));
1067
+ } catch (cause) {
1068
+ throw new OPE("failed to parse JWT Payload body as base64url encoded JSON", { cause });
1069
+ }
1070
+ if (!isJsonObject(claims)) {
1071
+ throw new OPE("JWT Payload must be a top level object");
1072
+ }
1073
+ const now = epochTime() + clockSkew2;
1074
+ if (claims.exp !== void 0) {
1075
+ if (typeof claims.exp !== "number") {
1076
+ throw new OPE('unexpected JWT "exp" (expiration time) claim type');
1077
+ }
1078
+ if (claims.exp <= now - clockTolerance2) {
1079
+ throw new OPE('unexpected JWT "exp" (expiration time) claim value, timestamp is <= now()');
1080
+ }
1081
+ }
1082
+ if (claims.iat !== void 0) {
1083
+ if (typeof claims.iat !== "number") {
1084
+ throw new OPE('unexpected JWT "iat" (issued at) claim type');
1085
+ }
1086
+ }
1087
+ if (claims.iss !== void 0) {
1088
+ if (typeof claims.iss !== "string") {
1089
+ throw new OPE('unexpected JWT "iss" (issuer) claim type');
1090
+ }
1091
+ }
1092
+ if (claims.nbf !== void 0) {
1093
+ if (typeof claims.nbf !== "number") {
1094
+ throw new OPE('unexpected JWT "nbf" (not before) claim type');
1095
+ }
1096
+ if (claims.nbf > now + clockTolerance2) {
1097
+ throw new OPE('unexpected JWT "nbf" (not before) claim value, timestamp is > now()');
1098
+ }
1099
+ }
1100
+ if (claims.aud !== void 0) {
1101
+ if (typeof claims.aud !== "string" && !Array.isArray(claims.aud)) {
1102
+ throw new OPE('unexpected JWT "aud" (audience) claim type');
1103
+ }
1104
+ }
1105
+ return { header, claims, signature, key };
1106
+ }
1107
+ function checkSigningAlgorithm(client, issuer, header) {
1108
+ if (client !== void 0) {
1109
+ if (header.alg !== client) {
1110
+ throw new OPE('unexpected JWT "alg" header parameter');
1111
+ }
800
1112
  return;
801
1113
  }
802
- if (Array.isArray(t)) {
803
- if (!t.includes(n.alg))
804
- throw new a('unexpected JWT "alg" header parameter');
1114
+ if (Array.isArray(issuer)) {
1115
+ if (!issuer.includes(header.alg)) {
1116
+ throw new OPE('unexpected JWT "alg" header parameter');
1117
+ }
805
1118
  return;
806
1119
  }
807
- if (n.alg !== "RS256")
808
- throw new a('unexpected JWT "alg" header parameter');
809
- }
810
- function E(e, t) {
811
- const { 0: n, length: o } = e.getAll(t);
812
- if (o > 1)
813
- throw new a(`"${t}" parameter must be provided only once`);
814
- return n;
1120
+ if (header.alg !== "RS256") {
1121
+ throw new OPE('unexpected JWT "alg" header parameter');
1122
+ }
815
1123
  }
816
- const Tt = Symbol(), At = Symbol();
817
- function Rt(e, t, n, o) {
818
- if (j(e), z(t), n instanceof URL && (n = n.searchParams), !(n instanceof URLSearchParams))
1124
+ function getURLSearchParameter(parameters, name) {
1125
+ const { 0: value, length } = parameters.getAll(name);
1126
+ if (length > 1) {
1127
+ throw new OPE(`"${name}" parameter must be provided only once`);
1128
+ }
1129
+ return value;
1130
+ }
1131
+ const skipStateCheck = Symbol();
1132
+ const expectNoState = Symbol();
1133
+ function validateAuthResponse(as, client, parameters, expectedState) {
1134
+ assertAs(as);
1135
+ assertClient(client);
1136
+ if (parameters instanceof URL) {
1137
+ parameters = parameters.searchParams;
1138
+ }
1139
+ if (!(parameters instanceof URLSearchParams)) {
819
1140
  throw new TypeError('"parameters" must be an instance of URLSearchParams, or URL');
820
- if (E(n, "response"))
821
- throw new a('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()');
822
- const s = E(n, "iss"), r = E(n, "state");
823
- if (!s && e.authorization_response_iss_parameter_supported)
824
- throw new a('response parameter "iss" (issuer) missing');
825
- if (s && s !== e.issuer)
826
- throw new a('unexpected "iss" (issuer) response parameter value');
827
- switch (o) {
1141
+ }
1142
+ if (getURLSearchParameter(parameters, "response")) {
1143
+ throw new OPE('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()');
1144
+ }
1145
+ const iss = getURLSearchParameter(parameters, "iss");
1146
+ const state = getURLSearchParameter(parameters, "state");
1147
+ if (!iss && as.authorization_response_iss_parameter_supported) {
1148
+ throw new OPE('response parameter "iss" (issuer) missing');
1149
+ }
1150
+ if (iss && iss !== as.issuer) {
1151
+ throw new OPE('unexpected "iss" (issuer) response parameter value');
1152
+ }
1153
+ switch (expectedState) {
828
1154
  case void 0:
829
- case At:
830
- if (r !== void 0)
831
- throw new a('unexpected "state" response parameter encountered');
1155
+ case expectNoState:
1156
+ if (state !== void 0) {
1157
+ throw new OPE('unexpected "state" response parameter encountered');
1158
+ }
832
1159
  break;
833
- case Tt:
1160
+ case skipStateCheck:
834
1161
  break;
835
1162
  default:
836
- if (!w(o))
837
- throw new a('"expectedState" must be a non-empty string');
838
- if (r === void 0)
839
- throw new a('response parameter "state" missing');
840
- if (r !== o)
841
- throw new a('unexpected "state" response parameter value');
842
- }
843
- const i = E(n, "error");
844
- if (i)
1163
+ if (!validateString(expectedState)) {
1164
+ throw new OPE('"expectedState" must be a non-empty string');
1165
+ }
1166
+ if (state === void 0) {
1167
+ throw new OPE('response parameter "state" missing');
1168
+ }
1169
+ if (state !== expectedState) {
1170
+ throw new OPE('unexpected "state" response parameter value');
1171
+ }
1172
+ }
1173
+ const error = getURLSearchParameter(parameters, "error");
1174
+ if (error) {
845
1175
  return {
846
- error: i,
847
- error_description: E(n, "error_description"),
848
- error_uri: E(n, "error_uri")
1176
+ error,
1177
+ error_description: getURLSearchParameter(parameters, "error_description"),
1178
+ error_uri: getURLSearchParameter(parameters, "error_uri")
849
1179
  };
850
- const d = E(n, "id_token"), g = E(n, "token");
851
- if (d !== void 0 || g !== void 0)
852
- throw new v("implicit and hybrid flows are not supported");
853
- return gt(new URLSearchParams(n));
1180
+ }
1181
+ const id_token = getURLSearchParameter(parameters, "id_token");
1182
+ const token = getURLSearchParameter(parameters, "token");
1183
+ if (id_token !== void 0 || token !== void 0) {
1184
+ throw new UnsupportedOperationError("implicit and hybrid flows are not supported");
1185
+ }
1186
+ return brand(new URLSearchParams(parameters));
854
1187
  }
855
- class P extends Error {
1188
+ class AuthorizationError extends Error {
856
1189
  }
857
- class G extends P {
858
- constructor(t, n, o) {
859
- super(t, o), this.error = n;
1190
+ class OAuthAuthorizationError extends AuthorizationError {
1191
+ constructor(message, error, options) {
1192
+ super(message, options);
1193
+ this.error = error;
860
1194
  }
861
1195
  }
862
- function xt({
863
- handleCallback: e
1196
+ function Callback({
1197
+ handleCallback
864
1198
  }) {
865
- const t = Ce(!1), [n, o] = je(void 0), s = Pe();
866
- return ze(() => {
867
- t.current || (t.current = !0, e().then(() => {
868
- s("/");
869
- }).catch((r) => {
870
- o(r);
871
- }));
872
- }, []), n ? n instanceof G ? /* @__PURE__ */ T.jsxs("div", { children: [
873
- /* @__PURE__ */ T.jsx("h2", { children: "Error" }),
874
- /* @__PURE__ */ T.jsxs("pre", { children: [
875
- n.error.error,
876
- n.error.error_description,
877
- n.error.error_uri
878
- ] })
879
- ] }) : /* @__PURE__ */ T.jsxs("div", { children: [
880
- /* @__PURE__ */ T.jsx("h2", { children: "Error" }),
881
- /* @__PURE__ */ T.jsxs("pre", { children: [
882
- n.message,
883
- n.stack
884
- ] })
885
- ] }) : /* @__PURE__ */ T.jsx("div", { children: "Loading..." });
886
- }
887
- const le = "code-verifier";
888
- class Pt {
1199
+ const didInitialize = useRef(false);
1200
+ const [error, setError] = useState(void 0);
1201
+ const navigate = useNavigate();
1202
+ useEffect(() => {
1203
+ if (didInitialize.current) {
1204
+ return;
1205
+ }
1206
+ didInitialize.current = true;
1207
+ handleCallback().then(() => {
1208
+ navigate("/");
1209
+ }).catch((err) => {
1210
+ setError(err);
1211
+ });
1212
+ }, []);
1213
+ if (error) {
1214
+ if (error instanceof OAuthAuthorizationError) {
1215
+ return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
1216
+ /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { children: "Error" }),
1217
+ /* @__PURE__ */ jsxRuntimeExports.jsxs("pre", { children: [
1218
+ error.error.error,
1219
+ error.error.error_description,
1220
+ error.error.error_uri
1221
+ ] })
1222
+ ] });
1223
+ }
1224
+ return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
1225
+ /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { children: "Error" }),
1226
+ /* @__PURE__ */ jsxRuntimeExports.jsxs("pre", { children: [
1227
+ error.message,
1228
+ error.stack
1229
+ ] })
1230
+ ] });
1231
+ }
1232
+ return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: "Loading..." });
1233
+ }
1234
+ const CODE_VERIFIER_KEY = "code-verifier";
1235
+ class OpenIDAuthenticationProvider {
889
1236
  constructor({
890
- issuer: t,
891
- authorizationEndpoint: n,
892
- tokenEndpoint: o,
893
- clientId: s
1237
+ issuer,
1238
+ authorizationEndpoint,
1239
+ tokenEndpoint,
1240
+ clientId
894
1241
  }) {
895
- S(this, "client");
896
- S(this, "issuer");
897
- S(this, "authorizationEndpoint");
898
- S(this, "tokenEndpoint");
899
- S(this, "authorizationServer");
900
- S(this, "tokens");
901
- S(this, "callbackUrlPath", "/oauth/callback");
902
- S(this, "logoutRedirectUrlPath", "/");
903
- S(this, "handleCallback", async () => {
904
- const t = new URL(window.location.href), n = t.searchParams.get("state"), o = localStorage.getItem(le);
905
- if (!o)
906
- throw new P(
1242
+ __publicField(this, "client");
1243
+ __publicField(this, "issuer");
1244
+ __publicField(this, "authorizationEndpoint");
1245
+ __publicField(this, "tokenEndpoint");
1246
+ __publicField(this, "authorizationServer");
1247
+ __publicField(this, "tokens");
1248
+ __publicField(this, "callbackUrlPath", "/oauth/callback");
1249
+ __publicField(this, "logoutRedirectUrlPath", "/");
1250
+ __publicField(this, "handleCallback", async () => {
1251
+ const url = new URL(window.location.href);
1252
+ const state = url.searchParams.get("state");
1253
+ const codeVerifier = localStorage.getItem(CODE_VERIFIER_KEY);
1254
+ if (!codeVerifier) {
1255
+ throw new AuthorizationError(
907
1256
  "Code verifier not found. Invalid auth state."
908
1257
  );
909
- const s = await this.getAuthServer(), r = Rt(
910
- s,
1258
+ }
1259
+ const authServer = await this.getAuthServer();
1260
+ const params = validateAuthResponse(
1261
+ authServer,
911
1262
  this.client,
912
- t.searchParams,
913
- n ?? void 0
1263
+ url.searchParams,
1264
+ state ?? void 0
914
1265
  );
915
- if (B(r))
916
- throw oe.error("Error validating OAuth response", r), new G(
1266
+ if (isOAuth2Error(params)) {
1267
+ logger.error("Error validating OAuth response", params);
1268
+ throw new OAuthAuthorizationError(
917
1269
  "Error validating OAuth response",
918
- r
1270
+ params
919
1271
  );
920
- const i = new URL(t);
921
- i.pathname = this.callbackUrlPath, i.search = "";
922
- const d = await mt(
923
- s,
1272
+ }
1273
+ const redirectUrl = new URL(url);
1274
+ redirectUrl.pathname = this.callbackUrlPath;
1275
+ redirectUrl.search = "";
1276
+ const response = await authorizationCodeGrantRequest(
1277
+ authServer,
924
1278
  this.client,
925
- r,
926
- i.toString(),
927
- o
928
- ), g = await bt(
929
- s,
1279
+ params,
1280
+ redirectUrl.toString(),
1281
+ codeVerifier
1282
+ );
1283
+ const oauthResult = await processAuthorizationCodeOAuth2Response(
1284
+ authServer,
930
1285
  this.client,
931
- d
1286
+ response
932
1287
  );
933
- this.setTokensFromResponse(g);
934
- const m = await this.getAccessToken(), y = await (await ut(
935
- s,
1288
+ this.setTokensFromResponse(oauthResult);
1289
+ const accessToken = await this.getAccessToken();
1290
+ const userInfoResponse = await userInfoRequest(
1291
+ authServer,
936
1292
  this.client,
937
- m
938
- )).json(), h = {
939
- sub: y.sub,
940
- email: y.email,
941
- name: y.name,
942
- emailVerified: y.email_verified ?? !1,
943
- pictureUrl: y.picture
1293
+ accessToken
1294
+ );
1295
+ const userInfo = await userInfoResponse.json();
1296
+ const profile = {
1297
+ sub: userInfo.sub,
1298
+ email: userInfo.email,
1299
+ name: userInfo.name,
1300
+ emailVerified: userInfo.email_verified ?? false,
1301
+ pictureUrl: userInfo.picture
944
1302
  };
945
- re.setState({
946
- isAuthenticated: !0,
947
- isPending: !1,
948
- profile: h
1303
+ useAuthState.setState({
1304
+ isAuthenticated: true,
1305
+ isPending: false,
1306
+ profile
949
1307
  });
950
1308
  });
951
1309
  this.client = {
952
- client_id: s,
1310
+ client_id: clientId,
953
1311
  token_endpoint_auth_method: "none"
954
- }, this.issuer = t, this.authorizationEndpoint = n, this.tokenEndpoint = o;
1312
+ };
1313
+ this.issuer = issuer;
1314
+ this.authorizationEndpoint = authorizationEndpoint;
1315
+ this.tokenEndpoint = tokenEndpoint;
955
1316
  }
956
1317
  async getAuthServer() {
957
- if (!this.authorizationServer)
958
- if (this.tokenEndpoint && this.authorizationEndpoint)
1318
+ if (!this.authorizationServer) {
1319
+ if (this.tokenEndpoint && this.authorizationEndpoint) {
959
1320
  this.authorizationServer = {
960
1321
  issuer: new URL(this.authorizationEndpoint).origin,
961
1322
  authorization_endpoint: this.authorizationEndpoint,
962
1323
  token_endpoint: this.tokenEndpoint,
963
1324
  code_challenge_methods_supported: []
964
1325
  };
965
- else {
966
- const t = new URL(this.issuer), n = await Fe(t);
967
- this.authorizationServer = await Me(
968
- t,
969
- n
1326
+ } else {
1327
+ const issuerUrl = new URL(this.issuer);
1328
+ const response = await discoveryRequest(issuerUrl);
1329
+ this.authorizationServer = await processDiscoveryResponse(
1330
+ issuerUrl,
1331
+ response
970
1332
  );
971
1333
  }
1334
+ }
972
1335
  return this.authorizationServer;
973
1336
  }
974
1337
  /**
975
1338
  * Sets the tokens from various OAuth responses
976
1339
  * @param response
977
1340
  */
978
- setTokensFromResponse(t) {
979
- if (B(t))
980
- throw oe.error("Bad Token Response", t), new G("Bad Token Response", t);
981
- if (!t.expires_in)
982
- throw new P("No expires_in in response");
1341
+ setTokensFromResponse(response) {
1342
+ if (isOAuth2Error(response)) {
1343
+ logger.error("Bad Token Response", response);
1344
+ throw new OAuthAuthorizationError("Bad Token Response", response);
1345
+ }
1346
+ if (!response.expires_in) {
1347
+ throw new AuthorizationError("No expires_in in response");
1348
+ }
983
1349
  this.tokens = {
984
- accessToken: t.access_token,
985
- refreshToken: t.refresh_token,
986
- expiresOn: new Date(Date.now() + t.expires_in * 1e3),
987
- tokenType: t.token_type
1350
+ accessToken: response.access_token,
1351
+ refreshToken: response.refresh_token,
1352
+ expiresOn: new Date(Date.now() + response.expires_in * 1e3),
1353
+ tokenType: response.token_type
988
1354
  };
989
1355
  }
990
1356
  async initialize() {
991
1357
  }
992
1358
  async login() {
993
- var d;
994
- const t = "S256", n = await this.getAuthServer();
995
- if (!n.authorization_endpoint)
996
- throw new P("No authorization endpoint");
997
- const o = Be(), s = await qe(o);
998
- localStorage.setItem(le, o);
999
- const r = new URL(
1000
- n.authorization_endpoint
1001
- ), i = new URL(window.location.href);
1002
- if (i.pathname = this.callbackUrlPath, i.search = "", r.searchParams.set("client_id", this.client.client_id), r.searchParams.set("redirect_uri", i.toString()), r.searchParams.set("response_type", "code"), r.searchParams.set("scope", "openid+profile+email"), r.searchParams.set("code_challenge", s), r.searchParams.set(
1359
+ var _a2;
1360
+ const code_challenge_method = "S256";
1361
+ const authorizationServer = await this.getAuthServer();
1362
+ if (!authorizationServer.authorization_endpoint) {
1363
+ throw new AuthorizationError("No authorization endpoint");
1364
+ }
1365
+ const codeVerifier = generateRandomCodeVerifier();
1366
+ const codeChallenge = await calculatePKCECodeChallenge(codeVerifier);
1367
+ localStorage.setItem(CODE_VERIFIER_KEY, codeVerifier);
1368
+ const authorizationUrl = new URL(
1369
+ authorizationServer.authorization_endpoint
1370
+ );
1371
+ const redirectUrl = new URL(window.location.href);
1372
+ redirectUrl.pathname = this.callbackUrlPath;
1373
+ redirectUrl.search = "";
1374
+ authorizationUrl.searchParams.set("client_id", this.client.client_id);
1375
+ authorizationUrl.searchParams.set("redirect_uri", redirectUrl.toString());
1376
+ authorizationUrl.searchParams.set("response_type", "code");
1377
+ authorizationUrl.searchParams.set("scope", "openid+profile+email");
1378
+ authorizationUrl.searchParams.set("code_challenge", codeChallenge);
1379
+ authorizationUrl.searchParams.set(
1003
1380
  "code_challenge_method",
1004
- t
1005
- ), ((d = n.code_challenge_methods_supported) == null ? void 0 : d.includes("S256")) !== !0) {
1006
- const g = Ge();
1007
- r.searchParams.set("state", g);
1381
+ code_challenge_method
1382
+ );
1383
+ if (((_a2 = authorizationServer.code_challenge_methods_supported) == null ? void 0 : _a2.includes("S256")) !== true) {
1384
+ const state = generateRandomState();
1385
+ authorizationUrl.searchParams.set("state", state);
1008
1386
  }
1009
- location.href = r.href;
1387
+ location.href = authorizationUrl.href;
1010
1388
  }
1011
1389
  async getAccessToken() {
1012
- const t = await this.getAuthServer();
1013
- if (!this.tokens)
1014
- throw new P("User is not authenticated");
1390
+ const as = await this.getAuthServer();
1391
+ if (!this.tokens) {
1392
+ throw new AuthorizationError("User is not authenticated");
1393
+ }
1015
1394
  if (this.tokens.expiresOn < /* @__PURE__ */ new Date()) {
1016
- if (!this.tokens.refreshToken)
1017
- throw new P(
1395
+ if (!this.tokens.refreshToken) {
1396
+ throw new AuthorizationError(
1018
1397
  "Token expired and no refresh token available"
1019
1398
  );
1020
- const n = await dt(
1021
- t,
1399
+ }
1400
+ const request = await refreshTokenGrantRequest(
1401
+ as,
1022
1402
  this.client,
1023
1403
  this.tokens.refreshToken
1024
- ), o = await ft(
1025
- t,
1404
+ );
1405
+ const response = await processRefreshTokenResponse(
1406
+ as,
1026
1407
  this.client,
1027
- n
1408
+ request
1028
1409
  );
1029
- this.setTokensFromResponse(o);
1410
+ this.setTokensFromResponse(response);
1030
1411
  }
1031
1412
  return this.tokens.accessToken;
1032
1413
  }
1033
1414
  async logout() {
1034
- re.setState({
1035
- isAuthenticated: !1,
1036
- isPending: !1,
1415
+ useAuthState.setState({
1416
+ isAuthenticated: false,
1417
+ isPending: false,
1037
1418
  profile: void 0
1038
1419
  });
1039
- const t = await this.getAuthServer(), n = new URL(window.location.href);
1040
- n.pathname = this.logoutRedirectUrlPath;
1041
- let o;
1042
- t.end_session_endpoint ? (o = new URL(t.end_session_endpoint), o.searchParams.set(
1043
- "post_logout_redirect_uri",
1044
- n.toString()
1045
- )) : o = n;
1420
+ const as = await this.getAuthServer();
1421
+ const redirectUrl = new URL(window.location.href);
1422
+ redirectUrl.pathname = this.logoutRedirectUrlPath;
1423
+ let logoutUrl;
1424
+ if (as.end_session_endpoint) {
1425
+ logoutUrl = new URL(as.end_session_endpoint);
1426
+ logoutUrl.searchParams.set(
1427
+ "post_logout_redirect_uri",
1428
+ redirectUrl.toString()
1429
+ );
1430
+ } else {
1431
+ logoutUrl = redirectUrl;
1432
+ }
1046
1433
  }
1047
1434
  getRoutes() {
1048
1435
  return [
1049
1436
  {
1050
1437
  path: this.callbackUrlPath,
1051
- element: /* @__PURE__ */ T.jsx(xt, { handleCallback: this.handleCallback })
1438
+ element: /* @__PURE__ */ jsxRuntimeExports.jsx(Callback, { handleCallback: this.handleCallback })
1052
1439
  }
1053
1440
  ];
1054
1441
  }
1055
1442
  }
1056
- const Jt = (e) => new Pt(e);
1443
+ const openIDAuth = (options) => new OpenIDAuthenticationProvider(options);
1057
1444
  export {
1058
- Pt as OpenIDAuthenticationProvider,
1059
- Jt as default
1445
+ OpenIDAuthenticationProvider,
1446
+ openIDAuth as default
1060
1447
  };
1061
1448
  //# sourceMappingURL=zudoku.auth-openid.js.map