@strivacity/sdk-core 1.0.1 → 2.0.0-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/README.md +9 -7
- package/dist/flows/BaseFlow.cjs +1 -1
- package/dist/flows/BaseFlow.cjs.map +1 -1
- package/dist/flows/BaseFlow.d.ts +42 -55
- package/dist/flows/BaseFlow.mjs +1 -1
- package/dist/flows/BaseFlow.mjs.map +1 -1
- package/dist/flows/NativeFlow.cjs +2 -0
- package/dist/flows/NativeFlow.cjs.map +1 -0
- package/dist/flows/NativeFlow.d.ts +24 -0
- package/dist/flows/NativeFlow.mjs +2 -0
- package/dist/flows/NativeFlow.mjs.map +1 -0
- package/dist/flows/PopupFlow.cjs +1 -1
- package/dist/flows/PopupFlow.cjs.map +1 -1
- package/dist/flows/PopupFlow.d.ts +7 -14
- package/dist/flows/PopupFlow.mjs +1 -1
- package/dist/flows/PopupFlow.mjs.map +1 -1
- package/dist/flows/RedirectFlow.cjs +1 -1
- package/dist/flows/RedirectFlow.cjs.map +1 -1
- package/dist/flows/RedirectFlow.d.ts +6 -12
- package/dist/flows/RedirectFlow.mjs +1 -1
- package/dist/flows/RedirectFlow.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +10 -4
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/storages/LocalStorage.cjs +1 -1
- package/dist/storages/LocalStorage.cjs.map +1 -1
- package/dist/storages/LocalStorage.d.ts +3 -3
- package/dist/storages/LocalStorage.mjs +1 -1
- package/dist/storages/LocalStorage.mjs.map +1 -1
- package/dist/storages/SessionStorage.cjs +1 -1
- package/dist/storages/SessionStorage.cjs.map +1 -1
- package/dist/storages/SessionStorage.d.ts +3 -3
- package/dist/storages/SessionStorage.mjs +1 -1
- package/dist/storages/SessionStorage.mjs.map +1 -1
- package/dist/types.cjs +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.ts +257 -25
- package/dist/types.mjs +1 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils/HttpClient.cjs +2 -0
- package/dist/utils/HttpClient.cjs.map +1 -0
- package/dist/utils/HttpClient.d.ts +4 -0
- package/dist/utils/HttpClient.mjs +2 -0
- package/dist/utils/HttpClient.mjs.map +1 -0
- package/dist/utils/Metadata.cjs +2 -0
- package/dist/utils/Metadata.cjs.map +1 -0
- package/dist/{Metadata.d.ts → utils/Metadata.d.ts} +26 -2
- package/dist/utils/Metadata.mjs +2 -0
- package/dist/utils/Metadata.mjs.map +1 -0
- package/dist/utils/NativeFlowHandler.cjs +2 -0
- package/dist/utils/NativeFlowHandler.cjs.map +1 -0
- package/dist/utils/NativeFlowHandler.d.ts +54 -0
- package/dist/utils/NativeFlowHandler.mjs +2 -0
- package/dist/utils/NativeFlowHandler.mjs.map +1 -0
- package/dist/utils/Session.cjs +2 -0
- package/dist/utils/Session.cjs.map +1 -0
- package/dist/{Session.d.ts → utils/Session.d.ts} +1 -1
- package/dist/utils/Session.mjs +2 -0
- package/dist/utils/Session.mjs.map +1 -0
- package/dist/utils/State.cjs +2 -0
- package/dist/utils/State.cjs.map +1 -0
- package/dist/utils/State.mjs +2 -0
- package/dist/utils/State.mjs.map +1 -0
- package/dist/utils/base64Url.cjs.map +1 -1
- package/dist/utils/base64Url.mjs.map +1 -1
- package/dist/utils/crypto.cjs.map +1 -1
- package/dist/utils/crypto.mjs.map +1 -1
- package/dist/utils/date.cjs.map +1 -1
- package/dist/utils/date.mjs.map +1 -1
- package/dist/utils/errors.cjs +2 -0
- package/dist/utils/errors.cjs.map +1 -0
- package/dist/utils/errors.d.ts +4 -0
- package/dist/utils/errors.mjs +2 -0
- package/dist/utils/errors.mjs.map +1 -0
- package/dist/utils/handlers.cjs +1 -1
- package/dist/utils/handlers.cjs.map +1 -1
- package/dist/utils/handlers.d.ts +11 -11
- package/dist/utils/handlers.mjs +1 -1
- package/dist/utils/handlers.mjs.map +1 -1
- package/dist/utils/jwt.cjs +1 -1
- package/dist/utils/jwt.cjs.map +1 -1
- package/dist/utils/jwt.mjs +1 -1
- package/dist/utils/jwt.mjs.map +1 -1
- package/dist/utils/object.cjs +2 -0
- package/dist/utils/object.cjs.map +1 -0
- package/dist/utils/object.d.ts +1 -0
- package/dist/utils/object.mjs +2 -0
- package/dist/utils/object.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/Metadata.cjs +0 -2
- package/dist/Metadata.cjs.map +0 -1
- package/dist/Metadata.mjs +0 -2
- package/dist/Metadata.mjs.map +0 -1
- package/dist/Session.cjs +0 -2
- package/dist/Session.cjs.map +0 -1
- package/dist/Session.mjs +0 -2
- package/dist/Session.mjs.map +0 -1
- package/dist/State.cjs +0 -2
- package/dist/State.cjs.map +0 -1
- package/dist/State.mjs +0 -2
- package/dist/State.mjs.map +0 -1
- package/dist/utils/constants.cjs +0 -2
- package/dist/utils/constants.cjs.map +0 -1
- package/dist/utils/constants.d.ts +0 -6
- package/dist/utils/constants.mjs +0 -2
- package/dist/utils/constants.mjs.map +0 -1
- package/dist/utils/fetch.cjs +0 -2
- package/dist/utils/fetch.cjs.map +0 -1
- package/dist/utils/fetch.d.ts +0 -2
- package/dist/utils/fetch.mjs +0 -2
- package/dist/utils/fetch.mjs.map +0 -1
- /package/dist/{State.d.ts → utils/State.d.ts} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handlers.cjs","sources":["../../src/utils/handlers.ts"],"sourcesContent":["import type { RedirectParams, ResponseMode,
|
|
1
|
+
{"version":3,"file":"handlers.cjs","sources":["../../src/utils/handlers.ts"],"sourcesContent":["import type { RedirectParams, ResponseMode, PopupParams, PopupWindowFeatures } from '../types';\n\nlet popupWindow: WindowProxy | null = null;\n\n/**\n * Handles URL redirection to a target window using a specified location method.\n *\n * @param {string} url The URL to redirect to.\n * @param {RedirectParams} [params] Optional parameters for the redirection, including the target window and location method.\n * @returns {Promise<void>} A promise that resolves when the redirection occurs.\n */\nasync function redirectUrlHandler(url: string, params?: RedirectParams): Promise<void> {\n\tconst targetWindow = params?.targetWindow === 'top' ? window.top : window.self;\n\tconst method = params?.locationMethod || 'assign';\n\n\tif (targetWindow) {\n\t\ttargetWindow.location[method](url);\n\t}\n\n\t// NOTE: Wait for the previous action\n\treturn new Promise(() => undefined);\n}\n\n/**\n * Handles the callback after a redirect and parses the response from the URL.\n *\n * @param {string} [url=globalThis.window?.location.href] The URL to parse, defaults to the current window location.\n * @param {ResponseMode} responseMode The response mode, either 'query' or 'fragment'.\n * @returns {Promise<Record<string, string>>} A promise that resolves to the parsed response data.\n */\nfunction redirectCallbackHandler(url: string = globalThis.window?.location.href, responseMode?: ResponseMode): Promise<Record<string, string>> {\n\tconst data = new URL(url)[responseMode === 'query' ? 'search' : 'hash'].slice(1);\n\n\treturn Promise.resolve(Object.fromEntries(new URLSearchParams(data)));\n}\n\n/**\n * Opens a popup window to handle URL redirection and resolves with the data received from the popup.\n *\n * @param {string} url The URL to redirect to in the popup.\n * @param {PopupParams} [params] Optional parameters for the popup, including window features and target.\n * @returns {Promise<Record<string, string>>} A promise that resolves to the data received from the popup window.\n * @throws {Error} If the popup window is blocked or closed by the user.\n */\nasync function popupUrlHandler(url: string, params?: PopupParams): Promise<Record<string, string>> {\n\tconst disposables = new Set<() => void>();\n\tconst closeWindow = (): void => {\n\t\tif (popupWindow) {\n\t\t\tif (!popupWindow.closed) {\n\t\t\t\tpopupWindow.close();\n\t\t\t}\n\n\t\t\tpopupWindow = null;\n\t\t}\n\n\t\tfor (const dispose of disposables) {\n\t\t\tdispose();\n\t\t}\n\n\t\tdisposables.clear();\n\t};\n\n\tif (popupWindow) {\n\t\tcloseWindow();\n\t}\n\n\tconst popupWindowFeatures: PopupWindowFeatures = {\n\t\tlocation: false,\n\t\ttoolbar: false,\n\t\theight: 640,\n\t\t...params?.popupWindowFeatures,\n\t};\n\n\tif (popupWindowFeatures.width === undefined) {\n\t\tpopupWindowFeatures.width = [800, 720, 600, 480].find((width) => width <= window.outerWidth / 1.618) ?? 360;\n\t}\n\n\tpopupWindowFeatures.left = Math.max(0, Math.round(window.screenX + (window.outerWidth - popupWindowFeatures.width) / 2));\n\n\tif (popupWindowFeatures.height !== undefined) {\n\t\tpopupWindowFeatures.top = Math.max(0, Math.round(window.screenY + (window.outerHeight - popupWindowFeatures.height) / 2));\n\t}\n\n\tpopupWindow = window.open(\n\t\tundefined,\n\t\tparams?.popupWindowTarget || '_blank',\n\t\tObject.entries(popupWindowFeatures)\n\t\t\t.filter(([, value]) => value !== null)\n\t\t\t.map(([key, value]) => `${key}=${typeof value !== 'boolean' ? (value as string) : value ? 'yes' : 'no'}`)\n\t\t\t.join(','),\n\t);\n\n\tif (!popupWindow) {\n\t\tthrow new Error('Popup window blocked');\n\t}\n\n\tpopupWindow.focus();\n\tpopupWindow.location.replace(url);\n\n\tconst data = await new Promise<Record<string, string>>((resolve, reject) => {\n\t\tconst listener = (event: MessageEvent<Record<string, string>>) => {\n\t\t\tif (event.origin === window.location.origin && event.source === popupWindow && event.data) {\n\t\t\t\tresolve(event.data);\n\t\t\t}\n\t\t};\n\n\t\tconst timer = setInterval(() => {\n\t\t\tif (popupWindow?.closed) {\n\t\t\t\tclearInterval(timer);\n\t\t\t\treject(Error('Popup closed by user'));\n\t\t\t}\n\t\t}, 500);\n\n\t\twindow.addEventListener('message', listener);\n\t\tdisposables.add(() => window.removeEventListener('message', listener));\n\t\tdisposables.add(() => clearInterval(timer));\n\t});\n\n\tcloseWindow();\n\n\treturn data;\n}\n\n/**\n * Handles the callback from a popup window, parsing the response parameters from the URL and posting them to the opener window.\n *\n * @param {string} [_url] the URL is not used in this function, but it is kept for type compatibility.\n * @param {ResponseMode} responseMode The response mode, either 'query' or 'fragment'.\n */\nfunction popupCallbackHandler(_url?: string, responseMode?: ResponseMode): Promise<void> {\n\tconst args: Record<string, string> = {};\n\n\tif (responseMode === 'fragment') {\n\t\tnew URLSearchParams(globalThis.window?.location.hash.replace('#', '?')).forEach((value, key) => (args[key] = value));\n\t} else {\n\t\tnew URLSearchParams(globalThis.window?.location.search).forEach((value, key) => (args[key] = value));\n\t}\n\n\tglobalThis.window?.opener?.postMessage(args, '*');\n\n\t// NOTE: Wait for the previous action\n\treturn new Promise(() => undefined);\n}\n\nexport { redirectUrlHandler, redirectCallbackHandler, popupUrlHandler, popupCallbackHandler };\n"],"names":["popupWindow","redirectUrlHandler","url","params","targetWindow","method","redirectCallbackHandler","_a","responseMode","data","popupUrlHandler","disposables","closeWindow","dispose","popupWindowFeatures","width","value","key","resolve","reject","listener","event","timer","popupCallbackHandler","_url","args","_b","_d","_c"],"mappings":"gFAEA,IAAIA,EAAkC,KAStC,eAAeC,EAAmBC,EAAaC,EAAwC,CACtF,MAAMC,GAAeD,GAAA,YAAAA,EAAQ,gBAAiB,MAAQ,OAAO,IAAM,OAAO,KACpEE,GAASF,GAAA,YAAAA,EAAQ,iBAAkB,SAEzC,OAAIC,GACHA,EAAa,SAASC,CAAM,EAAEH,CAAG,EAI3B,IAAI,QAAQ,IAAA,EAAe,CACnC,CASA,SAASI,EAAwBJ,GAAcK,MAAA,WAAW,SAAX,YAAAA,EAAmB,SAAS,QAAMC,EAA8D,CAC9I,MAAMC,EAAO,IAAI,IAAIP,CAAG,EAAEM,IAAiB,QAAU,SAAW,MAAM,EAAE,MAAM,CAAC,EAE/E,OAAO,QAAQ,QAAQ,OAAO,YAAY,IAAI,gBAAgBC,CAAI,CAAC,CAAC,CACrE,CAUA,eAAeC,EAAgBR,EAAaC,EAAuD,CAClG,MAAMQ,MAAkB,IAClBC,EAAc,IAAY,CAC3BZ,IACEA,EAAY,QAChBA,EAAY,MAAA,EAGbA,EAAc,MAGf,UAAWa,KAAWF,EACrBE,EAAA,EAGDF,EAAY,MAAA,CAAM,EAGfX,GACHY,EAAA,EAGD,MAAME,EAA2C,CAChD,SAAU,GACV,QAAS,GACT,OAAQ,IACR,GAAGX,GAAA,YAAAA,EAAQ,mBAA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EOH,CACR,CAQA,SAASc,EAAqBC,EAAehB,EAA4C,aACxF,MAAMiB,EAA+B,CAAA,EAErC,OAAIjB,IAAiB,WACpB,IAAI,iBAAgBD,EAAA,WAAW,SAAX,YAAAA,EAAmB,SAAS,KAAK,QAAQ,IAAK,IAAI,EAAE,QAAQ,CAACS,EAAOC,IAASQ,EAAKR,CAAG,EAAID,CAAM,EAEnH,IAAI,iBAAgBU,EAAA,WAAW,SAAX,YAAAA,EAAmB,SAAS,MAAM,EAAE,QAAQ,CAACV,EAAOC,IAASQ,EAAKR,CAAG,EAAID,CAAM,GAGpGW,GAAAC,EAAA,WAAW,SAAX,YAAAA,EAAmB,SAAnB,MAAAD,EAA2B,YAAYF,EAAM,KAGtC,IAAI,QAAQ,IAAA,EAAe,CACnC"}
|
package/dist/utils/handlers.d.ts
CHANGED
|
@@ -1,34 +1,34 @@
|
|
|
1
|
-
import { RedirectParams, ResponseMode,
|
|
1
|
+
import { RedirectParams, ResponseMode, PopupParams } from '../types';
|
|
2
2
|
/**
|
|
3
3
|
* Handles URL redirection to a target window using a specified location method.
|
|
4
4
|
*
|
|
5
|
-
* @param {
|
|
6
|
-
* @param {RedirectParams} [
|
|
7
|
-
* @param {boolean} [shouldWait=true] Whether to wait for the previous action (default is true).
|
|
5
|
+
* @param {string} url The URL to redirect to.
|
|
6
|
+
* @param {RedirectParams} [params] Optional parameters for the redirection, including the target window and location method.
|
|
8
7
|
* @returns {Promise<void>} A promise that resolves when the redirection occurs.
|
|
9
8
|
*/
|
|
10
|
-
declare function redirectUrlHandler(url:
|
|
9
|
+
declare function redirectUrlHandler(url: string, params?: RedirectParams): Promise<void>;
|
|
11
10
|
/**
|
|
12
11
|
* Handles the callback after a redirect and parses the response from the URL.
|
|
13
12
|
*
|
|
14
13
|
* @param {string} [url=globalThis.window?.location.href] The URL to parse, defaults to the current window location.
|
|
15
14
|
* @param {ResponseMode} responseMode The response mode, either 'query' or 'fragment'.
|
|
16
|
-
* @returns {Record<string, string
|
|
15
|
+
* @returns {Promise<Record<string, string>>} A promise that resolves to the parsed response data.
|
|
17
16
|
*/
|
|
18
|
-
declare function redirectCallbackHandler(url
|
|
17
|
+
declare function redirectCallbackHandler(url?: string, responseMode?: ResponseMode): Promise<Record<string, string>>;
|
|
19
18
|
/**
|
|
20
19
|
* Opens a popup window to handle URL redirection and resolves with the data received from the popup.
|
|
21
20
|
*
|
|
22
|
-
* @param {
|
|
23
|
-
* @param {
|
|
21
|
+
* @param {string} url The URL to redirect to in the popup.
|
|
22
|
+
* @param {PopupParams} [params] Optional parameters for the popup, including window features and target.
|
|
24
23
|
* @returns {Promise<Record<string, string>>} A promise that resolves to the data received from the popup window.
|
|
25
24
|
* @throws {Error} If the popup window is blocked or closed by the user.
|
|
26
25
|
*/
|
|
27
|
-
declare function popupUrlHandler(url:
|
|
26
|
+
declare function popupUrlHandler(url: string, params?: PopupParams): Promise<Record<string, string>>;
|
|
28
27
|
/**
|
|
29
28
|
* Handles the callback from a popup window, parsing the response parameters from the URL and posting them to the opener window.
|
|
30
29
|
*
|
|
30
|
+
* @param {string} [_url] the URL is not used in this function, but it is kept for type compatibility.
|
|
31
31
|
* @param {ResponseMode} responseMode The response mode, either 'query' or 'fragment'.
|
|
32
32
|
*/
|
|
33
|
-
declare function popupCallbackHandler(responseMode
|
|
33
|
+
declare function popupCallbackHandler(_url?: string, responseMode?: ResponseMode): Promise<void>;
|
|
34
34
|
export { redirectUrlHandler, redirectCallbackHandler, popupUrlHandler, popupCallbackHandler };
|
package/dist/utils/handlers.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
let
|
|
1
|
+
let n=null;async function h(d,o){const e=(o==null?void 0:o.targetWindow)==="top"?window.top:window.self,r=(o==null?void 0:o.locationMethod)||"assign";return e&&e.location[r](d),new Promise(()=>{})}function f(d=(e=>(e=globalThis.window)==null?void 0:e.location.href)(),o){const r=new URL(d)[o==="query"?"search":"hash"].slice(1);return Promise.resolve(Object.fromEntries(new URLSearchParams(r)))}async function u(d,o){const e=new Set,r=()=>{n&&(n.closed||n.close(),n=null);for(const i of e)i();e.clear()};n&&r();const t={location:!1,toolbar:!1,height:640,...o==null?void 0:o.popupWindowFeatures};if(t.width===void 0&&(t.width=[800,720,600,480].find(i=>i<=window.outerWidth/1.618)??360),t.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-t.width)/2)),t.height!==void 0&&(t.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-t.height)/2))),n=window.open(void 0,(o==null?void 0:o.popupWindowTarget)||"_blank",Object.entries(t).filter(([,i])=>i!==null).map(([i,l])=>`${i}=${typeof l!="boolean"?l:l?"yes":"no"}`).join(",")),!n)throw new Error("Popup window blocked");n.focus(),n.location.replace(d);const w=await new Promise((i,l)=>{const c=s=>{s.origin===window.location.origin&&s.source===n&&s.data&&i(s.data)},a=setInterval(()=>{n!=null&&n.closed&&(clearInterval(a),l(Error("Popup closed by user")))},500);window.addEventListener("message",c),e.add(()=>window.removeEventListener("message",c)),e.add(()=>clearInterval(a))});return r(),w}function g(d,o){var r,t,w,i;const e={};return o==="fragment"?new URLSearchParams((r=globalThis.window)==null?void 0:r.location.hash.replace("#","?")).forEach((l,c)=>e[c]=l):new URLSearchParams((t=globalThis.window)==null?void 0:t.location.search).forEach((l,c)=>e[c]=l),(i=(w=globalThis.window)==null?void 0:w.opener)==null||i.postMessage(e,"*"),new Promise(()=>{})}export{g as popupCallbackHandler,u as popupUrlHandler,f as redirectCallbackHandler,h as redirectUrlHandler};
|
|
2
2
|
//# sourceMappingURL=handlers.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handlers.mjs","sources":["../../src/utils/handlers.ts"],"sourcesContent":["import type { RedirectParams, ResponseMode,
|
|
1
|
+
{"version":3,"file":"handlers.mjs","sources":["../../src/utils/handlers.ts"],"sourcesContent":["import type { RedirectParams, ResponseMode, PopupParams, PopupWindowFeatures } from '../types';\n\nlet popupWindow: WindowProxy | null = null;\n\n/**\n * Handles URL redirection to a target window using a specified location method.\n *\n * @param {string} url The URL to redirect to.\n * @param {RedirectParams} [params] Optional parameters for the redirection, including the target window and location method.\n * @returns {Promise<void>} A promise that resolves when the redirection occurs.\n */\nasync function redirectUrlHandler(url: string, params?: RedirectParams): Promise<void> {\n\tconst targetWindow = params?.targetWindow === 'top' ? window.top : window.self;\n\tconst method = params?.locationMethod || 'assign';\n\n\tif (targetWindow) {\n\t\ttargetWindow.location[method](url);\n\t}\n\n\t// NOTE: Wait for the previous action\n\treturn new Promise(() => undefined);\n}\n\n/**\n * Handles the callback after a redirect and parses the response from the URL.\n *\n * @param {string} [url=globalThis.window?.location.href] The URL to parse, defaults to the current window location.\n * @param {ResponseMode} responseMode The response mode, either 'query' or 'fragment'.\n * @returns {Promise<Record<string, string>>} A promise that resolves to the parsed response data.\n */\nfunction redirectCallbackHandler(url: string = globalThis.window?.location.href, responseMode?: ResponseMode): Promise<Record<string, string>> {\n\tconst data = new URL(url)[responseMode === 'query' ? 'search' : 'hash'].slice(1);\n\n\treturn Promise.resolve(Object.fromEntries(new URLSearchParams(data)));\n}\n\n/**\n * Opens a popup window to handle URL redirection and resolves with the data received from the popup.\n *\n * @param {string} url The URL to redirect to in the popup.\n * @param {PopupParams} [params] Optional parameters for the popup, including window features and target.\n * @returns {Promise<Record<string, string>>} A promise that resolves to the data received from the popup window.\n * @throws {Error} If the popup window is blocked or closed by the user.\n */\nasync function popupUrlHandler(url: string, params?: PopupParams): Promise<Record<string, string>> {\n\tconst disposables = new Set<() => void>();\n\tconst closeWindow = (): void => {\n\t\tif (popupWindow) {\n\t\t\tif (!popupWindow.closed) {\n\t\t\t\tpopupWindow.close();\n\t\t\t}\n\n\t\t\tpopupWindow = null;\n\t\t}\n\n\t\tfor (const dispose of disposables) {\n\t\t\tdispose();\n\t\t}\n\n\t\tdisposables.clear();\n\t};\n\n\tif (popupWindow) {\n\t\tcloseWindow();\n\t}\n\n\tconst popupWindowFeatures: PopupWindowFeatures = {\n\t\tlocation: false,\n\t\ttoolbar: false,\n\t\theight: 640,\n\t\t...params?.popupWindowFeatures,\n\t};\n\n\tif (popupWindowFeatures.width === undefined) {\n\t\tpopupWindowFeatures.width = [800, 720, 600, 480].find((width) => width <= window.outerWidth / 1.618) ?? 360;\n\t}\n\n\tpopupWindowFeatures.left = Math.max(0, Math.round(window.screenX + (window.outerWidth - popupWindowFeatures.width) / 2));\n\n\tif (popupWindowFeatures.height !== undefined) {\n\t\tpopupWindowFeatures.top = Math.max(0, Math.round(window.screenY + (window.outerHeight - popupWindowFeatures.height) / 2));\n\t}\n\n\tpopupWindow = window.open(\n\t\tundefined,\n\t\tparams?.popupWindowTarget || '_blank',\n\t\tObject.entries(popupWindowFeatures)\n\t\t\t.filter(([, value]) => value !== null)\n\t\t\t.map(([key, value]) => `${key}=${typeof value !== 'boolean' ? (value as string) : value ? 'yes' : 'no'}`)\n\t\t\t.join(','),\n\t);\n\n\tif (!popupWindow) {\n\t\tthrow new Error('Popup window blocked');\n\t}\n\n\tpopupWindow.focus();\n\tpopupWindow.location.replace(url);\n\n\tconst data = await new Promise<Record<string, string>>((resolve, reject) => {\n\t\tconst listener = (event: MessageEvent<Record<string, string>>) => {\n\t\t\tif (event.origin === window.location.origin && event.source === popupWindow && event.data) {\n\t\t\t\tresolve(event.data);\n\t\t\t}\n\t\t};\n\n\t\tconst timer = setInterval(() => {\n\t\t\tif (popupWindow?.closed) {\n\t\t\t\tclearInterval(timer);\n\t\t\t\treject(Error('Popup closed by user'));\n\t\t\t}\n\t\t}, 500);\n\n\t\twindow.addEventListener('message', listener);\n\t\tdisposables.add(() => window.removeEventListener('message', listener));\n\t\tdisposables.add(() => clearInterval(timer));\n\t});\n\n\tcloseWindow();\n\n\treturn data;\n}\n\n/**\n * Handles the callback from a popup window, parsing the response parameters from the URL and posting them to the opener window.\n *\n * @param {string} [_url] the URL is not used in this function, but it is kept for type compatibility.\n * @param {ResponseMode} responseMode The response mode, either 'query' or 'fragment'.\n */\nfunction popupCallbackHandler(_url?: string, responseMode?: ResponseMode): Promise<void> {\n\tconst args: Record<string, string> = {};\n\n\tif (responseMode === 'fragment') {\n\t\tnew URLSearchParams(globalThis.window?.location.hash.replace('#', '?')).forEach((value, key) => (args[key] = value));\n\t} else {\n\t\tnew URLSearchParams(globalThis.window?.location.search).forEach((value, key) => (args[key] = value));\n\t}\n\n\tglobalThis.window?.opener?.postMessage(args, '*');\n\n\t// NOTE: Wait for the previous action\n\treturn new Promise(() => undefined);\n}\n\nexport { redirectUrlHandler, redirectCallbackHandler, popupUrlHandler, popupCallbackHandler };\n"],"names":["popupWindow","redirectUrlHandler","url","params","targetWindow","method","redirectCallbackHandler","_a","responseMode","data","popupUrlHandler","disposables","closeWindow","dispose","popupWindowFeatures","width","value","key","resolve","reject","listener","event","timer","popupCallbackHandler","_url","_b","_c","_d","args"],"mappings":"AAEA,IAAIA,EAAkC,KAStC,eAAeC,EAAmBC,EAAaC,EAAwC,CACtF,MAAMC,GAAeD,GAAA,YAAAA,EAAQ,gBAAiB,MAAQ,OAAO,IAAM,OAAO,KACpEE,GAASF,GAAA,YAAAA,EAAQ,iBAAkB,SAEzC,OAAIC,GACHA,EAAa,SAASC,CAAM,EAAEH,CAAG,EAI3B,IAAI,QAAQ,IAAA,EAAe,CACnC,CASA,SAASI,EAAwBJ,GAAcK,MAAA,WAAW,SAAX,YAAAA,EAAmB,SAAS,QAAMC,EAA8D,CAC9I,MAAMC,EAAO,IAAI,IAAIP,CAAG,EAAEM,IAAiB,QAAU,SAAW,MAAM,EAAE,MAAM,CAAC,EAE/E,OAAO,QAAQ,QAAQ,OAAO,YAAY,IAAI,gBAAgBC,CAAI,CAAC,CAAC,CACrE,CAUA,eAAeC,EAAgBR,EAAaC,EAAuD,CAClG,MAAMQ,MAAkB,IAClBC,EAAc,IAAY,CAC3BZ,IACEA,EAAY,QAChBA,EAAY,MAAA,EAGbA,EAAc,MAGf,UAAWa,KAAWF,EACrBE,EAAA,EAGDF,EAAY,MAAA,CAAM,EAG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,oBAAoB,UAAWS,CAAQ,CAAC,EACrET,EAAY,IAAI,IAAM,cAAcW,CAAK,CAAC,CAAA,CAC1C,EAED,OAAAV,EAAA,EAEOH,CACR,CAQA,SAASc,EAAqBC,EAAehB,EAA4C,CA/HzF,IAAAD,EAAAkB,EAAAC,EAAAC,EAgIC,MAAMC,EAA+B,CAAA,EAErC,OAAIpB,IAAiB,WACpB,IAAI,iBAAgBD,EAAA,WAAW,SAAX,YAAAA,EAAmB,SAAS,KAAK,QAAQ,IAAK,IAAI,EAAE,QAAQ,CAACS,EAAOC,IAASW,EAAKX,CAAG,EAAID,CAAM,EAEnH,IAAI,iBAAgBS,EAAA,WAAW,SAAX,YAAAA,EAAmB,SAAS,MAAM,EAAE,QAAQ,CAACT,EAAOC,IAASW,EAAKX,CAAG,EAAID,CAAM,GAGpGW,GAAAD,EAAA,WAAW,SAAX,YAAAA,EAAmB,SAAnB,MAAAC,EAA2B,YAAYC,EAAM,KAGtC,IAAI,QAAQ,IAAA,EAAe,CACnC"}
|
package/dist/utils/jwt.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./base64Url.cjs");function i(o){const e=o.split(".");if(e.length!==3)throw Error("Invalid JWT");return JSON.parse(n.Base64Url.decodeUnicode(e[1]))}async function l(o,e,t){const c=n.Base64Url.encode(new TextEncoder().encode(JSON.stringify(o))),d=n.Base64Url.encode(new TextEncoder().encode(JSON.stringify(e))),r=`${c}.${d}`,s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},t,new TextEncoder().encode(r)),a=n.Base64Url.encode(new Uint8Array(s));return`${r}.${a}`}function u(o,e){const t=n.Base64Url.encode(new TextEncoder().encode(JSON.stringify(o))),c=n.Base64Url.encode(new TextEncoder().encode(JSON.stringify(e)));return`${`${t}.${c}`}.signature`}const g={decode:i,generate:l,generateUnsigned:u};exports.jwt=g;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./base64Url.cjs");function i(o){const e=o.split(".");if(e.length!==3)throw new Error("Invalid JWT");return JSON.parse(n.Base64Url.decodeUnicode(e[1]))}async function l(o,e,t){const c=n.Base64Url.encode(new TextEncoder().encode(JSON.stringify(o))),d=n.Base64Url.encode(new TextEncoder().encode(JSON.stringify(e))),r=`${c}.${d}`,s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},t,new TextEncoder().encode(r)),a=n.Base64Url.encode(new Uint8Array(s));return`${r}.${a}`}function u(o,e){const t=n.Base64Url.encode(new TextEncoder().encode(JSON.stringify(o))),c=n.Base64Url.encode(new TextEncoder().encode(JSON.stringify(e)));return`${`${t}.${c}`}.signature`}const g={decode:i,generate:l,generateUnsigned:u};exports.jwt=g;
|
|
2
2
|
//# sourceMappingURL=jwt.cjs.map
|
package/dist/utils/jwt.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jwt.cjs","sources":["../../src/utils/jwt.ts"],"sourcesContent":["import type { JwtClaims } from '../types';\nimport { Base64Url } from './base64Url';\n\n/**\n * Decodes a JWT token and returns its claims.\n *\n * @template R The expected structure of the JWT claims.\n * @param {string} token The JWT token to decode.\n * @returns {R} The decoded JWT claims.\n * @throws {Error} If the token is invalid or has the wrong format.\n */\nfunction decode<R = JwtClaims>(token: string): R {\n\tconst sections = token.split('.');\n\n\tif (sections.length !== 3) {\n\t\tthrow Error('Invalid JWT');\n\t}\n\n\treturn JSON.parse(Base64Url.decodeUnicode(sections[1]));\n}\n\n/**\n * Generates a signed JWT token using the provided header, payload, and private key.\n *\n * @param {object} header The JWT header.\n * @param {object} payload The JWT payload.\n * @param {CryptoKey} privateKey The private key to sign the JWT.\n * @returns {Promise<string>} A promise that resolves to the signed JWT token.\n */\nasync function generate(header: object, payload: object, privateKey: CryptoKey): Promise<string> {\n\tconst encodedHeader = Base64Url.encode(new TextEncoder().encode(JSON.stringify(header)));\n\tconst encodedPayload = Base64Url.encode(new TextEncoder().encode(JSON.stringify(payload)));\n\tconst encodedToken = `${encodedHeader}.${encodedPayload}`;\n\n\tconst signature = await window.crypto.subtle.sign(\n\t\t{\n\t\t\tname: 'ECDSA',\n\t\t\thash: { name: 'SHA-256' },\n\t\t},\n\t\tprivateKey,\n\t\tnew TextEncoder().encode(encodedToken),\n\t);\n\n\tconst encodedSignature = Base64Url.encode(new Uint8Array(signature));\n\treturn `${encodedToken}.${encodedSignature}`;\n}\n\n/**\n * Generates an unsigned JWT token using the provided header and payload.\n * The token will not include a valid signature.\n *\n * @param {object} header The JWT header.\n * @param {object} payload The JWT payload.\n * @returns {string} The unsigned JWT token.\n */\nfunction generateUnsigned(header: object, payload: object): string {\n\tconst encodedHeader = Base64Url.encode(new TextEncoder().encode(JSON.stringify(header)));\n\tconst encodedPayload = Base64Url.encode(new TextEncoder().encode(JSON.stringify(payload)));\n\tconst encodedToken = `${encodedHeader}.${encodedPayload}`;\n\n\treturn `${encodedToken}.signature`;\n}\n\nexport const jwt = {\n\tdecode,\n\tgenerate,\n\tgenerateUnsigned,\n};\n"],"names":["decode","token","sections","Base64Url","generate","header","payload","privateKey","encodedHeader","encodedPayload","encodedToken","signature","encodedSignature","generateUnsigned","jwt"],"mappings":"mHAWA,SAASA,EAAsBC,EAAkB,
|
|
1
|
+
{"version":3,"file":"jwt.cjs","sources":["../../src/utils/jwt.ts"],"sourcesContent":["import type { JwtClaims } from '../types';\nimport { Base64Url } from './base64Url';\n\n/**\n * Decodes a JWT token and returns its claims.\n *\n * @template R The expected structure of the JWT claims.\n * @param {string} token The JWT token to decode.\n * @returns {R} The decoded JWT claims.\n * @throws {Error} If the token is invalid or has the wrong format.\n */\nfunction decode<R = JwtClaims>(token: string): R {\n\tconst sections = token.split('.');\n\n\tif (sections.length !== 3) {\n\t\tthrow new Error('Invalid JWT');\n\t}\n\n\treturn JSON.parse(Base64Url.decodeUnicode(sections[1])) as R;\n}\n\n/**\n * Generates a signed JWT token using the provided header, payload, and private key.\n *\n * @param {object} header The JWT header.\n * @param {object} payload The JWT payload.\n * @param {CryptoKey} privateKey The private key to sign the JWT.\n * @returns {Promise<string>} A promise that resolves to the signed JWT token.\n */\nasync function generate(header: object, payload: object, privateKey: CryptoKey): Promise<string> {\n\tconst encodedHeader = Base64Url.encode(new TextEncoder().encode(JSON.stringify(header)));\n\tconst encodedPayload = Base64Url.encode(new TextEncoder().encode(JSON.stringify(payload)));\n\tconst encodedToken = `${encodedHeader}.${encodedPayload}`;\n\n\tconst signature = await window.crypto.subtle.sign(\n\t\t{\n\t\t\tname: 'ECDSA',\n\t\t\thash: { name: 'SHA-256' },\n\t\t},\n\t\tprivateKey,\n\t\tnew TextEncoder().encode(encodedToken),\n\t);\n\n\tconst encodedSignature = Base64Url.encode(new Uint8Array(signature));\n\treturn `${encodedToken}.${encodedSignature}`;\n}\n\n/**\n * Generates an unsigned JWT token using the provided header and payload.\n * The token will not include a valid signature.\n *\n * @param {object} header The JWT header.\n * @param {object} payload The JWT payload.\n * @returns {string} The unsigned JWT token.\n */\nfunction generateUnsigned(header: object, payload: object): string {\n\tconst encodedHeader = Base64Url.encode(new TextEncoder().encode(JSON.stringify(header)));\n\tconst encodedPayload = Base64Url.encode(new TextEncoder().encode(JSON.stringify(payload)));\n\tconst encodedToken = `${encodedHeader}.${encodedPayload}`;\n\n\treturn `${encodedToken}.signature`;\n}\n\nexport const jwt = {\n\tdecode,\n\tgenerate,\n\tgenerateUnsigned,\n};\n"],"names":["decode","token","sections","Base64Url","generate","header","payload","privateKey","encodedHeader","encodedPayload","encodedToken","signature","encodedSignature","generateUnsigned","jwt"],"mappings":"mHAWA,SAASA,EAAsBC,EAAkB,CAChD,MAAMC,EAAWD,EAAM,MAAM,GAAG,EAEhC,GAAIC,EAAS,SAAW,EACvB,MAAM,IAAI,MAAM,aAAa,EAG9B,OAAO,KAAK,MAAMC,EAAAA,UAAU,cAAcD,EAAS,CAAC,CAAC,CAAC,CACvD,CAUA,eAAeE,EAASC,EAAgBC,EAAiBC,EAAwC,CAChG,MAAMC,EAAgBL,EAAAA,UAAU,OAAO,IAAI,YAAA,EAAc,OAAO,KAAK,UAAUE,CAAM,CAAC,CAAC,EACjFI,EAAiBN,EAAAA,UAAU,OAAO,IAAI,YAAA,EAAc,OAAO,KAAK,UAAUG,CAAO,CAAC,CAAC,EACnFI,EAAe,GAAGF,CAAa,IAAIC,CAAc,GAEjDE,EAAY,MAAM,OAAO,OAAO,OAAO,KAC5C,CACC,KAAM,QACN,KAAM,CAAE,KAAM,SAAA,CAAU,EAEzBJ,EACA,IAAI,YAAA,EAAc,OAAOG,CAAY,CAAA,EAGhCE,EAAmBT,EAAAA,UAAU,OAAO,IAAI,WAAWQ,CAAS,CAAC,EACnE,MAAO,GAAGD,CAAY,IAAIE,CAAgB,EAC3C,CAUA,SAASC,EAAiBR,EAAgBC,EAAyB,CAClE,MAAME,EAAgBL,EAAAA,UAAU,OAAO,IAAI,YAAA,EAAc,OAAO,KAAK,UAAUE,CAAM,CAAC,CAAC,EACjFI,EAAiBN,EAAAA,UAAU,OAAO,IAAI,YAAA,EAAc,OAAO,KAAK,UAAUG,CAAO,CAAC,CAAC,EAGzF,MAAO,GAFc,GAAGE,CAAa,IAAIC,CAAc,EAEjC,YACvB,CAEO,MAAMK,EAAM,CAClB,OAAAd,EACA,SAAAI,EACA,iBAAAS,CACD"}
|
package/dist/utils/jwt.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Base64Url as n}from"./base64Url.mjs";function a(o){const e=o.split(".");if(e.length!==3)throw Error("Invalid JWT");return JSON.parse(n.decodeUnicode(e[1]))}async function g(o,e,d){const c=n.encode(new TextEncoder().encode(JSON.stringify(o))),t=n.encode(new TextEncoder().encode(JSON.stringify(e))),r=`${c}.${t}`,s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},d,new TextEncoder().encode(r)),i=n.encode(new Uint8Array(s));return`${r}.${i}`}function w(o,e){const d=n.encode(new TextEncoder().encode(JSON.stringify(o))),c=n.encode(new TextEncoder().encode(JSON.stringify(e)));return`${`${d}.${c}`}.signature`}const f={decode:a,generate:g,generateUnsigned:w};export{f as jwt};
|
|
1
|
+
import{Base64Url as n}from"./base64Url.mjs";function a(o){const e=o.split(".");if(e.length!==3)throw new Error("Invalid JWT");return JSON.parse(n.decodeUnicode(e[1]))}async function g(o,e,d){const c=n.encode(new TextEncoder().encode(JSON.stringify(o))),t=n.encode(new TextEncoder().encode(JSON.stringify(e))),r=`${c}.${t}`,s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},d,new TextEncoder().encode(r)),i=n.encode(new Uint8Array(s));return`${r}.${i}`}function w(o,e){const d=n.encode(new TextEncoder().encode(JSON.stringify(o))),c=n.encode(new TextEncoder().encode(JSON.stringify(e)));return`${`${d}.${c}`}.signature`}const f={decode:a,generate:g,generateUnsigned:w};export{f as jwt};
|
|
2
2
|
//# sourceMappingURL=jwt.mjs.map
|
package/dist/utils/jwt.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jwt.mjs","sources":["../../src/utils/jwt.ts"],"sourcesContent":["import type { JwtClaims } from '../types';\nimport { Base64Url } from './base64Url';\n\n/**\n * Decodes a JWT token and returns its claims.\n *\n * @template R The expected structure of the JWT claims.\n * @param {string} token The JWT token to decode.\n * @returns {R} The decoded JWT claims.\n * @throws {Error} If the token is invalid or has the wrong format.\n */\nfunction decode<R = JwtClaims>(token: string): R {\n\tconst sections = token.split('.');\n\n\tif (sections.length !== 3) {\n\t\tthrow Error('Invalid JWT');\n\t}\n\n\treturn JSON.parse(Base64Url.decodeUnicode(sections[1]));\n}\n\n/**\n * Generates a signed JWT token using the provided header, payload, and private key.\n *\n * @param {object} header The JWT header.\n * @param {object} payload The JWT payload.\n * @param {CryptoKey} privateKey The private key to sign the JWT.\n * @returns {Promise<string>} A promise that resolves to the signed JWT token.\n */\nasync function generate(header: object, payload: object, privateKey: CryptoKey): Promise<string> {\n\tconst encodedHeader = Base64Url.encode(new TextEncoder().encode(JSON.stringify(header)));\n\tconst encodedPayload = Base64Url.encode(new TextEncoder().encode(JSON.stringify(payload)));\n\tconst encodedToken = `${encodedHeader}.${encodedPayload}`;\n\n\tconst signature = await window.crypto.subtle.sign(\n\t\t{\n\t\t\tname: 'ECDSA',\n\t\t\thash: { name: 'SHA-256' },\n\t\t},\n\t\tprivateKey,\n\t\tnew TextEncoder().encode(encodedToken),\n\t);\n\n\tconst encodedSignature = Base64Url.encode(new Uint8Array(signature));\n\treturn `${encodedToken}.${encodedSignature}`;\n}\n\n/**\n * Generates an unsigned JWT token using the provided header and payload.\n * The token will not include a valid signature.\n *\n * @param {object} header The JWT header.\n * @param {object} payload The JWT payload.\n * @returns {string} The unsigned JWT token.\n */\nfunction generateUnsigned(header: object, payload: object): string {\n\tconst encodedHeader = Base64Url.encode(new TextEncoder().encode(JSON.stringify(header)));\n\tconst encodedPayload = Base64Url.encode(new TextEncoder().encode(JSON.stringify(payload)));\n\tconst encodedToken = `${encodedHeader}.${encodedPayload}`;\n\n\treturn `${encodedToken}.signature`;\n}\n\nexport const jwt = {\n\tdecode,\n\tgenerate,\n\tgenerateUnsigned,\n};\n"],"names":["decode","token","sections","Base64Url","generate","header","payload","privateKey","encodedHeader","encodedPayload","encodedToken","signature","encodedSignature","generateUnsigned","jwt"],"mappings":"4CAWA,SAASA,EAAsBC,EAAkB,
|
|
1
|
+
{"version":3,"file":"jwt.mjs","sources":["../../src/utils/jwt.ts"],"sourcesContent":["import type { JwtClaims } from '../types';\nimport { Base64Url } from './base64Url';\n\n/**\n * Decodes a JWT token and returns its claims.\n *\n * @template R The expected structure of the JWT claims.\n * @param {string} token The JWT token to decode.\n * @returns {R} The decoded JWT claims.\n * @throws {Error} If the token is invalid or has the wrong format.\n */\nfunction decode<R = JwtClaims>(token: string): R {\n\tconst sections = token.split('.');\n\n\tif (sections.length !== 3) {\n\t\tthrow new Error('Invalid JWT');\n\t}\n\n\treturn JSON.parse(Base64Url.decodeUnicode(sections[1])) as R;\n}\n\n/**\n * Generates a signed JWT token using the provided header, payload, and private key.\n *\n * @param {object} header The JWT header.\n * @param {object} payload The JWT payload.\n * @param {CryptoKey} privateKey The private key to sign the JWT.\n * @returns {Promise<string>} A promise that resolves to the signed JWT token.\n */\nasync function generate(header: object, payload: object, privateKey: CryptoKey): Promise<string> {\n\tconst encodedHeader = Base64Url.encode(new TextEncoder().encode(JSON.stringify(header)));\n\tconst encodedPayload = Base64Url.encode(new TextEncoder().encode(JSON.stringify(payload)));\n\tconst encodedToken = `${encodedHeader}.${encodedPayload}`;\n\n\tconst signature = await window.crypto.subtle.sign(\n\t\t{\n\t\t\tname: 'ECDSA',\n\t\t\thash: { name: 'SHA-256' },\n\t\t},\n\t\tprivateKey,\n\t\tnew TextEncoder().encode(encodedToken),\n\t);\n\n\tconst encodedSignature = Base64Url.encode(new Uint8Array(signature));\n\treturn `${encodedToken}.${encodedSignature}`;\n}\n\n/**\n * Generates an unsigned JWT token using the provided header and payload.\n * The token will not include a valid signature.\n *\n * @param {object} header The JWT header.\n * @param {object} payload The JWT payload.\n * @returns {string} The unsigned JWT token.\n */\nfunction generateUnsigned(header: object, payload: object): string {\n\tconst encodedHeader = Base64Url.encode(new TextEncoder().encode(JSON.stringify(header)));\n\tconst encodedPayload = Base64Url.encode(new TextEncoder().encode(JSON.stringify(payload)));\n\tconst encodedToken = `${encodedHeader}.${encodedPayload}`;\n\n\treturn `${encodedToken}.signature`;\n}\n\nexport const jwt = {\n\tdecode,\n\tgenerate,\n\tgenerateUnsigned,\n};\n"],"names":["decode","token","sections","Base64Url","generate","header","payload","privateKey","encodedHeader","encodedPayload","encodedToken","signature","encodedSignature","generateUnsigned","jwt"],"mappings":"4CAWA,SAASA,EAAsBC,EAAkB,CAChD,MAAMC,EAAWD,EAAM,MAAM,GAAG,EAEhC,GAAIC,EAAS,SAAW,EACvB,MAAM,IAAI,MAAM,aAAa,EAG9B,OAAO,KAAK,MAAMC,EAAU,cAAcD,EAAS,CAAC,CAAC,CAAC,CACvD,CAUA,eAAeE,EAASC,EAAgBC,EAAiBC,EAAwC,CAChG,MAAMC,EAAgBL,EAAU,OAAO,IAAI,YAAA,EAAc,OAAO,KAAK,UAAUE,CAAM,CAAC,CAAC,EACjFI,EAAiBN,EAAU,OAAO,IAAI,YAAA,EAAc,OAAO,KAAK,UAAUG,CAAO,CAAC,CAAC,EACnFI,EAAe,GAAGF,CAAa,IAAIC,CAAc,GAEjDE,EAAY,MAAM,OAAO,OAAO,OAAO,KAC5C,CACC,KAAM,QACN,KAAM,CAAE,KAAM,SAAA,CAAU,EAEzBJ,EACA,IAAI,YAAA,EAAc,OAAOG,CAAY,CAAA,EAGhCE,EAAmBT,EAAU,OAAO,IAAI,WAAWQ,CAAS,CAAC,EACnE,MAAO,GAAGD,CAAY,IAAIE,CAAgB,EAC3C,CAUA,SAASC,EAAiBR,EAAgBC,EAAyB,CAClE,MAAME,EAAgBL,EAAU,OAAO,IAAI,YAAA,EAAc,OAAO,KAAK,UAAUE,CAAM,CAAC,CAAC,EACjFI,EAAiBN,EAAU,OAAO,IAAI,YAAA,EAAc,OAAO,KAAK,UAAUG,CAAO,CAAC,CAAC,EAGzF,MAAO,GAFc,GAAGE,CAAa,IAAIC,CAAc,EAEjC,YACvB,CAEO,MAAMK,EAAM,CAClB,OAAAd,EACA,SAAAI,EACA,iBAAAS,CACD"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function l(n){const o={};for(const s in n){const u=s.split(".");u.reduce((e,t,i)=>(i===u.length-1?e[t]=n[s]:e[t]=e[t]||{},e[t]),o)}return o}exports.unflattenObject=l;
|
|
2
|
+
//# sourceMappingURL=object.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"object.cjs","sources":["../../src/utils/object.ts"],"sourcesContent":["export function unflattenObject(flatObject: Record<string, unknown>): Record<string, unknown> {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tconst nestedObject: Record<string, any> = {};\n\n\tfor (const key in flatObject) {\n\t\tconst keys = key.split('.');\n\n\t\tkeys.reduce((acc, part, index) => {\n\t\t\tif (index === keys.length - 1) {\n\t\t\t\tacc[part] = flatObject[key];\n\t\t\t} else {\n\t\t\t\tacc[part] = acc[part] || {};\n\t\t\t}\n\n\t\t\treturn acc[part];\n\t\t}, nestedObject);\n\t}\n\n\treturn nestedObject;\n}\n"],"names":["unflattenObject","flatObject","nestedObject","key","keys","acc","part","index"],"mappings":"gFAAO,SAASA,EAAgBC,EAA8D,CAE7F,MAAMC,EAAoC,CAAA,EAE1C,UAAWC,KAAOF,EAAY,CAC7B,MAAMG,EAAOD,EAAI,MAAM,GAAG,EAE1BC,EAAK,OAAO,CAACC,EAAKC,EAAMC,KACnBA,IAAUH,EAAK,OAAS,EAC3BC,EAAIC,CAAI,EAAIL,EAAWE,CAAG,EAE1BE,EAAIC,CAAI,EAAID,EAAIC,CAAI,GAAK,CAAA,EAGnBD,EAAIC,CAAI,GACbJ,CAAY,CAAA,CAGhB,OAAOA,CACR"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function unflattenObject(flatObject: Record<string, unknown>): Record<string, unknown>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"object.mjs","sources":["../../src/utils/object.ts"],"sourcesContent":["export function unflattenObject(flatObject: Record<string, unknown>): Record<string, unknown> {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tconst nestedObject: Record<string, any> = {};\n\n\tfor (const key in flatObject) {\n\t\tconst keys = key.split('.');\n\n\t\tkeys.reduce((acc, part, index) => {\n\t\t\tif (index === keys.length - 1) {\n\t\t\t\tacc[part] = flatObject[key];\n\t\t\t} else {\n\t\t\t\tacc[part] = acc[part] || {};\n\t\t\t}\n\n\t\t\treturn acc[part];\n\t\t}, nestedObject);\n\t}\n\n\treturn nestedObject;\n}\n"],"names":["unflattenObject","flatObject","nestedObject","key","keys","acc","part","index"],"mappings":"AAAO,SAASA,EAAgBC,EAA8D,CAE7F,MAAMC,EAAoC,CAAA,EAE1C,UAAWC,KAAOF,EAAY,CAC7B,MAAMG,EAAOD,EAAI,MAAM,GAAG,EAE1BC,EAAK,OAAO,CAACC,EAAKC,EAAMC,KACnBA,IAAUH,EAAK,OAAS,EAC3BC,EAAIC,CAAI,EAAIL,EAAWE,CAAG,EAE1BE,EAAIC,CAAI,EAAID,EAAIC,CAAI,GAAK,CAAA,EAGnBD,EAAIC,CAAI,GACbJ,CAAY,CAAA,CAGhB,OAAOA,CACR"}
|
package/package.json
CHANGED
package/dist/Metadata.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var n=Object.defineProperty;var i=(a,t,e)=>t in a?n(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e;var r=(a,t,e)=>i(a,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./utils/fetch.cjs");class s{constructor(t){r(this,"data",null);this.metadataUrl=t}get issuer(){return this.getMetadataProperty("issuer")}get authorizationEndpoint(){return this.getMetadataProperty("authorization_endpoint")}get tokenEndpoint(){return this.getMetadataProperty("token_endpoint")}get userinfoEndpoint(){return this.getMetadataProperty("userinfo_endpoint")}get endSessionEndpoint(){return this.getMetadataProperty("end_session_endpoint")}get revocationEndpoint(){return this.getMetadataProperty("revocation_endpoint")}get jwksUri(){return this.getMetadataProperty("jwks_uri")}async fetchMetadata(){this.data=await o.fetch.get(this.metadataUrl).json()}async getMetadataProperty(t){var e;return(e=this.data)!=null&&e[t]?Promise.resolve(this.data[t]):(await this.fetchMetadata(),Promise.resolve(this.data[t]))}}exports.Metadata=s;
|
|
2
|
-
//# sourceMappingURL=Metadata.cjs.map
|
package/dist/Metadata.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Metadata.cjs","sources":["../src/Metadata.ts"],"sourcesContent":["import type { MetadataOptions } from './types';\nimport { fetch } from './utils/fetch';\n\n/**\n * Class responsible for fetching and handling metadata for authentication endpoints.\n */\nexport class Metadata {\n\t/**\n\t * Holds the metadata options once fetched, or null if not yet fetched.\n\t * @protected\n\t */\n\tprotected data: MetadataOptions | null = null;\n\n\t/**\n\t * Retrieves the issuer metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the issuer string.\n\t */\n\tget issuer(): Promise<string> {\n\t\treturn this.getMetadataProperty('issuer');\n\t}\n\n\t/**\n\t * Retrieves the authorization endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the authorization endpoint URL.\n\t */\n\tget authorizationEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('authorization_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the token endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the token endpoint URL.\n\t */\n\tget tokenEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('token_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the user info endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the user info endpoint URL.\n\t */\n\tget userinfoEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('userinfo_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the end session endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the end session endpoint URL.\n\t */\n\tget endSessionEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('end_session_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the revocation endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the revocation endpoint URL.\n\t */\n\tget revocationEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('revocation_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the JWKS URI metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the JWKS URI.\n\t */\n\tget jwksUri(): Promise<string> {\n\t\treturn this.getMetadataProperty('jwks_uri');\n\t}\n\n\t/**\n\t * Creates an instance of the Metadata class.\n\t *\n\t * @param {string} metadataUrl The URL to fetch metadata from.\n\t */\n\tconstructor(protected metadataUrl: string) {}\n\n\t/**\n\t * Fetches and updates the metadata from the specified URL.\n\t *\n\t * @returns {Promise<void>} A promise that resolves once the metadata is fetched.\n\t */\n\tasync fetchMetadata(): Promise<void> {\n\t\tthis.data = await fetch.get(this.metadataUrl).json<MetadataOptions>();\n\t}\n\n\t/**\n\t * Retrieves a specific metadata property.\n\t *\n\t * @template K The key of the metadata property.\n\t * @param {K} key The metadata property key to retrieve.\n\t * @returns {Promise<MetadataOptions[K]>} A promise that resolves to the value of the specified metadata property.\n\t */\n\tasync getMetadataProperty<K extends keyof MetadataOptions>(key: K): Promise<MetadataOptions[K]> {\n\t\tif (this.data?.[key]) {\n\t\t\treturn Promise.resolve(this.data[key]);\n\t\t}\n\n\t\tawait this.fetchMetadata();\n\n\t\treturn Promise.resolve((this.data as MetadataOptions)[key]);\n\t}\n}\n"],"names":["Metadata","metadataUrl","__publicField","fetch","key","_a"],"mappings":"yRAMO,MAAMA,CAAS,CA2ErB,YAAsBC,EAAqB,CAtEjCC,EAAA,YAA+B,MAsEnB,KAAA,YAAAD,CAAsB,CA/D5C,IAAI,QAA0B,CACtB,OAAA,KAAK,oBAAoB,QAAQ,CACzC,CAOA,IAAI,uBAAyC,CACrC,OAAA,KAAK,oBAAoB,wBAAwB,CACzD,CAOA,IAAI,eAAiC,CAC7B,OAAA,KAAK,oBAAoB,gBAAgB,CACjD,CAOA,IAAI,kBAAoC,CAChC,OAAA,KAAK,oBAAoB,mBAAmB,CACpD,CAOA,IAAI,oBAAsC,CAClC,OAAA,KAAK,oBAAoB,sBAAsB,CACvD,CAOA,IAAI,oBAAsC,CAClC,OAAA,KAAK,oBAAoB,qBAAqB,CACtD,CAOA,IAAI,SAA2B,CACvB,OAAA,KAAK,oBAAoB,UAAU,CAC3C,CAcA,MAAM,eAA+B,CACpC,KAAK,KAAO,MAAME,QAAM,IAAI,KAAK,WAAW,EAAE,MAC/C,CASA,MAAM,oBAAqDC,EAAqC,OAC3F,OAAAC,EAAA,KAAK,OAAL,MAAAA,EAAYD,GACR,QAAQ,QAAQ,KAAK,KAAKA,CAAG,CAAC,GAGtC,MAAM,KAAK,gBAEJ,QAAQ,QAAS,KAAK,KAAyBA,CAAG,CAAC,EAC3D,CACD"}
|
package/dist/Metadata.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var n=Object.defineProperty;var i=(a,t,e)=>t in a?n(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e;var r=(a,t,e)=>i(a,typeof t!="symbol"?t+"":t,e);import{fetch as o}from"./utils/fetch.mjs";class p{constructor(t){r(this,"data",null);this.metadataUrl=t}get issuer(){return this.getMetadataProperty("issuer")}get authorizationEndpoint(){return this.getMetadataProperty("authorization_endpoint")}get tokenEndpoint(){return this.getMetadataProperty("token_endpoint")}get userinfoEndpoint(){return this.getMetadataProperty("userinfo_endpoint")}get endSessionEndpoint(){return this.getMetadataProperty("end_session_endpoint")}get revocationEndpoint(){return this.getMetadataProperty("revocation_endpoint")}get jwksUri(){return this.getMetadataProperty("jwks_uri")}async fetchMetadata(){this.data=await o.get(this.metadataUrl).json()}async getMetadataProperty(t){var e;return(e=this.data)!=null&&e[t]?Promise.resolve(this.data[t]):(await this.fetchMetadata(),Promise.resolve(this.data[t]))}}export{p as Metadata};
|
|
2
|
-
//# sourceMappingURL=Metadata.mjs.map
|
package/dist/Metadata.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Metadata.mjs","sources":["../src/Metadata.ts"],"sourcesContent":["import type { MetadataOptions } from './types';\nimport { fetch } from './utils/fetch';\n\n/**\n * Class responsible for fetching and handling metadata for authentication endpoints.\n */\nexport class Metadata {\n\t/**\n\t * Holds the metadata options once fetched, or null if not yet fetched.\n\t * @protected\n\t */\n\tprotected data: MetadataOptions | null = null;\n\n\t/**\n\t * Retrieves the issuer metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the issuer string.\n\t */\n\tget issuer(): Promise<string> {\n\t\treturn this.getMetadataProperty('issuer');\n\t}\n\n\t/**\n\t * Retrieves the authorization endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the authorization endpoint URL.\n\t */\n\tget authorizationEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('authorization_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the token endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the token endpoint URL.\n\t */\n\tget tokenEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('token_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the user info endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the user info endpoint URL.\n\t */\n\tget userinfoEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('userinfo_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the end session endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the end session endpoint URL.\n\t */\n\tget endSessionEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('end_session_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the revocation endpoint metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the revocation endpoint URL.\n\t */\n\tget revocationEndpoint(): Promise<string> {\n\t\treturn this.getMetadataProperty('revocation_endpoint');\n\t}\n\n\t/**\n\t * Retrieves the JWKS URI metadata.\n\t *\n\t * @returns {Promise<string>} A promise that resolves to the JWKS URI.\n\t */\n\tget jwksUri(): Promise<string> {\n\t\treturn this.getMetadataProperty('jwks_uri');\n\t}\n\n\t/**\n\t * Creates an instance of the Metadata class.\n\t *\n\t * @param {string} metadataUrl The URL to fetch metadata from.\n\t */\n\tconstructor(protected metadataUrl: string) {}\n\n\t/**\n\t * Fetches and updates the metadata from the specified URL.\n\t *\n\t * @returns {Promise<void>} A promise that resolves once the metadata is fetched.\n\t */\n\tasync fetchMetadata(): Promise<void> {\n\t\tthis.data = await fetch.get(this.metadataUrl).json<MetadataOptions>();\n\t}\n\n\t/**\n\t * Retrieves a specific metadata property.\n\t *\n\t * @template K The key of the metadata property.\n\t * @param {K} key The metadata property key to retrieve.\n\t * @returns {Promise<MetadataOptions[K]>} A promise that resolves to the value of the specified metadata property.\n\t */\n\tasync getMetadataProperty<K extends keyof MetadataOptions>(key: K): Promise<MetadataOptions[K]> {\n\t\tif (this.data?.[key]) {\n\t\t\treturn Promise.resolve(this.data[key]);\n\t\t}\n\n\t\tawait this.fetchMetadata();\n\n\t\treturn Promise.resolve((this.data as MetadataOptions)[key]);\n\t}\n}\n"],"names":["Metadata","metadataUrl","__publicField","fetch","key","_a"],"mappings":"8MAMO,MAAMA,CAAS,CA2ErB,YAAsBC,EAAqB,CAtEjCC,EAAA,YAA+B,MAsEnB,KAAA,YAAAD,CAAsB,CA/D5C,IAAI,QAA0B,CACtB,OAAA,KAAK,oBAAoB,QAAQ,CACzC,CAOA,IAAI,uBAAyC,CACrC,OAAA,KAAK,oBAAoB,wBAAwB,CACzD,CAOA,IAAI,eAAiC,CAC7B,OAAA,KAAK,oBAAoB,gBAAgB,CACjD,CAOA,IAAI,kBAAoC,CAChC,OAAA,KAAK,oBAAoB,mBAAmB,CACpD,CAOA,IAAI,oBAAsC,CAClC,OAAA,KAAK,oBAAoB,sBAAsB,CACvD,CAOA,IAAI,oBAAsC,CAClC,OAAA,KAAK,oBAAoB,qBAAqB,CACtD,CAOA,IAAI,SAA2B,CACvB,OAAA,KAAK,oBAAoB,UAAU,CAC3C,CAcA,MAAM,eAA+B,CACpC,KAAK,KAAO,MAAME,EAAM,IAAI,KAAK,WAAW,EAAE,MAC/C,CASA,MAAM,oBAAqDC,EAAqC,OAC3F,OAAAC,EAAA,KAAK,OAAL,MAAAA,EAAYD,GACR,QAAQ,QAAQ,KAAK,KAAKA,CAAG,CAAC,GAGtC,MAAM,KAAK,gBAEJ,QAAQ,QAAS,KAAK,KAAyBA,CAAG,CAAC,EAC3D,CACD"}
|
package/dist/Session.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var i=Object.defineProperty;var u=(l,e,r)=>e in l?i(l,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):l[e]=r;var t=(l,e,r)=>u(l,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./utils/date.cjs");class s{constructor(){t(this,"state",null);t(this,"code",null);t(this,"error",null);t(this,"error_description",null);t(this,"id_token",null);t(this,"access_token",null);t(this,"refresh_token",null);t(this,"token_type","bearer");t(this,"scope",null);t(this,"expires_at",null);t(this,"claims",null)}get expires_in(){return this.expires_at?this.expires_at-n.timestamp():0}set expires_in(e){e!==null&&!isNaN(e)&&(this.expires_at=Math.floor(e)+n.timestamp())}static load(e){if(!e)return null;let r=new s;try{Object.assign(r,JSON.parse(e))}catch{r=null}return r}}exports.Session=s;
|
|
2
|
-
//# sourceMappingURL=Session.cjs.map
|
package/dist/Session.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Session.cjs","sources":["../src/Session.ts"],"sourcesContent":["import type { IdTokenClaims } from './types';\nimport { timestamp } from './utils/date';\n\n/**\n * Class representing a user's authentication session, storing tokens and related information.\n */\nexport class Session {\n\t/**\n\t * The state parameter used in the authentication request.\n\t * @type {string | null}\n\t */\n\tstate: string | null = null;\n\n\t/**\n\t * The authorization code returned by the authorization server.\n\t * @type {string | null}\n\t */\n\tcode: string | null = null;\n\n\t/**\n\t * The error returned during the authentication process, if any.\n\t * @type {string | null}\n\t */\n\terror: string | null = null;\n\n\t/**\n\t * A description of the error returned during authentication.\n\t * @type {string | null}\n\t */\n\terror_description: string | null = null;\n\n\t/**\n\t * The ID token issued by the authorization server.\n\t * @type {string | null}\n\t */\n\tid_token: string | null = null;\n\n\t/**\n\t * The access token issued by the authorization server.\n\t * @type {string | null}\n\t */\n\taccess_token: string | null = null;\n\n\t/**\n\t * The refresh token issued by the authorization server.\n\t * @type {string | null}\n\t */\n\trefresh_token: string | null = null;\n\n\t/**\n\t * The type of token issued, defaulting to 'bearer'.\n\t * @type {string}\n\t */\n\ttoken_type = 'bearer';\n\n\t/**\n\t * The scope of the issued token.\n\t * @type {string | null}\n\t */\n\tscope: string | null = null;\n\n\t/**\n\t * The expiration timestamp of the access token, represented in seconds since the epoch.\n\t * @type {number | null}\n\t */\n\texpires_at: number | null = null;\n\n\t/**\n\t * The claims associated with the ID token.\n\t * @type {IdTokenClaims | null}\n\t */\n\tclaims: IdTokenClaims | null = null;\n\n\t/**\n\t * Returns the number of seconds until the access token expires.\n\t * If `expires_at` is not set, returns 0.\n\t *\n\t * @returns {number} The number of seconds until the token expires.\n\t */\n\tget expires_in(): number {\n\t\tif (!this.expires_at) {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn this.expires_at - timestamp();\n\t}\n\n\t/**\n\t * Sets the expiration time based on a duration in seconds.\n\t * This also updates the `expires_at` timestamp.\n\t *\n\t * @param {number | null} value The number of seconds until the token expires.\n\t */\n\tset expires_in(value: number | null) {\n\t\tif (value !== null && !isNaN(value)) {\n\t\t\tthis.expires_at = Math.floor(value) + timestamp();\n\t\t}\n\t}\n\n\t/**\n\t * Loads a serialized session from a JSON string.\n\t *\n\t * @param {string | null} serializedSession The JSON string representing a session.\n\t * @returns {Session | null} A new session instance populated with the data from the string, or null if parsing fails.\n\t */\n\tstatic load(serializedSession: string | null): Session | null {\n\t\tif (!serializedSession) {\n\t\t\treturn null;\n\t\t}\n\n\t\tlet session: Session | null = new Session();\n\n\t\ttry {\n\t\t\tObject.assign(session, JSON.parse(serializedSession));\n\t\t} catch {\n\t\t\tsession = null;\n\t\t}\n\n\t\treturn session;\n\t}\n}\n"],"names":["Session","__publicField","timestamp","value","serializedSession","session"],"mappings":"wRAMO,MAAMA,CAAQ,CAAd,cAKNC,EAAA,aAAuB,MAMvBA,EAAA,YAAsB,MAMtBA,EAAA,aAAuB,MAMvBA,EAAA,yBAAmC,MAMnCA,EAAA,gBAA0B,MAM1BA,EAAA,oBAA8B,MAM9BA,EAAA,qBAA+B,MAM/BA,EAAA,kBAAa,UAMbA,EAAA,aAAuB,MAMvBA,EAAA,kBAA4B,MAM5BA,EAAA,cAA+B,MAQ/B,IAAI,YAAqB,CACpB,OAAC,KAAK,WAIH,KAAK,WAAaC,EAAAA,YAHjB,CAIT,CAQA,IAAI,WAAWC,EAAsB,CAChCA,IAAU,MAAQ,CAAC,MAAMA,CAAK,IACjC,KAAK,WAAa,KAAK,MAAMA,CAAK,EAAID,EAAAA,YAExC,CAQA,OAAO,KAAKE,EAAkD,CAC7D,GAAI,CAACA,EACG,OAAA,KAGJ,IAAAC,EAA0B,IAAIL,EAE9B,GAAA,CACH,OAAO,OAAOK,EAAS,KAAK,MAAMD,CAAiB,CAAC,CAAA,MAC7C,CACGC,EAAA,IACX,CAEO,OAAAA,CACR,CACD"}
|
package/dist/Session.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var i=Object.defineProperty;var o=(l,e,r)=>e in l?i(l,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):l[e]=r;var t=(l,e,r)=>o(l,typeof e!="symbol"?e+"":e,r);import{timestamp as n}from"./utils/date.mjs";class s{constructor(){t(this,"state",null);t(this,"code",null);t(this,"error",null);t(this,"error_description",null);t(this,"id_token",null);t(this,"access_token",null);t(this,"refresh_token",null);t(this,"token_type","bearer");t(this,"scope",null);t(this,"expires_at",null);t(this,"claims",null)}get expires_in(){return this.expires_at?this.expires_at-n():0}set expires_in(e){e!==null&&!isNaN(e)&&(this.expires_at=Math.floor(e)+n())}static load(e){if(!e)return null;let r=new s;try{Object.assign(r,JSON.parse(e))}catch{r=null}return r}}export{s as Session};
|
|
2
|
-
//# sourceMappingURL=Session.mjs.map
|
package/dist/Session.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Session.mjs","sources":["../src/Session.ts"],"sourcesContent":["import type { IdTokenClaims } from './types';\nimport { timestamp } from './utils/date';\n\n/**\n * Class representing a user's authentication session, storing tokens and related information.\n */\nexport class Session {\n\t/**\n\t * The state parameter used in the authentication request.\n\t * @type {string | null}\n\t */\n\tstate: string | null = null;\n\n\t/**\n\t * The authorization code returned by the authorization server.\n\t * @type {string | null}\n\t */\n\tcode: string | null = null;\n\n\t/**\n\t * The error returned during the authentication process, if any.\n\t * @type {string | null}\n\t */\n\terror: string | null = null;\n\n\t/**\n\t * A description of the error returned during authentication.\n\t * @type {string | null}\n\t */\n\terror_description: string | null = null;\n\n\t/**\n\t * The ID token issued by the authorization server.\n\t * @type {string | null}\n\t */\n\tid_token: string | null = null;\n\n\t/**\n\t * The access token issued by the authorization server.\n\t * @type {string | null}\n\t */\n\taccess_token: string | null = null;\n\n\t/**\n\t * The refresh token issued by the authorization server.\n\t * @type {string | null}\n\t */\n\trefresh_token: string | null = null;\n\n\t/**\n\t * The type of token issued, defaulting to 'bearer'.\n\t * @type {string}\n\t */\n\ttoken_type = 'bearer';\n\n\t/**\n\t * The scope of the issued token.\n\t * @type {string | null}\n\t */\n\tscope: string | null = null;\n\n\t/**\n\t * The expiration timestamp of the access token, represented in seconds since the epoch.\n\t * @type {number | null}\n\t */\n\texpires_at: number | null = null;\n\n\t/**\n\t * The claims associated with the ID token.\n\t * @type {IdTokenClaims | null}\n\t */\n\tclaims: IdTokenClaims | null = null;\n\n\t/**\n\t * Returns the number of seconds until the access token expires.\n\t * If `expires_at` is not set, returns 0.\n\t *\n\t * @returns {number} The number of seconds until the token expires.\n\t */\n\tget expires_in(): number {\n\t\tif (!this.expires_at) {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn this.expires_at - timestamp();\n\t}\n\n\t/**\n\t * Sets the expiration time based on a duration in seconds.\n\t * This also updates the `expires_at` timestamp.\n\t *\n\t * @param {number | null} value The number of seconds until the token expires.\n\t */\n\tset expires_in(value: number | null) {\n\t\tif (value !== null && !isNaN(value)) {\n\t\t\tthis.expires_at = Math.floor(value) + timestamp();\n\t\t}\n\t}\n\n\t/**\n\t * Loads a serialized session from a JSON string.\n\t *\n\t * @param {string | null} serializedSession The JSON string representing a session.\n\t * @returns {Session | null} A new session instance populated with the data from the string, or null if parsing fails.\n\t */\n\tstatic load(serializedSession: string | null): Session | null {\n\t\tif (!serializedSession) {\n\t\t\treturn null;\n\t\t}\n\n\t\tlet session: Session | null = new Session();\n\n\t\ttry {\n\t\t\tObject.assign(session, JSON.parse(serializedSession));\n\t\t} catch {\n\t\t\tsession = null;\n\t\t}\n\n\t\treturn session;\n\t}\n}\n"],"names":["Session","__publicField","timestamp","value","serializedSession","session"],"mappings":"iNAMO,MAAMA,CAAQ,CAAd,cAKNC,EAAA,aAAuB,MAMvBA,EAAA,YAAsB,MAMtBA,EAAA,aAAuB,MAMvBA,EAAA,yBAAmC,MAMnCA,EAAA,gBAA0B,MAM1BA,EAAA,oBAA8B,MAM9BA,EAAA,qBAA+B,MAM/BA,EAAA,kBAAa,UAMbA,EAAA,aAAuB,MAMvBA,EAAA,kBAA4B,MAM5BA,EAAA,cAA+B,MAQ/B,IAAI,YAAqB,CACpB,OAAC,KAAK,WAIH,KAAK,WAAaC,IAHjB,CAIT,CAQA,IAAI,WAAWC,EAAsB,CAChCA,IAAU,MAAQ,CAAC,MAAMA,CAAK,IACjC,KAAK,WAAa,KAAK,MAAMA,CAAK,EAAID,IAExC,CAQA,OAAO,KAAKE,EAAkD,CAC7D,GAAI,CAACA,EACG,OAAA,KAGJ,IAAAC,EAA0B,IAAIL,EAE9B,GAAA,CACH,OAAO,OAAOK,EAAS,KAAK,MAAMD,CAAiB,CAAC,CAAA,MAC7C,CACGC,EAAA,IACX,CAEO,OAAAA,CACR,CACD"}
|
package/dist/State.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var o=Object.defineProperty;var d=(n,e,t)=>e in n?o(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var r=(n,e,t)=>d(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./utils/crypto.cjs"),s=require("./utils/date.cjs");require("./utils/base64Url.cjs");class i{constructor(){r(this,"id");r(this,"createdAt");r(this,"codeVerifier");r(this,"codeChallenge");r(this,"nonce")}static async create(){const e=new i;return e.id=c.Crypto.generateState(),e.createdAt=s.timestamp(),e.codeVerifier=c.Crypto.generateCodeVerifier(),e.codeChallenge=await c.Crypto.generateCodeChallenge(e.codeVerifier),e.nonce=c.Crypto.generateNonce(),e}static fromSerializedData(e){const t=new i,a=JSON.parse(e);return t.id=a.id,t.createdAt=a.createdAt,t.codeVerifier=a.codeVerifier,t.codeChallenge=a.codeChallenge,t.nonce=a.nonce,t}}exports.State=i;
|
|
2
|
-
//# sourceMappingURL=State.cjs.map
|
package/dist/State.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"State.cjs","sources":["../src/State.ts"],"sourcesContent":["import { Crypto } from './utils/crypto';\nimport { timestamp } from './utils/date';\n\n/**\n * Class representing an OAuth state, including code verifier and nonce for PKCE flows.\n */\nexport class State {\n\t/**\n\t * The unique identifier for the state.\n\t * @type {string}\n\t */\n\tid!: string;\n\n\t/**\n\t * The timestamp when the state was created, represented in seconds since the epoch.\n\t * @type {number}\n\t */\n\tcreatedAt!: number;\n\n\t/**\n\t * The code verifier used in the PKCE (Proof Key for Code Exchange) flow.\n\t * @type {string}\n\t */\n\tcodeVerifier!: string;\n\n\t/**\n\t * The code challenge derived from the code verifier for the PKCE flow.\n\t * @type {string}\n\t */\n\tcodeChallenge!: string;\n\n\t/**\n\t * The nonce value used to associate a client session with an ID token for replay protection.\n\t * @type {string}\n\t */\n\tnonce!: string;\n\n\t/**\n\t * Creates a new instance of `State` with generated values for PKCE and nonce.\n\t *\n\t * @returns {Promise<State>} A promise that resolves to a new `State` instance.\n\t */\n\tstatic async create(): Promise<State> {\n\t\tconst instance = new State();\n\n\t\tinstance.id = Crypto.generateState();\n\t\tinstance.createdAt = timestamp();\n\t\tinstance.codeVerifier = Crypto.generateCodeVerifier();\n\t\tinstance.codeChallenge = await Crypto.generateCodeChallenge(instance.codeVerifier);\n\t\tinstance.nonce = Crypto.generateNonce();\n\n\t\treturn instance as State;\n\t}\n\n\t/**\n\t * Deserializes a `State` instance from a JSON string.\n\t *\n\t * @param {string} serializedData The serialized state data as a JSON string.\n\t * @returns {State} A new `State` instance populated with the deserialized data.\n\t */\n\tstatic fromSerializedData(serializedData: string): State {\n\t\tconst instance = new State();\n\t\tconst data = JSON.parse(serializedData);\n\n\t\tinstance.id = data.id;\n\t\tinstance.createdAt = data.createdAt;\n\t\tinstance.codeVerifier = data.codeVerifier;\n\t\tinstance.codeChallenge = data.codeChallenge;\n\t\tinstance.nonce = data.nonce;\n\n\t\treturn instance;\n\t}\n}\n"],"names":["State","__publicField","instance","Crypto","timestamp","serializedData","data"],"mappings":"yVAMO,MAAMA,CAAM,CAAZ,cAKNC,EAAA,WAMAA,EAAA,kBAMAA,EAAA,qBAMAA,EAAA,sBAMAA,EAAA,cAOA,aAAa,QAAyB,CAC/B,MAAAC,EAAW,IAAIF,EAEZ,OAAAE,EAAA,GAAKC,SAAO,gBACrBD,EAAS,UAAYE,EAAAA,YACZF,EAAA,aAAeC,SAAO,uBAC/BD,EAAS,cAAgB,MAAMC,EAAAA,OAAO,sBAAsBD,EAAS,YAAY,EACxEA,EAAA,MAAQC,SAAO,gBAEjBD,CACR,CAQA,OAAO,mBAAmBG,EAA+B,CAClD,MAAAH,EAAW,IAAIF,EACfM,EAAO,KAAK,MAAMD,CAAc,EAEtC,OAAAH,EAAS,GAAKI,EAAK,GACnBJ,EAAS,UAAYI,EAAK,UAC1BJ,EAAS,aAAeI,EAAK,aAC7BJ,EAAS,cAAgBI,EAAK,cAC9BJ,EAAS,MAAQI,EAAK,MAEfJ,CACR,CACD"}
|
package/dist/State.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var o=Object.defineProperty;var d=(n,e,r)=>e in n?o(n,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):n[e]=r;var t=(n,e,r)=>d(n,typeof e!="symbol"?e+"":e,r);import{Crypto as c}from"./utils/crypto.mjs";import{timestamp as l}from"./utils/date.mjs";import"./utils/base64Url.mjs";class i{constructor(){t(this,"id");t(this,"createdAt");t(this,"codeVerifier");t(this,"codeChallenge");t(this,"nonce")}static async create(){const e=new i;return e.id=c.generateState(),e.createdAt=l(),e.codeVerifier=c.generateCodeVerifier(),e.codeChallenge=await c.generateCodeChallenge(e.codeVerifier),e.nonce=c.generateNonce(),e}static fromSerializedData(e){const r=new i,a=JSON.parse(e);return r.id=a.id,r.createdAt=a.createdAt,r.codeVerifier=a.codeVerifier,r.codeChallenge=a.codeChallenge,r.nonce=a.nonce,r}}export{i as State};
|
|
2
|
-
//# sourceMappingURL=State.mjs.map
|
package/dist/State.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"State.mjs","sources":["../src/State.ts"],"sourcesContent":["import { Crypto } from './utils/crypto';\nimport { timestamp } from './utils/date';\n\n/**\n * Class representing an OAuth state, including code verifier and nonce for PKCE flows.\n */\nexport class State {\n\t/**\n\t * The unique identifier for the state.\n\t * @type {string}\n\t */\n\tid!: string;\n\n\t/**\n\t * The timestamp when the state was created, represented in seconds since the epoch.\n\t * @type {number}\n\t */\n\tcreatedAt!: number;\n\n\t/**\n\t * The code verifier used in the PKCE (Proof Key for Code Exchange) flow.\n\t * @type {string}\n\t */\n\tcodeVerifier!: string;\n\n\t/**\n\t * The code challenge derived from the code verifier for the PKCE flow.\n\t * @type {string}\n\t */\n\tcodeChallenge!: string;\n\n\t/**\n\t * The nonce value used to associate a client session with an ID token for replay protection.\n\t * @type {string}\n\t */\n\tnonce!: string;\n\n\t/**\n\t * Creates a new instance of `State` with generated values for PKCE and nonce.\n\t *\n\t * @returns {Promise<State>} A promise that resolves to a new `State` instance.\n\t */\n\tstatic async create(): Promise<State> {\n\t\tconst instance = new State();\n\n\t\tinstance.id = Crypto.generateState();\n\t\tinstance.createdAt = timestamp();\n\t\tinstance.codeVerifier = Crypto.generateCodeVerifier();\n\t\tinstance.codeChallenge = await Crypto.generateCodeChallenge(instance.codeVerifier);\n\t\tinstance.nonce = Crypto.generateNonce();\n\n\t\treturn instance as State;\n\t}\n\n\t/**\n\t * Deserializes a `State` instance from a JSON string.\n\t *\n\t * @param {string} serializedData The serialized state data as a JSON string.\n\t * @returns {State} A new `State` instance populated with the deserialized data.\n\t */\n\tstatic fromSerializedData(serializedData: string): State {\n\t\tconst instance = new State();\n\t\tconst data = JSON.parse(serializedData);\n\n\t\tinstance.id = data.id;\n\t\tinstance.createdAt = data.createdAt;\n\t\tinstance.codeVerifier = data.codeVerifier;\n\t\tinstance.codeChallenge = data.codeChallenge;\n\t\tinstance.nonce = data.nonce;\n\n\t\treturn instance;\n\t}\n}\n"],"names":["State","__publicField","instance","Crypto","timestamp","serializedData","data"],"mappings":"2RAMO,MAAMA,CAAM,CAAZ,cAKNC,EAAA,WAMAA,EAAA,kBAMAA,EAAA,qBAMAA,EAAA,sBAMAA,EAAA,cAOA,aAAa,QAAyB,CAC/B,MAAAC,EAAW,IAAIF,EAEZ,OAAAE,EAAA,GAAKC,EAAO,gBACrBD,EAAS,UAAYE,IACZF,EAAA,aAAeC,EAAO,uBAC/BD,EAAS,cAAgB,MAAMC,EAAO,sBAAsBD,EAAS,YAAY,EACxEA,EAAA,MAAQC,EAAO,gBAEjBD,CACR,CAQA,OAAO,mBAAmBG,EAA+B,CAClD,MAAAH,EAAW,IAAIF,EACfM,EAAO,KAAK,MAAMD,CAAc,EAEtC,OAAAH,EAAS,GAAKI,EAAK,GACnBJ,EAAS,UAAYI,EAAK,UAC1BJ,EAAS,aAAeI,EAAK,aAC7BJ,EAAS,cAAgBI,EAAK,cAC9BJ,EAAS,MAAQI,EAAK,MAEfJ,CACR,CACD"}
|
package/dist/utils/constants.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"constants.cjs","sources":["../../src/utils/constants.ts"],"sourcesContent":["/**\n * Determines if the code is running in a browser environment.\n *\n * @type {boolean}\n */\nexport const isBrowser = typeof window !== 'undefined';\n"],"names":["isBrowser"],"mappings":"gFAKa,MAAAA,EAAY,OAAO,OAAW"}
|
package/dist/utils/constants.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"constants.mjs","sources":["../../src/utils/constants.ts"],"sourcesContent":["/**\n * Determines if the code is running in a browser environment.\n *\n * @type {boolean}\n */\nexport const isBrowser = typeof window !== 'undefined';\n"],"names":["isBrowser"],"mappings":"AAKa,MAAAA,EAAY,OAAO,OAAW"}
|
package/dist/utils/fetch.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var E=Object.defineProperty;var S=(r,t,e)=>t in r?E(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var h=(r,t,e)=>S(r,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class w extends Error{constructor(e,s,o){const n=e.status||e.status===0?e.status:"",i=e.statusText||"",a=`${n} ${i}`.trim(),u=a?`status code ${a}`:"an unknown error";super(`Request failed with ${u}: ${s.method} ${s.url}`);h(this,"response");h(this,"request");h(this,"options");this.name="HTTPError",this.response=e,this.request=s,this.options=o}}class T extends Error{constructor(e){super(`Request timed out: ${e.method} ${e.url}`);h(this,"request");this.name="TimeoutError",this.request=e}}const p=r=>r!==null&&typeof r=="object",l=(...r)=>{for(const t of r)if((!p(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return _({},...r)},g=(r={},t={})=>{const e=new globalThis.Headers(r),s=t instanceof globalThis.Headers,o=new globalThis.Headers(t);for(const[n,i]of o.entries())s&&i==="undefined"||i===void 0?e.delete(n):e.set(n,i);return e};function d(r,t,e){return Object.hasOwn(t,e)&&t[e]===void 0?[]:_(r[e]??[],t[e]??[])}const q=(r={},t={})=>({beforeRequest:d(r,t,"beforeRequest"),beforeRetry:d(r,t,"beforeRetry"),afterResponse:d(r,t,"afterResponse"),beforeError:d(r,t,"beforeError")}),_=(...r)=>{let t={},e={},s={};for(const o of r)if(Array.isArray(o))Array.isArray(t)||(t=[]),t=[...t,...o];else if(p(o)){for(let[n,i]of Object.entries(o))p(i)&&n in t&&(i=_(t[n],i)),t={...t,[n]:i};p(o.hooks)&&(s=q(s,o.hooks),t.hooks=s),p(o.headers)&&(e=g(e,o.headers),t.headers=e)}return t},C=(()=>{let r=!1,t=!1;const e=typeof globalThis.ReadableStream=="function",s=typeof globalThis.Request=="function";if(e&&s)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type")}catch(o){if(o instanceof Error&&o.message==="unsupported BodyInit type")return!1;throw o}return r&&!t})(),A=typeof globalThis.AbortController=="function",P=typeof globalThis.ReadableStream=="function",O=typeof globalThis.FormData=="function",k=["get","post","put","patch","head","delete"],I={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},m=2147483647,x=Symbol("stop"),U={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},j={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0},L=r=>k.includes(r)?r.toUpperCase():r,H=["get","put","head","delete","options","trace"],v=[408,413,429,500,502,503,504],N=[413,429,503],R={limit:2,methods:H,statusCodes:v,afterStatusCodes:N,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:r=>.3*2**(r-1)*1e3},M=(r={})=>{if(typeof r=="number")return{...R,limit:r};if(r.methods&&!Array.isArray(r.methods))throw new Error("retry.methods must be an array");if(r.statusCodes&&!Array.isArray(r.statusCodes))throw new Error("retry.statusCodes must be an array");return{...R,...r}};async function $(r,t,e,s){return new Promise((o,n)=>{const i=setTimeout(()=>{e&&e.abort(),n(new T(r))},s.timeout);s.fetch(r,t).then(o).catch(n).then(()=>{clearTimeout(i)})})}async function B(r,{signal:t}){return new Promise((e,s)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",o,{once:!0}));function o(){clearTimeout(n),s(t.reason)}const n=setTimeout(()=>{t==null||t.removeEventListener("abort",o),e()},r)})}const D=(r,t)=>{const e={};for(const s in t)!(s in j)&&!(s in U)&&!(s in r)&&(e[s]=t[s]);return e};class y{constructor(t,e={}){h(this,"request");h(this,"abortController");h(this,"_retryCount",0);h(this,"_input");h(this,"_options");var s,o;if(this._input=t,this._options={...e,headers:g(this._input.headers,e.headers),hooks:q({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:L(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:M(e.retry),throwHttpErrors:e.throwHttpErrors!==!1,timeout:e.timeout??1e4,fetch:e.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(A){this.abortController=new globalThis.AbortController;const n=this._options.signal??this._input.signal;n==null||n.addEventListener("abort",()=>{this.abortController.abort(n.reason)}),this._options.signal=this.abortController.signal}if(C&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=((o=(s=this._options).stringifyJson)==null?void 0:o.call(s,this._options.json))??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const i="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,i);(O&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}}static create(t,e){const s=new y(t,e),o=async()=>{if(typeof s._options.timeout=="number"&&s._options.timeout>m)throw new RangeError(`The \`timeout\` option cannot be greater than ${m}`);await Promise.resolve();let a=await s._fetch();for(const u of s._options.hooks.afterResponse){const c=await u(s.request,s._options,s._decorateResponse(a.clone()));c instanceof globalThis.Response&&(a=c)}if(s._decorateResponse(a),!a.ok&&s._options.throwHttpErrors){let u=new w(a,s.request,s._options);for(const c of s._options.hooks.beforeError)u=await c(u);throw u}if(s._options.onDownloadProgress){if(typeof s._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!P)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return s._stream(a.clone(),s._options.onDownloadProgress)}return a},i=s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(o):o();for(const[a,u]of Object.entries(I))i[a]=async()=>{s.request.headers.set("accept",s.request.headers.get("accept")||u);const f=(await i).clone();if(a==="json"){if(f.status===204||(await f.clone().arrayBuffer()).byteLength===0)return"";if(e.parseJson)return e.parseJson(await f.text())}return f[a]()};return i}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof T)throw t;if(t instanceof w){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;const s=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(s&&this._options.retry.afterStatusCodes.includes(t.response.status)){let o=Number(s)*1e3;Number.isNaN(o)?o=Date.parse(s)-Date.now():o>=Date.parse("2024-01-01")&&(o-=Date.now());const n=this._options.retry.maxRetryAfter??o;return o<n?o:n}if(t.response.status===413)throw t}const e=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,e)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(e){const s=Math.min(this._calculateRetryDelay(e),m);if(this._retryCount<1)throw e;await B(s,{signal:this._options.signal});for(const o of this._options.hooks.beforeRetry)if(await o({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===x)return;return this._retry(t)}}async _fetch(){for(const s of this._options.hooks.beforeRequest){const o=await s(this.request,this._options);if(o instanceof Request){this.request=o;break}if(o instanceof Response)return o}const t=D(this.request,this._options),e=this.request;return this.request=e.clone(),this._options.timeout===!1?this._options.fetch(e,t):$(e,t,this.abortController,this._options)}_stream(t,e){const s=Number(t.headers.get("content-length"))||0;let o=0;return t.status===204?(e&&e({percent:1,totalBytes:s,transferredBytes:o},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(n){const i=t.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:s},new Uint8Array);async function a(){const{done:u,value:c}=await i.read();if(u){n.close();return}if(e){o+=c.byteLength;const f=s===0?0:o/s;e({percent:f,transferredBytes:o,totalBytes:s},c)}n.enqueue(c),await a()}await a()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}/*! MIT License © Sindre Sorhus */const b=r=>{const t=(e,s)=>y.create(e,l(r,s));for(const e of k)t[e]=(s,o)=>y.create(s,l(r,o,{method:e}));return t.create=e=>b(l(e)),t.extend=e=>(typeof e=="function"&&(e=e(r??{})),b(l(r,e))),t.stop=x,t},J=b();exports.fetch=J;
|
|
2
|
-
//# sourceMappingURL=fetch.cjs.map
|
package/dist/utils/fetch.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.cjs","sources":["../../../../node_modules/.pnpm/ky@1.7.2/node_modules/ky/distribution/errors/HTTPError.js","../../../../node_modules/.pnpm/ky@1.7.2/node_modules/ky/distribution/errors/TimeoutError.js","../../../../node_modules/.pnpm/ky@1.7.2/node_modules/ky/distribution/utils/is.js","../../../../node_modules/.pnpm/ky@1.7.2/node_modules/ky/distribution/utils/merge.js","../../../../node_modules/.pnpm/ky@1.7.2/node_modules/ky/distribution/core/constants.js","../../../../node_modules/.pnpm/ky@1.7.2/node_modules/ky/distribution/utils/normalize.js","../../../../node_modules/.pnpm/ky@1.7.2/node_modules/ky/distribution/utils/timeout.js","../../../../node_modules/.pnpm/ky@1.7.2/node_modules/ky/distribution/utils/delay.js","../../../../node_modules/.pnpm/ky@1.7.2/node_modules/ky/distribution/utils/options.js","../../../../node_modules/.pnpm/ky@1.7.2/node_modules/ky/distribution/core/Ky.js","../../../../node_modules/.pnpm/ky@1.7.2/node_modules/ky/distribution/index.js"],"sourcesContent":["export class HTTPError extends Error {\n response;\n request;\n options;\n constructor(response, request, options) {\n const code = (response.status || response.status === 0) ? response.status : '';\n const title = response.statusText || '';\n const status = `${code} ${title}`.trim();\n const reason = status ? `status code ${status}` : 'an unknown error';\n super(`Request failed with ${reason}: ${request.method} ${request.url}`);\n this.name = 'HTTPError';\n this.response = response;\n this.request = request;\n this.options = options;\n }\n}\n//# sourceMappingURL=HTTPError.js.map","export class TimeoutError extends Error {\n request;\n constructor(request) {\n super(`Request timed out: ${request.method} ${request.url}`);\n this.name = 'TimeoutError';\n this.request = request;\n }\n}\n//# sourceMappingURL=TimeoutError.js.map","// eslint-disable-next-line @typescript-eslint/ban-types\nexport const isObject = (value) => value !== null && typeof value === 'object';\n//# sourceMappingURL=is.js.map","import { isObject } from './is.js';\nexport const validateAndMerge = (...sources) => {\n for (const source of sources) {\n if ((!isObject(source) || Array.isArray(source)) && source !== undefined) {\n throw new TypeError('The `options` argument must be an object');\n }\n }\n return deepMerge({}, ...sources);\n};\nexport const mergeHeaders = (source1 = {}, source2 = {}) => {\n const result = new globalThis.Headers(source1);\n const isHeadersInstance = source2 instanceof globalThis.Headers;\n const source = new globalThis.Headers(source2);\n for (const [key, value] of source.entries()) {\n if ((isHeadersInstance && value === 'undefined') || value === undefined) {\n result.delete(key);\n }\n else {\n result.set(key, value);\n }\n }\n return result;\n};\nfunction newHookValue(original, incoming, property) {\n return (Object.hasOwn(incoming, property) && incoming[property] === undefined)\n ? []\n : deepMerge(original[property] ?? [], incoming[property] ?? []);\n}\nexport const mergeHooks = (original = {}, incoming = {}) => ({\n beforeRequest: newHookValue(original, incoming, 'beforeRequest'),\n beforeRetry: newHookValue(original, incoming, 'beforeRetry'),\n afterResponse: newHookValue(original, incoming, 'afterResponse'),\n beforeError: newHookValue(original, incoming, 'beforeError'),\n});\n// TODO: Make this strongly-typed (no `any`).\nexport const deepMerge = (...sources) => {\n let returnValue = {};\n let headers = {};\n let hooks = {};\n for (const source of sources) {\n if (Array.isArray(source)) {\n if (!Array.isArray(returnValue)) {\n returnValue = [];\n }\n returnValue = [...returnValue, ...source];\n }\n else if (isObject(source)) {\n for (let [key, value] of Object.entries(source)) {\n if (isObject(value) && key in returnValue) {\n value = deepMerge(returnValue[key], value);\n }\n returnValue = { ...returnValue, [key]: value };\n }\n if (isObject(source.hooks)) {\n hooks = mergeHooks(hooks, source.hooks);\n returnValue.hooks = hooks;\n }\n if (isObject(source.headers)) {\n headers = mergeHeaders(headers, source.headers);\n returnValue.headers = headers;\n }\n }\n }\n return returnValue;\n};\n//# sourceMappingURL=merge.js.map","export const supportsRequestStreams = (() => {\n let duplexAccessed = false;\n let hasContentType = false;\n const supportsReadableStream = typeof globalThis.ReadableStream === 'function';\n const supportsRequest = typeof globalThis.Request === 'function';\n if (supportsReadableStream && supportsRequest) {\n try {\n hasContentType = new globalThis.Request('https://empty.invalid', {\n body: new globalThis.ReadableStream(),\n method: 'POST',\n // @ts-expect-error - Types are outdated.\n get duplex() {\n duplexAccessed = true;\n return 'half';\n },\n }).headers.has('Content-Type');\n }\n catch (error) {\n // QQBrowser on iOS throws \"unsupported BodyInit type\" error (see issue #581)\n if (error instanceof Error && error.message === 'unsupported BodyInit type') {\n return false;\n }\n throw error;\n }\n }\n return duplexAccessed && !hasContentType;\n})();\nexport const supportsAbortController = typeof globalThis.AbortController === 'function';\nexport const supportsResponseStreams = typeof globalThis.ReadableStream === 'function';\nexport const supportsFormData = typeof globalThis.FormData === 'function';\nexport const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];\nconst validate = () => undefined;\nvalidate();\nexport const responseTypes = {\n json: 'application/json',\n text: 'text/*',\n formData: 'multipart/form-data',\n arrayBuffer: '*/*',\n blob: '*/*',\n};\n// The maximum value of a 32bit int (see issue #117)\nexport const maxSafeTimeout = 2_147_483_647;\nexport const stop = Symbol('stop');\nexport const kyOptionKeys = {\n json: true,\n parseJson: true,\n stringifyJson: true,\n searchParams: true,\n prefixUrl: true,\n retry: true,\n timeout: true,\n hooks: true,\n throwHttpErrors: true,\n onDownloadProgress: true,\n fetch: true,\n};\nexport const requestOptionsRegistry = {\n method: true,\n headers: true,\n body: true,\n mode: true,\n credentials: true,\n cache: true,\n redirect: true,\n referrer: true,\n referrerPolicy: true,\n integrity: true,\n keepalive: true,\n signal: true,\n window: true,\n dispatcher: true,\n duplex: true,\n priority: true,\n};\n//# sourceMappingURL=constants.js.map","import { requestMethods } from '../core/constants.js';\nexport const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;\nconst retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];\nconst retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];\nconst retryAfterStatusCodes = [413, 429, 503];\nconst defaultRetryOptions = {\n limit: 2,\n methods: retryMethods,\n statusCodes: retryStatusCodes,\n afterStatusCodes: retryAfterStatusCodes,\n maxRetryAfter: Number.POSITIVE_INFINITY,\n backoffLimit: Number.POSITIVE_INFINITY,\n delay: attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000,\n};\nexport const normalizeRetryOptions = (retry = {}) => {\n if (typeof retry === 'number') {\n return {\n ...defaultRetryOptions,\n limit: retry,\n };\n }\n if (retry.methods && !Array.isArray(retry.methods)) {\n throw new Error('retry.methods must be an array');\n }\n if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {\n throw new Error('retry.statusCodes must be an array');\n }\n return {\n ...defaultRetryOptions,\n ...retry,\n };\n};\n//# sourceMappingURL=normalize.js.map","import { TimeoutError } from '../errors/TimeoutError.js';\n// `Promise.race()` workaround (#91)\nexport default async function timeout(request, init, abortController, options) {\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n if (abortController) {\n abortController.abort();\n }\n reject(new TimeoutError(request));\n }, options.timeout);\n void options\n .fetch(request, init)\n .then(resolve)\n .catch(reject)\n .then(() => {\n clearTimeout(timeoutId);\n });\n });\n}\n//# sourceMappingURL=timeout.js.map","// https://github.com/sindresorhus/delay/tree/ab98ae8dfcb38e1593286c94d934e70d14a4e111\nexport default async function delay(ms, { signal }) {\n return new Promise((resolve, reject) => {\n if (signal) {\n signal.throwIfAborted();\n signal.addEventListener('abort', abortHandler, { once: true });\n }\n function abortHandler() {\n clearTimeout(timeoutId);\n reject(signal.reason);\n }\n const timeoutId = setTimeout(() => {\n signal?.removeEventListener('abort', abortHandler);\n resolve();\n }, ms);\n });\n}\n//# sourceMappingURL=delay.js.map","import { kyOptionKeys, requestOptionsRegistry } from '../core/constants.js';\nexport const findUnknownOptions = (request, options) => {\n const unknownOptions = {};\n for (const key in options) {\n if (!(key in requestOptionsRegistry) && !(key in kyOptionKeys) && !(key in request)) {\n unknownOptions[key] = options[key];\n }\n }\n return unknownOptions;\n};\n//# sourceMappingURL=options.js.map","import { HTTPError } from '../errors/HTTPError.js';\nimport { TimeoutError } from '../errors/TimeoutError.js';\nimport { mergeHeaders, mergeHooks } from '../utils/merge.js';\nimport { normalizeRequestMethod, normalizeRetryOptions } from '../utils/normalize.js';\nimport timeout from '../utils/timeout.js';\nimport delay from '../utils/delay.js';\nimport { findUnknownOptions } from '../utils/options.js';\nimport { maxSafeTimeout, responseTypes, stop, supportsAbortController, supportsFormData, supportsResponseStreams, supportsRequestStreams, } from './constants.js';\nexport class Ky {\n static create(input, options) {\n const ky = new Ky(input, options);\n const function_ = async () => {\n if (typeof ky._options.timeout === 'number' && ky._options.timeout > maxSafeTimeout) {\n throw new RangeError(`The \\`timeout\\` option cannot be greater than ${maxSafeTimeout}`);\n }\n // Delay the fetch so that body method shortcuts can set the Accept header\n await Promise.resolve();\n let response = await ky._fetch();\n for (const hook of ky._options.hooks.afterResponse) {\n // eslint-disable-next-line no-await-in-loop\n const modifiedResponse = await hook(ky.request, ky._options, ky._decorateResponse(response.clone()));\n if (modifiedResponse instanceof globalThis.Response) {\n response = modifiedResponse;\n }\n }\n ky._decorateResponse(response);\n if (!response.ok && ky._options.throwHttpErrors) {\n let error = new HTTPError(response, ky.request, ky._options);\n for (const hook of ky._options.hooks.beforeError) {\n // eslint-disable-next-line no-await-in-loop\n error = await hook(error);\n }\n throw error;\n }\n // If `onDownloadProgress` is passed, it uses the stream API internally\n /* istanbul ignore next */\n if (ky._options.onDownloadProgress) {\n if (typeof ky._options.onDownloadProgress !== 'function') {\n throw new TypeError('The `onDownloadProgress` option must be a function');\n }\n if (!supportsResponseStreams) {\n throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');\n }\n return ky._stream(response.clone(), ky._options.onDownloadProgress);\n }\n return response;\n };\n const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());\n const result = (isRetriableMethod ? ky._retry(function_) : function_());\n for (const [type, mimeType] of Object.entries(responseTypes)) {\n result[type] = async () => {\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);\n const awaitedResult = await result;\n const response = awaitedResult.clone();\n if (type === 'json') {\n if (response.status === 204) {\n return '';\n }\n const arrayBuffer = await response.clone().arrayBuffer();\n const responseSize = arrayBuffer.byteLength;\n if (responseSize === 0) {\n return '';\n }\n if (options.parseJson) {\n return options.parseJson(await response.text());\n }\n }\n return response[type]();\n };\n }\n return result;\n }\n request;\n abortController;\n _retryCount = 0;\n _input;\n _options;\n // eslint-disable-next-line complexity\n constructor(input, options = {}) {\n this._input = input;\n this._options = {\n ...options,\n headers: mergeHeaders(this._input.headers, options.headers),\n hooks: mergeHooks({\n beforeRequest: [],\n beforeRetry: [],\n beforeError: [],\n afterResponse: [],\n }, options.hooks),\n method: normalizeRequestMethod(options.method ?? this._input.method),\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n prefixUrl: String(options.prefixUrl || ''),\n retry: normalizeRetryOptions(options.retry),\n throwHttpErrors: options.throwHttpErrors !== false,\n timeout: options.timeout ?? 10_000,\n fetch: options.fetch ?? globalThis.fetch.bind(globalThis),\n };\n if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {\n throw new TypeError('`input` must be a string, URL, or Request');\n }\n if (this._options.prefixUrl && typeof this._input === 'string') {\n if (this._input.startsWith('/')) {\n throw new Error('`input` must not begin with a slash when using `prefixUrl`');\n }\n if (!this._options.prefixUrl.endsWith('/')) {\n this._options.prefixUrl += '/';\n }\n this._input = this._options.prefixUrl + this._input;\n }\n if (supportsAbortController) {\n this.abortController = new globalThis.AbortController();\n const originalSignal = this._options.signal ?? this._input.signal;\n originalSignal?.addEventListener('abort', () => {\n this.abortController.abort(originalSignal.reason);\n });\n this._options.signal = this.abortController.signal;\n }\n if (supportsRequestStreams) {\n // @ts-expect-error - Types are outdated.\n this._options.duplex = 'half';\n }\n if (this._options.json !== undefined) {\n this._options.body = this._options.stringifyJson?.(this._options.json) ?? JSON.stringify(this._options.json);\n this._options.headers.set('content-type', this._options.headers.get('content-type') ?? 'application/json');\n }\n this.request = new globalThis.Request(this._input, this._options);\n if (this._options.searchParams) {\n // eslint-disable-next-line unicorn/prevent-abbreviations\n const textSearchParams = typeof this._options.searchParams === 'string'\n ? this._options.searchParams.replace(/^\\?/, '')\n : new URLSearchParams(this._options.searchParams).toString();\n // eslint-disable-next-line unicorn/prevent-abbreviations\n const searchParams = '?' + textSearchParams;\n const url = this.request.url.replace(/(?:\\?.*?)?(?=#|$)/, searchParams);\n // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one\n if (((supportsFormData && this._options.body instanceof globalThis.FormData)\n || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {\n this.request.headers.delete('content-type');\n }\n // The spread of `this.request` is required as otherwise it misses the `duplex` option for some reason and throws.\n this.request = new globalThis.Request(new globalThis.Request(url, { ...this.request }), this._options);\n }\n }\n _calculateRetryDelay(error) {\n this._retryCount++;\n if (this._retryCount > this._options.retry.limit || error instanceof TimeoutError) {\n throw error;\n }\n if (error instanceof HTTPError) {\n if (!this._options.retry.statusCodes.includes(error.response.status)) {\n throw error;\n }\n const retryAfter = error.response.headers.get('Retry-After')\n ?? error.response.headers.get('RateLimit-Reset')\n ?? error.response.headers.get('X-RateLimit-Reset') // GitHub\n ?? error.response.headers.get('X-Rate-Limit-Reset'); // Twitter\n if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {\n let after = Number(retryAfter) * 1000;\n if (Number.isNaN(after)) {\n after = Date.parse(retryAfter) - Date.now();\n }\n else if (after >= Date.parse('2024-01-01')) {\n // A large number is treated as a timestamp (fixed threshold protects against clock skew)\n after -= Date.now();\n }\n const max = this._options.retry.maxRetryAfter ?? after;\n return after < max ? after : max;\n }\n if (error.response.status === 413) {\n throw error;\n }\n }\n const retryDelay = this._options.retry.delay(this._retryCount);\n return Math.min(this._options.retry.backoffLimit, retryDelay);\n }\n _decorateResponse(response) {\n if (this._options.parseJson) {\n response.json = async () => this._options.parseJson(await response.text());\n }\n return response;\n }\n async _retry(function_) {\n try {\n return await function_();\n }\n catch (error) {\n const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);\n if (this._retryCount < 1) {\n throw error;\n }\n await delay(ms, { signal: this._options.signal });\n for (const hook of this._options.hooks.beforeRetry) {\n // eslint-disable-next-line no-await-in-loop\n const hookResult = await hook({\n request: this.request,\n options: this._options,\n error: error,\n retryCount: this._retryCount,\n });\n // If `stop` is returned from the hook, the retry process is stopped\n if (hookResult === stop) {\n return;\n }\n }\n return this._retry(function_);\n }\n }\n async _fetch() {\n for (const hook of this._options.hooks.beforeRequest) {\n // eslint-disable-next-line no-await-in-loop\n const result = await hook(this.request, this._options);\n if (result instanceof Request) {\n this.request = result;\n break;\n }\n if (result instanceof Response) {\n return result;\n }\n }\n const nonRequestOptions = findUnknownOptions(this.request, this._options);\n // Cloning is done here to prepare in advance for retries\n const mainRequest = this.request;\n this.request = mainRequest.clone();\n if (this._options.timeout === false) {\n return this._options.fetch(mainRequest, nonRequestOptions);\n }\n return timeout(mainRequest, nonRequestOptions, this.abortController, this._options);\n }\n /* istanbul ignore next */\n _stream(response, onDownloadProgress) {\n const totalBytes = Number(response.headers.get('content-length')) || 0;\n let transferredBytes = 0;\n if (response.status === 204) {\n if (onDownloadProgress) {\n onDownloadProgress({ percent: 1, totalBytes, transferredBytes }, new Uint8Array());\n }\n return new globalThis.Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n }\n return new globalThis.Response(new globalThis.ReadableStream({\n async start(controller) {\n const reader = response.body.getReader();\n if (onDownloadProgress) {\n onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());\n }\n async function read() {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n return;\n }\n if (onDownloadProgress) {\n transferredBytes += value.byteLength;\n const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;\n onDownloadProgress({ percent, transferredBytes, totalBytes }, value);\n }\n controller.enqueue(value);\n await read();\n }\n await read();\n },\n }), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n }\n}\n//# sourceMappingURL=Ky.js.map","/*! MIT License © Sindre Sorhus */\nimport { Ky } from './core/Ky.js';\nimport { requestMethods, stop } from './core/constants.js';\nimport { validateAndMerge } from './utils/merge.js';\nconst createInstance = (defaults) => {\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));\n for (const method of requestMethods) {\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));\n }\n ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));\n ky.extend = (newDefaults) => {\n if (typeof newDefaults === 'function') {\n newDefaults = newDefaults(defaults ?? {});\n }\n return createInstance(validateAndMerge(defaults, newDefaults));\n };\n ky.stop = stop;\n return ky;\n};\nconst ky = createInstance();\nexport default ky;\nexport { HTTPError } from './errors/HTTPError.js';\nexport { TimeoutError } from './errors/TimeoutError.js';\n//# sourceMappingURL=index.js.map"],"names":["HTTPError","response","request","options","code","title","status","reason","__publicField","TimeoutError","isObject","value","validateAndMerge","sources","source","deepMerge","mergeHeaders","source1","source2","result","isHeadersInstance","key","newHookValue","original","incoming","property","mergeHooks","returnValue","headers","hooks","supportsRequestStreams","duplexAccessed","hasContentType","supportsReadableStream","supportsRequest","error","supportsAbortController","supportsResponseStreams","supportsFormData","requestMethods","responseTypes","maxSafeTimeout","stop","kyOptionKeys","requestOptionsRegistry","normalizeRequestMethod","input","retryMethods","retryStatusCodes","retryAfterStatusCodes","defaultRetryOptions","attemptCount","normalizeRetryOptions","retry","timeout","init","abortController","resolve","reject","timeoutId","delay","ms","signal","abortHandler","findUnknownOptions","unknownOptions","Ky","originalSignal","_b","_a","searchParams","url","ky","function_","hook","modifiedResponse","type","mimeType","retryAfter","after","max","retryDelay","nonRequestOptions","mainRequest","onDownloadProgress","totalBytes","transferredBytes","controller","reader","read","done","percent","createInstance","defaults","method","newDefaults"],"mappings":"oPAAO,MAAMA,UAAkB,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AAY,EAExF,eAAeI,GAAO,CAClB,KAAM,CAAE,KAAAC,EAAM,MAAA/E,CAAK,EAAK,MAAM6E,EAAO,KAAI,EACzC,GAAIE,EAAM,CACNH,EAAW,MAAK,EAChB,MACH,CACD,GAAIH,EAAoB,CACpBE,GAAoB3E,EAAM,WAC1B,MAAMgF,EAAUN,IAAe,EAAI,EAAIC,EAAmBD,EAC1DD,EAAmB,CAAE,QAAAO,EAAS,iBAAAL,EAAkB,WAAAD,CAAY,EAAE1E,CAAK,CACtE,CACD4E,EAAW,QAAQ5E,CAAK,EACxB,MAAM8E,EAAI,CACb,CACD,MAAMA,EAAI,CACb,CACb,CAAS,EAAG,CACA,OAAQxF,EAAS,OACjB,WAAYA,EAAS,WACrB,QAASA,EAAS,OAC9B,CAAS,CACJ,CACL,CC/QA,kCAIA,MAAM2F,EAAkBC,GAAa,CAEjC,MAAMrB,EAAK,CAAC1B,EAAO3C,IAAY+D,EAAG,OAAOpB,EAAOlC,EAAiBiF,EAAU1F,CAAO,CAAC,EACnF,UAAW2F,KAAUvD,EAEjBiC,EAAGsB,CAAM,EAAI,CAAChD,EAAO3C,IAAY+D,EAAG,OAAOpB,EAAOlC,EAAiBiF,EAAU1F,EAAS,CAAE,OAAA2F,CAAM,CAAE,CAAC,EAErG,OAAAtB,EAAG,OAAUuB,GAAgBH,EAAehF,EAAiBmF,CAAW,CAAC,EACzEvB,EAAG,OAAUuB,IACL,OAAOA,GAAgB,aACvBA,EAAcA,EAAYF,GAAY,CAAA,CAAE,GAErCD,EAAehF,EAAiBiF,EAAUE,CAAW,CAAC,GAEjEvB,EAAG,KAAO9B,EACH8B,CACX,EACMA,EAAKoB,EAAc","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10]}
|
package/dist/utils/fetch.d.ts
DELETED
package/dist/utils/fetch.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var E=Object.defineProperty;var C=(r,t,e)=>t in r?E(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var h=(r,t,e)=>C(r,typeof t!="symbol"?t+"":t,e);class w extends Error{constructor(e,s,o){const n=e.status||e.status===0?e.status:"",i=e.statusText||"",a=`${n} ${i}`.trim(),u=a?`status code ${a}`:"an unknown error";super(`Request failed with ${u}: ${s.method} ${s.url}`);h(this,"response");h(this,"request");h(this,"options");this.name="HTTPError",this.response=e,this.request=s,this.options=o}}class T extends Error{constructor(e){super(`Request timed out: ${e.method} ${e.url}`);h(this,"request");this.name="TimeoutError",this.request=e}}const p=r=>r!==null&&typeof r=="object",l=(...r)=>{for(const t of r)if((!p(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return _({},...r)},g=(r={},t={})=>{const e=new globalThis.Headers(r),s=t instanceof globalThis.Headers,o=new globalThis.Headers(t);for(const[n,i]of o.entries())s&&i==="undefined"||i===void 0?e.delete(n):e.set(n,i);return e};function d(r,t,e){return Object.hasOwn(t,e)&&t[e]===void 0?[]:_(r[e]??[],t[e]??[])}const q=(r={},t={})=>({beforeRequest:d(r,t,"beforeRequest"),beforeRetry:d(r,t,"beforeRetry"),afterResponse:d(r,t,"afterResponse"),beforeError:d(r,t,"beforeError")}),_=(...r)=>{let t={},e={},s={};for(const o of r)if(Array.isArray(o))Array.isArray(t)||(t=[]),t=[...t,...o];else if(p(o)){for(let[n,i]of Object.entries(o))p(i)&&n in t&&(i=_(t[n],i)),t={...t,[n]:i};p(o.hooks)&&(s=q(s,o.hooks),t.hooks=s),p(o.headers)&&(e=g(e,o.headers),t.headers=e)}return t},S=(()=>{let r=!1,t=!1;const e=typeof globalThis.ReadableStream=="function",s=typeof globalThis.Request=="function";if(e&&s)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type")}catch(o){if(o instanceof Error&&o.message==="unsupported BodyInit type")return!1;throw o}return r&&!t})(),A=typeof globalThis.AbortController=="function",P=typeof globalThis.ReadableStream=="function",I=typeof globalThis.FormData=="function",k=["get","post","put","patch","head","delete"],O={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},m=2147483647,x=Symbol("stop"),U={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},L={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0},j=r=>k.includes(r)?r.toUpperCase():r,H=["get","put","head","delete","options","trace"],v=[408,413,429,500,502,503,504],N=[413,429,503],R={limit:2,methods:H,statusCodes:v,afterStatusCodes:N,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:r=>.3*2**(r-1)*1e3},$=(r={})=>{if(typeof r=="number")return{...R,limit:r};if(r.methods&&!Array.isArray(r.methods))throw new Error("retry.methods must be an array");if(r.statusCodes&&!Array.isArray(r.statusCodes))throw new Error("retry.statusCodes must be an array");return{...R,...r}};async function M(r,t,e,s){return new Promise((o,n)=>{const i=setTimeout(()=>{e&&e.abort(),n(new T(r))},s.timeout);s.fetch(r,t).then(o).catch(n).then(()=>{clearTimeout(i)})})}async function B(r,{signal:t}){return new Promise((e,s)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",o,{once:!0}));function o(){clearTimeout(n),s(t.reason)}const n=setTimeout(()=>{t==null||t.removeEventListener("abort",o),e()},r)})}const D=(r,t)=>{const e={};for(const s in t)!(s in L)&&!(s in U)&&!(s in r)&&(e[s]=t[s]);return e};class y{constructor(t,e={}){h(this,"request");h(this,"abortController");h(this,"_retryCount",0);h(this,"_input");h(this,"_options");var s,o;if(this._input=t,this._options={...e,headers:g(this._input.headers,e.headers),hooks:q({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:j(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:$(e.retry),throwHttpErrors:e.throwHttpErrors!==!1,timeout:e.timeout??1e4,fetch:e.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(A){this.abortController=new globalThis.AbortController;const n=this._options.signal??this._input.signal;n==null||n.addEventListener("abort",()=>{this.abortController.abort(n.reason)}),this._options.signal=this.abortController.signal}if(S&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=((o=(s=this._options).stringifyJson)==null?void 0:o.call(s,this._options.json))??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const i="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,i);(I&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}}static create(t,e){const s=new y(t,e),o=async()=>{if(typeof s._options.timeout=="number"&&s._options.timeout>m)throw new RangeError(`The \`timeout\` option cannot be greater than ${m}`);await Promise.resolve();let a=await s._fetch();for(const u of s._options.hooks.afterResponse){const c=await u(s.request,s._options,s._decorateResponse(a.clone()));c instanceof globalThis.Response&&(a=c)}if(s._decorateResponse(a),!a.ok&&s._options.throwHttpErrors){let u=new w(a,s.request,s._options);for(const c of s._options.hooks.beforeError)u=await c(u);throw u}if(s._options.onDownloadProgress){if(typeof s._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!P)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return s._stream(a.clone(),s._options.onDownloadProgress)}return a},i=s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(o):o();for(const[a,u]of Object.entries(O))i[a]=async()=>{s.request.headers.set("accept",s.request.headers.get("accept")||u);const f=(await i).clone();if(a==="json"){if(f.status===204||(await f.clone().arrayBuffer()).byteLength===0)return"";if(e.parseJson)return e.parseJson(await f.text())}return f[a]()};return i}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof T)throw t;if(t instanceof w){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;const s=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(s&&this._options.retry.afterStatusCodes.includes(t.response.status)){let o=Number(s)*1e3;Number.isNaN(o)?o=Date.parse(s)-Date.now():o>=Date.parse("2024-01-01")&&(o-=Date.now());const n=this._options.retry.maxRetryAfter??o;return o<n?o:n}if(t.response.status===413)throw t}const e=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,e)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(e){const s=Math.min(this._calculateRetryDelay(e),m);if(this._retryCount<1)throw e;await B(s,{signal:this._options.signal});for(const o of this._options.hooks.beforeRetry)if(await o({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===x)return;return this._retry(t)}}async _fetch(){for(const s of this._options.hooks.beforeRequest){const o=await s(this.request,this._options);if(o instanceof Request){this.request=o;break}if(o instanceof Response)return o}const t=D(this.request,this._options),e=this.request;return this.request=e.clone(),this._options.timeout===!1?this._options.fetch(e,t):M(e,t,this.abortController,this._options)}_stream(t,e){const s=Number(t.headers.get("content-length"))||0;let o=0;return t.status===204?(e&&e({percent:1,totalBytes:s,transferredBytes:o},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(n){const i=t.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:s},new Uint8Array);async function a(){const{done:u,value:c}=await i.read();if(u){n.close();return}if(e){o+=c.byteLength;const f=s===0?0:o/s;e({percent:f,transferredBytes:o,totalBytes:s},c)}n.enqueue(c),await a()}await a()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}/*! MIT License © Sindre Sorhus */const b=r=>{const t=(e,s)=>y.create(e,l(r,s));for(const e of k)t[e]=(s,o)=>y.create(s,l(r,o,{method:e}));return t.create=e=>b(l(e)),t.extend=e=>(typeof e=="function"&&(e=e(r??{})),b(l(r,e))),t.stop=x,t},V=b();export{V as fetch};
|
|
2
|
-
//# sourceMappingURL=fetch.mjs.map
|