@nhost/nhost-js 4.6.0 → 4.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/fetch-DjLYNzv8.cjs +2 -0
- package/dist/fetch-DjLYNzv8.cjs.map +1 -0
- package/dist/fetch-DsJJyobH.js +2 -0
- package/dist/fetch-DsJJyobH.js.map +1 -0
- package/dist/graphql-BEFThamT.cjs +2 -0
- package/dist/graphql-BEFThamT.cjs.map +1 -0
- package/dist/graphql-CTZ9QikM.js +2 -0
- package/dist/graphql-CTZ9QikM.js.map +1 -0
- package/dist/nhost-js/auth.cjs +2 -2
- package/dist/nhost-js/auth.cjs.map +1 -1
- package/dist/nhost-js/auth.js +2 -32
- package/dist/nhost-js/auth.js.map +1 -1
- package/dist/nhost-js/fetch.cjs +1 -2
- package/dist/nhost-js/fetch.js +1 -30
- package/dist/nhost-js/functions.cjs +2 -2
- package/dist/nhost-js/functions.cjs.map +1 -1
- package/dist/nhost-js/functions.js +2 -50
- package/dist/nhost-js/functions.js.map +1 -1
- package/dist/nhost-js/graphql.cjs +1 -2
- package/dist/nhost-js/graphql.js +1 -53
- package/dist/nhost-js/session.cjs +1 -2
- package/dist/nhost-js/session.js +1 -242
- package/dist/nhost-js/storage.cjs +2 -2
- package/dist/nhost-js/storage.cjs.map +1 -1
- package/dist/nhost-js/storage.js +2 -342
- package/dist/nhost-js/storage.js.map +1 -1
- package/dist/nhost-js.cjs +2 -2
- package/dist/nhost-js.cjs.map +1 -1
- package/dist/nhost-js.js +2 -241
- package/dist/nhost-js.js.map +1 -1
- package/dist/nhost-js.umd.js +2 -2
- package/dist/nhost-js.umd.js.map +1 -1
- package/dist/refreshSession-BvZuC-Or.js +2 -0
- package/dist/refreshSession-BvZuC-Or.js.map +1 -0
- package/dist/refreshSession-ZW-JniXX.cjs +2 -0
- package/dist/refreshSession-ZW-JniXX.cjs.map +1 -0
- package/dist/session-oECsmiRB.js +2 -0
- package/dist/session-oECsmiRB.js.map +1 -0
- package/dist/session-r_9IPgQp.cjs +2 -0
- package/dist/session-r_9IPgQp.cjs.map +1 -0
- package/dist/src/auth/client.d.ts +227 -5
- package/dist/src/auth/client.d.ts.map +1 -1
- package/dist/src/auth/client.js +138 -0
- package/dist/src/auth/client.js.map +1 -1
- package/dist/src/graphql/client.d.ts +11 -0
- package/dist/src/graphql/client.d.ts.map +1 -1
- package/dist/src/graphql/client.js +31 -1
- package/dist/src/graphql/client.js.map +1 -1
- package/dist/src/graphql/index.d.ts +2 -1
- package/dist/src/graphql/index.d.ts.map +1 -1
- package/dist/src/graphql/index.js +1 -1
- package/dist/src/graphql/index.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -2
- package/dist/client-BL0edWHv.cjs +0 -2
- package/dist/client-BL0edWHv.cjs.map +0 -1
- package/dist/client-BOrTAJrs.js +0 -1304
- package/dist/client-BOrTAJrs.js.map +0 -1
- package/dist/fetch-2PHmQBIJ.js +0 -61
- package/dist/fetch-2PHmQBIJ.js.map +0 -1
- package/dist/fetch-DWXwEnoe.cjs +0 -2
- package/dist/fetch-DWXwEnoe.cjs.map +0 -1
- package/dist/middlewareWithAdminSession-CcuYKs5Y.js +0 -106
- package/dist/middlewareWithAdminSession-CcuYKs5Y.js.map +0 -1
- package/dist/middlewareWithAdminSession-j70iKbBX.cjs +0 -2
- package/dist/middlewareWithAdminSession-j70iKbBX.cjs.map +0 -1
- package/dist/nhost-js/fetch.cjs.map +0 -1
- package/dist/nhost-js/fetch.js.map +0 -1
- package/dist/nhost-js/graphql.cjs.map +0 -1
- package/dist/nhost-js/graphql.js.map +0 -1
- package/dist/nhost-js/session.cjs.map +0 -1
- package/dist/nhost-js/session.js.map +0 -1
- package/dist/refreshSession-Bw715ZmX.cjs +0 -2
- package/dist/refreshSession-Bw715ZmX.cjs.map +0 -1
- package/dist/refreshSession-WwGlzgtM.js +0 -95
- package/dist/refreshSession-WwGlzgtM.js.map +0 -1
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
import { r as refreshSession } from "./refreshSession-WwGlzgtM.js";
|
|
2
|
-
const attachAccessTokenMiddleware = (storage) => (next) => async (url, options = {}) => {
|
|
3
|
-
const headers = new Headers(options.headers || {});
|
|
4
|
-
if (headers.has("Authorization")) {
|
|
5
|
-
return next(url, options);
|
|
6
|
-
}
|
|
7
|
-
const session = storage.get();
|
|
8
|
-
if (session?.accessToken) {
|
|
9
|
-
const newOptions = {
|
|
10
|
-
...options,
|
|
11
|
-
headers: addAuthorizationHeader(headers, session)
|
|
12
|
-
};
|
|
13
|
-
return next(url, newOptions);
|
|
14
|
-
}
|
|
15
|
-
return next(url, options);
|
|
16
|
-
};
|
|
17
|
-
function addAuthorizationHeader(headers, session) {
|
|
18
|
-
if (session.accessToken) {
|
|
19
|
-
headers.set("Authorization", `Bearer ${session.accessToken}`);
|
|
20
|
-
}
|
|
21
|
-
return headers;
|
|
22
|
-
}
|
|
23
|
-
const sessionRefreshMiddleware = (auth, storage, options) => {
|
|
24
|
-
const { marginSeconds = 60 } = options || {};
|
|
25
|
-
return (next) => async (url, options2 = {}) => {
|
|
26
|
-
if (shouldSkipTokenHandling(url, options2)) {
|
|
27
|
-
return next(url, options2);
|
|
28
|
-
}
|
|
29
|
-
try {
|
|
30
|
-
await refreshSession(auth, storage, marginSeconds);
|
|
31
|
-
} catch {
|
|
32
|
-
}
|
|
33
|
-
return next(url, options2);
|
|
34
|
-
};
|
|
35
|
-
};
|
|
36
|
-
function shouldSkipTokenHandling(url, options) {
|
|
37
|
-
const headers = new Headers(options.headers || {});
|
|
38
|
-
if (headers.has("Authorization")) {
|
|
39
|
-
return true;
|
|
40
|
-
}
|
|
41
|
-
if (url.endsWith("/v1/token")) {
|
|
42
|
-
return true;
|
|
43
|
-
}
|
|
44
|
-
return false;
|
|
45
|
-
}
|
|
46
|
-
const updateSessionFromResponseMiddleware = (storage) => {
|
|
47
|
-
const sessionExtractor = (body) => {
|
|
48
|
-
if (typeof body === "string") {
|
|
49
|
-
return null;
|
|
50
|
-
}
|
|
51
|
-
if ("session" in body) {
|
|
52
|
-
return body.session || null;
|
|
53
|
-
}
|
|
54
|
-
if ("accessToken" in body && "refreshToken" in body && "user" in body) {
|
|
55
|
-
return body;
|
|
56
|
-
}
|
|
57
|
-
return null;
|
|
58
|
-
};
|
|
59
|
-
return (next) => async (url, options) => {
|
|
60
|
-
const response = await next(url, options);
|
|
61
|
-
try {
|
|
62
|
-
if (url.endsWith("/signout")) {
|
|
63
|
-
storage.remove();
|
|
64
|
-
return response;
|
|
65
|
-
}
|
|
66
|
-
if (url.endsWith("/token") || url.includes("/token/exchange") || url.includes("/signin/") || url.includes("/signup/")) {
|
|
67
|
-
const clonedResponse = response.clone();
|
|
68
|
-
const body = await clonedResponse.json().catch(() => null);
|
|
69
|
-
if (body) {
|
|
70
|
-
const session = sessionExtractor(body);
|
|
71
|
-
if (session?.accessToken && session.refreshToken) {
|
|
72
|
-
storage.set(session);
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
} catch (error) {
|
|
77
|
-
console.warn("Error in session response middleware:", error);
|
|
78
|
-
}
|
|
79
|
-
return response;
|
|
80
|
-
};
|
|
81
|
-
};
|
|
82
|
-
const withAdminSessionMiddleware = (options) => (next) => async (url, requestOptions = {}) => {
|
|
83
|
-
const headers = new Headers(requestOptions.headers || {});
|
|
84
|
-
if (!headers.has("x-hasura-admin-secret")) {
|
|
85
|
-
headers.set("x-hasura-admin-secret", options.adminSecret);
|
|
86
|
-
}
|
|
87
|
-
if (options.role && !headers.has("x-hasura-role")) {
|
|
88
|
-
headers.set("x-hasura-role", options.role);
|
|
89
|
-
}
|
|
90
|
-
if (options.sessionVariables) {
|
|
91
|
-
for (const [key, value] of Object.entries(options.sessionVariables)) {
|
|
92
|
-
const headerKey = key.startsWith("x-hasura-") ? key : `x-hasura-${key}`;
|
|
93
|
-
if (!headers.has(headerKey)) {
|
|
94
|
-
headers.set(headerKey, value);
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
return next(url, { ...requestOptions, headers });
|
|
99
|
-
};
|
|
100
|
-
export {
|
|
101
|
-
attachAccessTokenMiddleware as a,
|
|
102
|
-
sessionRefreshMiddleware as s,
|
|
103
|
-
updateSessionFromResponseMiddleware as u,
|
|
104
|
-
withAdminSessionMiddleware as w
|
|
105
|
-
};
|
|
106
|
-
//# sourceMappingURL=middlewareWithAdminSession-CcuYKs5Y.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"middlewareWithAdminSession-CcuYKs5Y.js","sources":["../src/fetch/middlewareAttachAccessToken.ts","../src/fetch/middlewareSessionRefresh.ts","../src/fetch/middlewareUpdateSessionFromResponse.ts","../src/fetch/middlewareWithAdminSession.ts"],"sourcesContent":["/**\n * Authorization token attachment middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically attach\n * authorization tokens to outgoing API requests, ensuring the client\n * is properly authenticated.\n */\n\nimport type { Session } from '../auth';\nimport type { SessionStorage } from '../session/storage';\nimport type { ChainFunction, FetchFunction } from './fetch';\n\n/**\n * Creates a fetch middleware that adds the Authorization header with the current access token.\n *\n * This middleware:\n * 1. Gets the current session from storage\n * 2. Adds the authorization header with the access token to outgoing requests\n *\n * This middleware should be used after the refresh middleware in the chain to\n * ensure the most recent token is used.\n *\n * @param storage - Storage implementation for retrieving session data\n * @returns A middleware function that adds Authorization headers\n */\nexport const attachAccessTokenMiddleware =\n (storage: SessionStorage): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(options.headers || {});\n\n // Skip if Authorization header is already set\n if (headers.has('Authorization')) {\n return next(url, options);\n }\n\n // Get current session from storage\n const session = storage.get();\n\n if (session?.accessToken) {\n // Add authorization header\n const newOptions = {\n ...options,\n headers: addAuthorizationHeader(headers, session),\n };\n\n // Continue with the fetch chain\n return next(url, newOptions);\n }\n\n // No session or no access token, continue without authorization\n return next(url, options);\n };\n\n/**\n * Adds the Authorization header with the access token to the request headers\n *\n * @param headers - Original request headers\n * @param session - Current session containing the access token\n * @returns Modified headers with Authorization header\n */\nfunction addAuthorizationHeader(headers: Headers, session: Session): Headers {\n if (session.accessToken) {\n headers.set('Authorization', `Bearer ${session.accessToken}`);\n }\n return headers;\n}\n","/**\n * Auth token refresh middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically refresh\n * authentication tokens before they expire, ensuring seamless API access\n * without requiring manual token refresh by the application.\n */\n\nimport type { Client } from '../auth';\nimport { refreshSession } from '../session/refreshSession';\nimport type { SessionStorage } from '../session/storage';\nimport type { ChainFunction, FetchFunction } from './fetch';\n\n/**\n * Creates a fetch middleware that automatically refreshes authentication tokens.\n *\n * This middleware:\n * 1. Checks if the current token is about to expire\n * 2. If so, uses the refresh token to obtain a new access token\n *\n * The middleware handles token refresh transparently, so the application\n * doesn't need to manually refresh tokens.\n *\n * @param auth - Auth API client for token refresh operations\n * @param storage - Storage implementation for persisting session data\n * @param options - Configuration options for token refresh behavior\n * @param options.marginSeconds - Number of seconds before token expiration to trigger a refresh, default is 60 seconds\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const sessionRefreshMiddleware = (\n auth: Client,\n storage: SessionStorage,\n options?: {\n marginSeconds?: number;\n },\n): ChainFunction => {\n const { marginSeconds = 60 } = options || {};\n\n // Create and return the chain function\n return (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): Promise<Response> => {\n // Skip token handling for certain requests\n if (shouldSkipTokenHandling(url, options)) {\n return next(url, options);\n }\n\n try {\n await refreshSession(auth, storage, marginSeconds);\n } catch {\n // do nothing, we still want to call the next function\n }\n return next(url, options);\n };\n};\n\n/**\n * Determines if token handling should be skipped for this request\n *\n * @param url - Request URL\n * @param options - Request options\n * @returns True if token handling should be skipped, false otherwise\n */\nfunction shouldSkipTokenHandling(url: string, options: RequestInit): boolean {\n const headers = new Headers(options.headers || {});\n\n // If Authorization header is explicitly set, skip token handling\n if (headers.has('Authorization')) {\n return true;\n }\n\n // If calling the token endpoint, skip to avoid infinite loops\n if (url.endsWith('/v1/token')) {\n return true;\n }\n\n return false;\n}\n","/**\n * Session response middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically extract\n * and persist session information from authentication responses, ensuring\n * that new sessions are properly stored after sign-in operations.\n */\n\nimport type { Session, SessionPayload } from '../auth';\nimport type { SessionStorage } from '../session/storage';\nimport type { ChainFunction } from './fetch';\n\n/**\n * Creates a fetch middleware that automatically extracts and stores session data from API responses.\n *\n * This middleware:\n * 1. Monitors responses from authentication-related endpoints\n * 2. Extracts session information when present\n * 3. Stores the session in the provided storage implementation\n * 4. Handles session removal on sign-out\n *\n * This ensures that session data is always up-to-date in storage after operations\n * that create or invalidate sessions.\n *\n * @param storage - Storage implementation for persisting session data\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const updateSessionFromResponseMiddleware = (\n storage: SessionStorage,\n): ChainFunction => {\n /**\n * Helper function to extract session data from various response formats\n *\n * @param body - Response data to extract session from\n * @returns Session object if found, null otherwise\n */\n const sessionExtractor = (\n body: Session | SessionPayload | string,\n ): Session | null => {\n if (typeof body === 'string') {\n return null;\n }\n\n if ('session' in body) {\n // SessionPayload\n return body.session || null;\n }\n\n if ('accessToken' in body && 'refreshToken' in body && 'user' in body) {\n // Session\n return body;\n }\n\n return null;\n };\n\n return (next: (url: string, options?: RequestInit) => Promise<Response>) =>\n async (url: string, options?: RequestInit) => {\n // Call the next middleware in the chain\n const response = await next(url, options);\n\n try {\n // Check if this is a logout request\n if (url.endsWith('/signout')) {\n // Remove session on sign-out\n storage.remove();\n return response;\n }\n\n // Check if this is an auth-related endpoint that might return session data\n if (\n url.endsWith('/token') ||\n url.includes('/token/exchange') ||\n url.includes('/signin/') ||\n url.includes('/signup/')\n ) {\n // Clone the response to avoid consuming it\n const clonedResponse = response.clone();\n\n // Parse the JSON data\n const body = (await clonedResponse.json().catch(() => null)) as\n | Session\n | SessionPayload;\n\n if (body) {\n // Extract session data from response using provided extractor\n const session = sessionExtractor(body);\n\n // If session data is found, store it\n if (session?.accessToken && session.refreshToken) {\n storage.set(session);\n }\n }\n }\n } catch (error) {\n console.warn('Error in session response middleware:', error);\n }\n\n // Return the original response\n return response;\n };\n};\n","/**\n * Admin session middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically attach\n * Hasura admin secret for admin permissions in requests.\n */\n\nimport type { ChainFunction, FetchFunction } from './fetch';\n\n/**\n * Configuration options for admin session middleware\n */\nexport interface AdminSessionOptions {\n /**\n * Hasura admin secret for elevated permissions (sets x-hasura-admin-secret header)\n */\n adminSecret: string;\n\n /**\n * Hasura role to use for the request (sets x-hasura-role header)\n */\n role?: string;\n\n /**\n * Additional Hasura session variables to attach to requests.\n * Keys will be automatically prefixed with 'x-hasura-' if not already present.\n *\n * @example\n * ```ts\n * {\n * 'user-id': '123',\n * 'org-id': '456'\n * }\n * // Results in headers:\n * // x-hasura-user-id: 123\n * // x-hasura-org-id: 456\n * ```\n */\n sessionVariables?: Record<string, string>;\n}\n\n/**\n * Creates a fetch middleware that attaches the Hasura admin secret and optional session variables to requests.\n *\n * This middleware:\n * 1. Sets the x-hasura-admin-secret header, which grants full admin access to Hasura\n * 2. Optionally sets the x-hasura-role header if a role is provided\n * 3. Optionally sets additional x-hasura-* headers for custom session variables\n *\n * **Security Warning**: Never use this middleware in client-side code or expose\n * the admin secret to end users. Admin secrets grant unrestricted access to your\n * entire database. This should only be used in trusted server-side environments.\n *\n * The middleware preserves request-specific headers when they conflict with the\n * admin session configuration.\n *\n * @param options - Admin session options including admin secret, role, and session variables\n * @returns A middleware function that can be used in the fetch chain\n *\n * @example\n * ```ts\n * // Create middleware with admin secret only\n * const adminMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET\n * });\n *\n * // Create middleware with admin secret and role\n * const adminUserMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET,\n * role: 'user'\n * });\n *\n * // Create middleware with admin secret, role, and custom session variables\n * const fullMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET,\n * role: 'user',\n * sessionVariables: {\n * 'user-id': '123',\n * 'org-id': '456'\n * }\n * });\n *\n * // Use with createCustomClient for an admin client\n * const adminClient = createCustomClient({\n * subdomain: 'myproject',\n * region: 'eu-central-1',\n * chainFunctions: [adminMiddleware]\n * });\n * ```\n */\nexport const withAdminSessionMiddleware =\n (options: AdminSessionOptions): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, requestOptions: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(requestOptions.headers || {});\n\n // Set x-hasura-admin-secret if not already present\n if (!headers.has('x-hasura-admin-secret')) {\n headers.set('x-hasura-admin-secret', options.adminSecret);\n }\n\n // Set x-hasura-role if provided and not already present\n if (options.role && !headers.has('x-hasura-role')) {\n headers.set('x-hasura-role', options.role);\n }\n\n // Set custom session variables\n if (options.sessionVariables) {\n for (const [key, value] of Object.entries(options.sessionVariables)) {\n // Ensure the key has the x-hasura- prefix\n const headerKey = key.startsWith('x-hasura-') ? key : `x-hasura-${key}`;\n\n // Only set if not already present in the request\n if (!headers.has(headerKey)) {\n headers.set(headerKey, value);\n }\n }\n }\n\n return next(url, { ...requestOptions, headers });\n };\n"],"names":["options"],"mappings":";AAyBO,MAAM,8BACX,CAAC,YACD,CAAC,SACD,OAAO,KAAa,UAAuB,OAA0B;AACnE,QAAM,UAAU,IAAI,QAAQ,QAAQ,WAAW,CAAA,CAAE;AAGjD,MAAI,QAAQ,IAAI,eAAe,GAAG;AAChC,WAAO,KAAK,KAAK,OAAO;AAAA,EAC1B;AAGA,QAAM,UAAU,QAAQ,IAAA;AAExB,MAAI,SAAS,aAAa;AAExB,UAAM,aAAa;AAAA,MACjB,GAAG;AAAA,MACH,SAAS,uBAAuB,SAAS,OAAO;AAAA,IAAA;AAIlD,WAAO,KAAK,KAAK,UAAU;AAA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ization",`Bearer ${s.accessToken}`),e}exports.attachAccessTokenMiddleware=e=>n=>async(r,t={})=>{const a=new Headers(t.headers||{});if(a.has("Authorization"))return n(r,t);const i=e.get();if(i?.accessToken){const e={...t,headers:s(a,i)};return n(r,e)}return n(r,t)},exports.sessionRefreshMiddleware=(s,n,r)=>{const{marginSeconds:t=60}=r||{};return r=>async(a,i={})=>{if(function(e,s){const n=new Headers(s.headers||{});if(n.has("Authorization"))return!0;if(e.endsWith("/v1/token"))return!0;return!1}(a,i))return r(a,i);try{await e.refreshSession(s,n,t)}catch{}return r(a,i)}},exports.updateSessionFromResponseMiddleware=e=>s=>async(n,r)=>{const t=await s(n,r);try{if(n.endsWith("/signout"))return e.remove(),t;if(n.endsWith("/token")||n.includes("/token/exchange")||n.includes("/signin/")||n.includes("/signup/")){const s=t.clone(),n=await s.json().catch((()=>null));if(n){const s=(e=>"string"==typeof e?null:"session"in e?e.session||null:"accessToken"in e&&"refreshToken"in e&&"user"in e?e:null)(n);s?.accessToken&&s.refreshToken&&e.set(s)}}}catch(a){console.warn("Error in session response middleware:",a)}return t},exports.withAdminSessionMiddleware=e=>s=>async(n,r={})=>{const t=new Headers(r.headers||{});if(t.has("x-hasura-admin-secret")||t.set("x-hasura-admin-secret",e.adminSecret),e.role&&!t.has("x-hasura-role")&&t.set("x-hasura-role",e.role),e.sessionVariables)for(const[s,a]of Object.entries(e.sessionVariables)){const e=s.startsWith("x-hasura-")?s:`x-hasura-${s}`;t.has(e)||t.set(e,a)}return s(n,{...r,headers:t})};
|
|
2
|
-
//# sourceMappingURL=middlewareWithAdminSession-j70iKbBX.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"middlewareWithAdminSession-j70iKbBX.cjs","sources":["../src/fetch/middlewareAttachAccessToken.ts","../src/fetch/middlewareSessionRefresh.ts","../src/fetch/middlewareUpdateSessionFromResponse.ts","../src/fetch/middlewareWithAdminSession.ts"],"sourcesContent":["/**\n * Authorization token attachment middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically attach\n * authorization tokens to outgoing API requests, ensuring the client\n * is properly authenticated.\n */\n\nimport type { Session } from '../auth';\nimport type { SessionStorage } from '../session/storage';\nimport type { ChainFunction, FetchFunction } from './fetch';\n\n/**\n * Creates a fetch middleware that adds the Authorization header with the current access token.\n *\n * This middleware:\n * 1. Gets the current session from storage\n * 2. Adds the authorization header with the access token to outgoing requests\n *\n * This middleware should be used after the refresh middleware in the chain to\n * ensure the most recent token is used.\n *\n * @param storage - Storage implementation for retrieving session data\n * @returns A middleware function that adds Authorization headers\n */\nexport const attachAccessTokenMiddleware =\n (storage: SessionStorage): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(options.headers || {});\n\n // Skip if Authorization header is already set\n if (headers.has('Authorization')) {\n return next(url, options);\n }\n\n // Get current session from storage\n const session = storage.get();\n\n if (session?.accessToken) {\n // Add authorization header\n const newOptions = {\n ...options,\n headers: addAuthorizationHeader(headers, session),\n };\n\n // Continue with the fetch chain\n return next(url, newOptions);\n }\n\n // No session or no access token, continue without authorization\n return next(url, options);\n };\n\n/**\n * Adds the Authorization header with the access token to the request headers\n *\n * @param headers - Original request headers\n * @param session - Current session containing the access token\n * @returns Modified headers with Authorization header\n */\nfunction addAuthorizationHeader(headers: Headers, session: Session): Headers {\n if (session.accessToken) {\n headers.set('Authorization', `Bearer ${session.accessToken}`);\n }\n return headers;\n}\n","/**\n * Auth token refresh middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically refresh\n * authentication tokens before they expire, ensuring seamless API access\n * without requiring manual token refresh by the application.\n */\n\nimport type { Client } from '../auth';\nimport { refreshSession } from '../session/refreshSession';\nimport type { SessionStorage } from '../session/storage';\nimport type { ChainFunction, FetchFunction } from './fetch';\n\n/**\n * Creates a fetch middleware that automatically refreshes authentication tokens.\n *\n * This middleware:\n * 1. Checks if the current token is about to expire\n * 2. If so, uses the refresh token to obtain a new access token\n *\n * The middleware handles token refresh transparently, so the application\n * doesn't need to manually refresh tokens.\n *\n * @param auth - Auth API client for token refresh operations\n * @param storage - Storage implementation for persisting session data\n * @param options - Configuration options for token refresh behavior\n * @param options.marginSeconds - Number of seconds before token expiration to trigger a refresh, default is 60 seconds\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const sessionRefreshMiddleware = (\n auth: Client,\n storage: SessionStorage,\n options?: {\n marginSeconds?: number;\n },\n): ChainFunction => {\n const { marginSeconds = 60 } = options || {};\n\n // Create and return the chain function\n return (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): Promise<Response> => {\n // Skip token handling for certain requests\n if (shouldSkipTokenHandling(url, options)) {\n return next(url, options);\n }\n\n try {\n await refreshSession(auth, storage, marginSeconds);\n } catch {\n // do nothing, we still want to call the next function\n }\n return next(url, options);\n };\n};\n\n/**\n * Determines if token handling should be skipped for this request\n *\n * @param url - Request URL\n * @param options - Request options\n * @returns True if token handling should be skipped, false otherwise\n */\nfunction shouldSkipTokenHandling(url: string, options: RequestInit): boolean {\n const headers = new Headers(options.headers || {});\n\n // If Authorization header is explicitly set, skip token handling\n if (headers.has('Authorization')) {\n return true;\n }\n\n // If calling the token endpoint, skip to avoid infinite loops\n if (url.endsWith('/v1/token')) {\n return true;\n }\n\n return false;\n}\n","/**\n * Session response middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically extract\n * and persist session information from authentication responses, ensuring\n * that new sessions are properly stored after sign-in operations.\n */\n\nimport type { Session, SessionPayload } from '../auth';\nimport type { SessionStorage } from '../session/storage';\nimport type { ChainFunction } from './fetch';\n\n/**\n * Creates a fetch middleware that automatically extracts and stores session data from API responses.\n *\n * This middleware:\n * 1. Monitors responses from authentication-related endpoints\n * 2. Extracts session information when present\n * 3. Stores the session in the provided storage implementation\n * 4. Handles session removal on sign-out\n *\n * This ensures that session data is always up-to-date in storage after operations\n * that create or invalidate sessions.\n *\n * @param storage - Storage implementation for persisting session data\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const updateSessionFromResponseMiddleware = (\n storage: SessionStorage,\n): ChainFunction => {\n /**\n * Helper function to extract session data from various response formats\n *\n * @param body - Response data to extract session from\n * @returns Session object if found, null otherwise\n */\n const sessionExtractor = (\n body: Session | SessionPayload | string,\n ): Session | null => {\n if (typeof body === 'string') {\n return null;\n }\n\n if ('session' in body) {\n // SessionPayload\n return body.session || null;\n }\n\n if ('accessToken' in body && 'refreshToken' in body && 'user' in body) {\n // Session\n return body;\n }\n\n return null;\n };\n\n return (next: (url: string, options?: RequestInit) => Promise<Response>) =>\n async (url: string, options?: RequestInit) => {\n // Call the next middleware in the chain\n const response = await next(url, options);\n\n try {\n // Check if this is a logout request\n if (url.endsWith('/signout')) {\n // Remove session on sign-out\n storage.remove();\n return response;\n }\n\n // Check if this is an auth-related endpoint that might return session data\n if (\n url.endsWith('/token') ||\n url.includes('/token/exchange') ||\n url.includes('/signin/') ||\n url.includes('/signup/')\n ) {\n // Clone the response to avoid consuming it\n const clonedResponse = response.clone();\n\n // Parse the JSON data\n const body = (await clonedResponse.json().catch(() => null)) as\n | Session\n | SessionPayload;\n\n if (body) {\n // Extract session data from response using provided extractor\n const session = sessionExtractor(body);\n\n // If session data is found, store it\n if (session?.accessToken && session.refreshToken) {\n storage.set(session);\n }\n }\n }\n } catch (error) {\n console.warn('Error in session response middleware:', error);\n }\n\n // Return the original response\n return response;\n };\n};\n","/**\n * Admin session middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically attach\n * Hasura admin secret for admin permissions in requests.\n */\n\nimport type { ChainFunction, FetchFunction } from './fetch';\n\n/**\n * Configuration options for admin session middleware\n */\nexport interface AdminSessionOptions {\n /**\n * Hasura admin secret for elevated permissions (sets x-hasura-admin-secret header)\n */\n adminSecret: string;\n\n /**\n * Hasura role to use for the request (sets x-hasura-role header)\n */\n role?: string;\n\n /**\n * Additional Hasura session variables to attach to requests.\n * Keys will be automatically prefixed with 'x-hasura-' if not already present.\n *\n * @example\n * ```ts\n * {\n * 'user-id': '123',\n * 'org-id': '456'\n * }\n * // Results in headers:\n * // x-hasura-user-id: 123\n * // x-hasura-org-id: 456\n * ```\n */\n sessionVariables?: Record<string, string>;\n}\n\n/**\n * Creates a fetch middleware that attaches the Hasura admin secret and optional session variables to requests.\n *\n * This middleware:\n * 1. Sets the x-hasura-admin-secret header, which grants full admin access to Hasura\n * 2. Optionally sets the x-hasura-role header if a role is provided\n * 3. Optionally sets additional x-hasura-* headers for custom session variables\n *\n * **Security Warning**: Never use this middleware in client-side code or expose\n * the admin secret to end users. Admin secrets grant unrestricted access to your\n * entire database. This should only be used in trusted server-side environments.\n *\n * The middleware preserves request-specific headers when they conflict with the\n * admin session configuration.\n *\n * @param options - Admin session options including admin secret, role, and session variables\n * @returns A middleware function that can be used in the fetch chain\n *\n * @example\n * ```ts\n * // Create middleware with admin secret only\n * const adminMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET\n * });\n *\n * // Create middleware with admin secret and role\n * const adminUserMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET,\n * role: 'user'\n * });\n *\n * // Create middleware with admin secret, role, and custom session variables\n * const fullMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET,\n * role: 'user',\n * sessionVariables: {\n * 'user-id': '123',\n * 'org-id': '456'\n * }\n * });\n *\n * // Use with createCustomClient for an admin client\n * const adminClient = createCustomClient({\n * subdomain: 'myproject',\n * region: 'eu-central-1',\n * chainFunctions: [adminMiddleware]\n * });\n * ```\n */\nexport const withAdminSessionMiddleware =\n (options: AdminSessionOptions): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, requestOptions: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(requestOptions.headers || {});\n\n // Set x-hasura-admin-secret if not already present\n if (!headers.has('x-hasura-admin-secret')) {\n headers.set('x-hasura-admin-secret', options.adminSecret);\n }\n\n // Set x-hasura-role if provided and not already present\n if (options.role && !headers.has('x-hasura-role')) {\n headers.set('x-hasura-role', options.role);\n }\n\n // Set custom session variables\n if (options.sessionVariables) {\n for (const [key, value] of Object.entries(options.sessionVariables)) {\n // Ensure the key has the x-hasura- prefix\n const headerKey = key.startsWith('x-hasura-') ? key : `x-hasura-${key}`;\n\n // Only set if not already present in the request\n if (!headers.has(headerKey)) {\n headers.set(headerKey, value);\n }\n }\n }\n\n return next(url, { ...requestOptions, headers });\n };\n"],"names":["addAuthorizationHeader","headers","session","accessToken","set","storage","next","async","url","options","Headers","has","get","newOptions","auth","marginSeconds","endsWith","shouldSkipTokenHandling","refreshSession","response","remove","includes","clonedResponse","clone","body","json","catch","sessionExtractor","refreshToken","error","console","warn","requestOptions","adminSecret","role","sessionVariables","key","value","Object","entries","headerKey","startsWith"],"mappings":"8DA6DA,SAASA,EAAuBC,EAAkBC,GAIhD,OAHIA,EAAQC,aACVF,EAAQG,IAAI,gBAAiB,UAAUF,EAAQC,eAE1CF,CACT,qCAxCGI,GACAC,GACDC,MAAOC,EAAaC,EAAuB,MACzC,MAAMR,EAAU,IAAIS,QAAQD,EAAQR,SAAW,CAAA,GAG/C,GAAIA,EAAQU,IAAI,iBACd,OAAOL,EAAKE,EAAKC,GAInB,MAAMP,EAAUG,EAAQO,MAExB,GAAIV,GAASC,YAAa,CAExB,MAAMU,EAAa,IACdJ,EACHR,QAASD,EAAuBC,EAASC,IAI3C,OAAOI,EAAKE,EAAKK,EACnB,CAGA,OAAOP,EAAKE,EAAKC,EAAO,mCCtBY,CACtCK,EACAT,EACAI,KAIA,MAAMM,cAAEA,EAAgB,IAAON,GAAW,CAAA,EAG1C,OAAQH,GACNC,MAAOC,EAAaC,EAAuB,CAAA,KAEzC,GAoBN,SAAiCD,EAAaC,GAC5C,MAAMR,EAAU,IAAIS,QAAQD,EAAQR,SAAW,CAAA,GAG/C,GAAIA,EAAQU,IAAI,iBACd,OAAO,EAIT,GAAIH,EAAIQ,SAAS,aACf,OA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,OAAO/B,EAAKE,EAAK,IAAKwB,EAAgB/B,WAAS"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.cjs","sources":["../../src/fetch/middlewareWithHeaders.ts","../../src/fetch/middlewareWithRole.ts"],"sourcesContent":["/**\n * Headers middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically attach\n * default headers to all outgoing requests, while allowing request-specific\n * headers to take precedence.\n */\n\nimport type { ChainFunction, FetchFunction } from './fetch';\n\n/**\n * Creates a fetch middleware that attaches default headers to requests.\n *\n * This middleware:\n * 1. Merges default headers with request-specific headers\n * 2. Preserves request-specific headers when they conflict with defaults\n *\n * The middleware ensures consistent headers across requests while allowing\n * individual requests to override defaults as needed.\n *\n * @param defaultHeaders - Default headers to attach to all requests\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const withHeadersMiddleware =\n (defaultHeaders: HeadersInit): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(options.headers || {});\n const defaults = new Headers(defaultHeaders);\n\n defaults.forEach((value, key) => {\n if (!headers.has(key)) {\n headers.set(key, value);\n }\n });\n\n return next(url, { ...options, headers });\n };\n","/**\n * Role middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically set\n * the Hasura role for all requests. This is useful when you want to\n * make requests as a specific role without using the admin secret.\n */\n\nimport type { ChainFunction, FetchFunction } from './fetch';\n\n/**\n * Creates a fetch middleware that sets the Hasura role header.\n *\n * This middleware sets the x-hasura-role header for all requests, allowing\n * you to specify which role's permissions should be used. This works with\n * authenticated sessions where the user has access to the specified role.\n *\n * Unlike `withAdminSessionMiddleware`, this does not bypass permission rules\n * but instead uses the permission rules defined for the specified role.\n *\n * The middleware preserves request-specific headers when they conflict with\n * the role configuration.\n *\n * @param role - The Hasura role to use for requests\n * @returns A middleware function that can be used in the fetch chain\n *\n * @example\n * ```ts\n * // Use with createClient to default all requests to a specific role\n * const nhost = createClient({\n * subdomain: 'myproject',\n * region: 'eu-central-1',\n * chainFunctions: [withRoleMiddleware('moderator')]\n * });\n *\n * // Use with createServerClient for server-side requests\n * const serverNhost = createServerClient({\n * subdomain: 'myproject',\n * region: 'eu-central-1',\n * storage: myServerStorage,\n * chainFunctions: [withRoleMiddleware('moderator')]\n * });\n * ```\n */\nexport const withRoleMiddleware =\n (role: string): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, requestOptions: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(requestOptions.headers || {});\n\n // Set x-hasura-role if not already present\n if (!headers.has('x-hasura-role')) {\n headers.set('x-hasura-role', role);\n }\n\n return next(url, { ...requestOptions, headers });\n };\n"],"names":["defaultHeaders","next","async","url","options","headers","Headers","forEach","value","key","has","set","role","requestOptions"],"mappings":"ijBAwBGA,GACAC,GACDC,MAAOC,EAAaC,EAAuB,MACzC,MAAMC,EAAU,IAAIC,QAAQF,EAAQC,SAAW,CAAA,GAS/C,OARiB,IAAIC,QAAQN,GAEpBO,SAAQ,CAACC,EAAOC,KAClBJ,EAAQK,IAAID,IACfJ,EAAQM,IAAIF,EAAKD,EACnB,IAGKP,EAAKE,EAAK,IAAKC,EAASC,WAAS,6BCSzCO,GACAX,GACDC,MAAOC,EAAaU,EAA8B,MAChD,MAAMR,EAAU,IAAIC,QAAQO,EAAeR,SAAW,CAAA,GAOtD,OAJKA,EAAQK,IAAI,kBACfL,EAAQM,IAAI,gBAAiBC,GAGxBX,EAAKE,EAAK,IAAKU,EAAgBR,WAAS"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.js","sources":["../../src/fetch/middlewareWithHeaders.ts","../../src/fetch/middlewareWithRole.ts"],"sourcesContent":["/**\n * Headers middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically attach\n * default headers to all outgoing requests, while allowing request-specific\n * headers to take precedence.\n */\n\nimport type { ChainFunction, FetchFunction } from './fetch';\n\n/**\n * Creates a fetch middleware that attaches default headers to requests.\n *\n * This middleware:\n * 1. Merges default headers with request-specific headers\n * 2. Preserves request-specific headers when they conflict with defaults\n *\n * The middleware ensures consistent headers across requests while allowing\n * individual requests to override defaults as needed.\n *\n * @param defaultHeaders - Default headers to attach to all requests\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const withHeadersMiddleware =\n (defaultHeaders: HeadersInit): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(options.headers || {});\n const defaults = new Headers(defaultHeaders);\n\n defaults.forEach((value, key) => {\n if (!headers.has(key)) {\n headers.set(key, value);\n }\n });\n\n return next(url, { ...options, headers });\n };\n","/**\n * Role middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically set\n * the Hasura role for all requests. This is useful when you want to\n * make requests as a specific role without using the admin secret.\n */\n\nimport type { ChainFunction, FetchFunction } from './fetch';\n\n/**\n * Creates a fetch middleware that sets the Hasura role header.\n *\n * This middleware sets the x-hasura-role header for all requests, allowing\n * you to specify which role's permissions should be used. This works with\n * authenticated sessions where the user has access to the specified role.\n *\n * Unlike `withAdminSessionMiddleware`, this does not bypass permission rules\n * but instead uses the permission rules defined for the specified role.\n *\n * The middleware preserves request-specific headers when they conflict with\n * the role configuration.\n *\n * @param role - The Hasura role to use for requests\n * @returns A middleware function that can be used in the fetch chain\n *\n * @example\n * ```ts\n * // Use with createClient to default all requests to a specific role\n * const nhost = createClient({\n * subdomain: 'myproject',\n * region: 'eu-central-1',\n * chainFunctions: [withRoleMiddleware('moderator')]\n * });\n *\n * // Use with createServerClient for server-side requests\n * const serverNhost = createServerClient({\n * subdomain: 'myproject',\n * region: 'eu-central-1',\n * storage: myServerStorage,\n * chainFunctions: [withRoleMiddleware('moderator')]\n * });\n * ```\n */\nexport const withRoleMiddleware =\n (role: string): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, requestOptions: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(requestOptions.headers || {});\n\n // Set x-hasura-role if not already present\n if (!headers.has('x-hasura-role')) {\n headers.set('x-hasura-role', role);\n }\n\n return next(url, { ...requestOptions, headers });\n };\n"],"names":[],"mappings":";;AAuBO,MAAM,wBACX,CAAC,mBACD,CAAC,SACD,OAAO,KAAa,UAAuB,OAA0B;AACnE,QAAM,UAAU,IAAI,QAAQ,QAAQ,WAAW,CAAA,CAAE;AACjD,QAAM,WAAW,IAAI,QAAQ,cAAc;AAE3C,WAAS,QAAQ,CAAC,OAAO,QAAQ;AAC/B,QAAI,CAAC,QAAQ,IAAI,GAAG,GAAG;AACrB,cAAQ,IAAI,KAAK,KAAK;AAAA,IACxB;AAAA,EACF,CAAC;AAED,SAAO,KAAK,KAAK,EAAE,GAAG,SAAS,SAAS;AAC1C;ACOK,MAAM,qBACX,CAAC,SACD,CAAC,SACD,OAAO,KAAa,iBAA8B,OAA0B;AAC1E,QAAM,UAAU,IAAI,QAAQ,eAAe,WAAW,CAAA,CAAE;AAGxD,MAAI,CAAC,QAAQ,IAAI,eAAe,GAAG;AACjC,YAAQ,IAAI,iBAAiB,IAAI;AAAA,EACnC;AAEA,SAAO,KAAK,KAAK,EAAE,GAAG,gBAAgB,SAAS;AACjD;"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"graphql.cjs","sources":["../../src/graphql/client.ts"],"sourcesContent":["/**\n * GraphQL client for the Nhost JavaScript SDK.\n *\n * This module provides functionality for executing GraphQL operations against\n * a Hasura GraphQL API.\n */\n\nimport type { TypedDocumentNode } from '@graphql-typed-document-node/core';\nimport {\n type ChainFunction,\n createEnhancedFetch,\n FetchError,\n type FetchResponse,\n} from '../fetch';\n\n/**\n * Variables object for GraphQL operations.\n * Key-value pairs of variable names and their values.\n */\nexport type GraphQLVariables = Record<string, unknown>;\n\n/**\n * GraphQL request object used for queries and mutations.\n */\nexport interface GraphQLRequest<TVariables = GraphQLVariables> {\n /** The GraphQL query or mutation string */\n query: string;\n /** Optional variables for parameterized queries */\n variables?: TVariables;\n /** Optional name of the operation to execute */\n operationName?: string;\n}\n\n/**\n * Represents a GraphQL error returned from the server.\n */\nexport interface GraphQLError {\n /** Error message */\n message: string;\n /** Source locations in the GraphQL document where the error occurred */\n locations?: { line: number; column: number }[];\n /** Path in the query where the error occurred */\n path?: string[];\n /** Additional error information specific to the GraphQL implementation */\n extensions?: { path: string; code: string };\n}\n\n/**\n * Standard GraphQL response format as defined by the GraphQL specification.\n */\nexport interface GraphQLResponse<TResponseData = unknown> {\n /** The data returned from successful execution */\n data?: TResponseData;\n /** Array of errors if execution was unsuccessful or partially successful */\n errors?: GraphQLError[];\n}\n\n/**\n * GraphQL client interface providing methods for executing queries and mutations\n */\nexport interface Client {\n /**\n * Execute a GraphQL query operation\n *\n * Queries are used to fetch data and should not modify any data on the server.\n *\n * @param request - GraphQL request object containing query and optional variables\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the GraphQL response and metadata\n */\n request<TResponseData = unknown, TVariables = GraphQLVariables>(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n\n /**\n * Execute a GraphQL query operation using a typed document node\n *\n * @param document - TypedDocumentNode containing the query and type information\n * @param variables - Variables for the GraphQL operation\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the GraphQL response and metadata\n */\n request<TResponseData, TVariables = GraphQLVariables>(\n document: TypedDocumentNode<TResponseData, TVariables>,\n variables?: TVariables,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n\n /**\n * URL for the GraphQL endpoint.\n */\n url: string;\n\n /** Add a middleware function to the fetch chain\n * @param chainFunction - The middleware function to add\n */\n pushChainFunction(chainFunction: ChainFunction): void;\n}\n\n/**\n * Creates a GraphQL API client for interacting with a GraphQL endpoint.\n *\n * This client provides methods for executing queries and mutations against\n * a GraphQL API, with support for middleware functions to handle authentication,\n * error handling, and other cross-cutting concerns.\n *\n * @param url - Base URL for the GraphQL endpoint\n * @param chainFunctions - Array of middleware functions for the fetch chain\n * @returns GraphQL client with query and mutation methods\n */\nexport const createAPIClient = (\n url: string,\n chainFunctions: ChainFunction[] = [],\n): Client => {\n let enhancedFetch = createEnhancedFetch(chainFunctions);\n\n const pushChainFunction = (chainFunction: ChainFunction) => {\n chainFunctions.push(chainFunction);\n enhancedFetch = createEnhancedFetch(chainFunctions);\n };\n\n const executeOperation = async <\n TResponseData = unknown,\n TVariables = GraphQLVariables,\n >(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>> => {\n const response = await enhancedFetch(`${url}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(request),\n ...options,\n });\n\n const body = await response.text();\n const data: GraphQLResponse<TResponseData> = (\n body ? JSON.parse(body) : {}\n ) as GraphQLResponse<TResponseData>;\n\n const resp = {\n body: data,\n status: response.status,\n headers: response.headers,\n };\n\n if (data.errors) {\n throw new FetchError(data, response.status, response.headers);\n }\n\n return resp;\n };\n\n function request<TResponseData = unknown, TVariables = GraphQLVariables>(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n function request<TResponseData, TVariables = GraphQLVariables>(\n document: TypedDocumentNode<TResponseData, TVariables>,\n variables?: TVariables,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n function request<TResponseData, TVariables = GraphQLVariables>(\n requestOrDocument:\n | GraphQLRequest<TVariables>\n | TypedDocumentNode<TResponseData, TVariables>,\n variablesOrOptions?: TVariables | RequestInit,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>> {\n if (typeof requestOrDocument === 'object' && 'kind' in requestOrDocument) {\n const definition = requestOrDocument.definitions[0];\n\n const request: GraphQLRequest<TVariables> = {\n query: requestOrDocument.loc?.source.body || '',\n variables: variablesOrOptions as TVariables,\n operationName:\n definition && 'name' in definition\n ? definition.name?.value\n : undefined,\n };\n return executeOperation(request, options);\n } else {\n // Handle GraphQLRequest\n const request = requestOrDocument;\n const requestOptions = variablesOrOptions as RequestInit;\n return executeOperation(request, requestOptions);\n }\n }\n\n return {\n request,\n url,\n pushChainFunction,\n } as Client;\n};\n"],"names":["url","chainFunctions","enhancedFetch","createEnhancedFetch","executeOperation","async","request","options","response","method","headers","body","JSON","stringify","text","data","parse","resp","status","errors","FetchError","requestOrDocument","variablesOrOptions","definition","definitions","query","loc","source","variables","operationName","name","value","pushChainFunction","chainFunction","push"],"mappings":"iJA+G+B,CAC7BA,EACAC,EAAkC,MAElC,IAAIC,EAAgBC,EAAAA,oBAAoBF,GAExC,MAKMG,EAAmBC,MAIvBC,EACAC,KAEA,MAAMC,QAAiBN,EAAc,GAAGF,IAAO,CAC7CS,OAAQ,OACRC,QAAS,CACP,eAAgB,oBAElBC,KAAMC,KAAKC,UAAUP,MAClBC,IAGCI,QAAaH,EAASM,OACtBC,EACJJ,EAAOC,KAAKI,MAAML,GAAQ,CAAA,EAGtBM,EAAO,CACXN,KAAMI,EACNG,OAAQV,EAASU,OACjBR,QAASF,EAASE,SAGpB,GAAIK,EAAKI,OACP,MAAM,IAAIC,EAAAA,WAAWL,EAAMP,EAASU,OAAQV,EAASE,SAGvD,OAAOO,CAAA,EAuCT,MAAO,CACLX,QA5BF,SACEe,EAGAC,EACAf,GAEA,GAAiC,iBAAtBc,GAAkC,SAAUA,EAAmB,CACxE,MAAME,EAAaF,EAAkBG,YAAY,GAE3ClB,EAAsC,CAC1CmB,MAAOJ,EAAkBK,KAAKC,OAAOhB,MAAQ,GAC7CiB,UAAWN,EACXO,cACEN,GAAc,SAAUA,EACpBA,EAAWO,MAAMC,WACjB,GAER,OAAO3B,EAAiBE,EAASC,EACnC,CAIE,OAAOH,EAFSiB,EACOC,EAG3B,EAIEtB,MACAgC,kBA9EyBC,IACzBhC,EAAeiC,KAAKD,GACpB/B,EAAgBC,EAAAA,oBAAoBF,EAAc,EA4ElD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"graphql.js","sources":["../../src/graphql/client.ts"],"sourcesContent":["/**\n * GraphQL client for the Nhost JavaScript SDK.\n *\n * This module provides functionality for executing GraphQL operations against\n * a Hasura GraphQL API.\n */\n\nimport type { TypedDocumentNode } from '@graphql-typed-document-node/core';\nimport {\n type ChainFunction,\n createEnhancedFetch,\n FetchError,\n type FetchResponse,\n} from '../fetch';\n\n/**\n * Variables object for GraphQL operations.\n * Key-value pairs of variable names and their values.\n */\nexport type GraphQLVariables = Record<string, unknown>;\n\n/**\n * GraphQL request object used for queries and mutations.\n */\nexport interface GraphQLRequest<TVariables = GraphQLVariables> {\n /** The GraphQL query or mutation string */\n query: string;\n /** Optional variables for parameterized queries */\n variables?: TVariables;\n /** Optional name of the operation to execute */\n operationName?: string;\n}\n\n/**\n * Represents a GraphQL error returned from the server.\n */\nexport interface GraphQLError {\n /** Error message */\n message: string;\n /** Source locations in the GraphQL document where the error occurred */\n locations?: { line: number; column: number }[];\n /** Path in the query where the error occurred */\n path?: string[];\n /** Additional error information specific to the GraphQL implementation */\n extensions?: { path: string; code: string };\n}\n\n/**\n * Standard GraphQL response format as defined by the GraphQL specification.\n */\nexport interface GraphQLResponse<TResponseData = unknown> {\n /** The data returned from successful execution */\n data?: TResponseData;\n /** Array of errors if execution was unsuccessful or partially successful */\n errors?: GraphQLError[];\n}\n\n/**\n * GraphQL client interface providing methods for executing queries and mutations\n */\nexport interface Client {\n /**\n * Execute a GraphQL query operation\n *\n * Queries are used to fetch data and should not modify any data on the server.\n *\n * @param request - GraphQL request object containing query and optional variables\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the GraphQL response and metadata\n */\n request<TResponseData = unknown, TVariables = GraphQLVariables>(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n\n /**\n * Execute a GraphQL query operation using a typed document node\n *\n * @param document - TypedDocumentNode containing the query and type information\n * @param variables - Variables for the GraphQL operation\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the GraphQL response and metadata\n */\n request<TResponseData, TVariables = GraphQLVariables>(\n document: TypedDocumentNode<TResponseData, TVariables>,\n variables?: TVariables,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n\n /**\n * URL for the GraphQL endpoint.\n */\n url: string;\n\n /** Add a middleware function to the fetch chain\n * @param chainFunction - The middleware function to add\n */\n pushChainFunction(chainFunction: ChainFunction): void;\n}\n\n/**\n * Creates a GraphQL API client for interacting with a GraphQL endpoint.\n *\n * This client provides methods for executing queries and mutations against\n * a GraphQL API, with support for middleware functions to handle authentication,\n * error handling, and other cross-cutting concerns.\n *\n * @param url - Base URL for the GraphQL endpoint\n * @param chainFunctions - Array of middleware functions for the fetch chain\n * @returns GraphQL client with query and mutation methods\n */\nexport const createAPIClient = (\n url: string,\n chainFunctions: ChainFunction[] = [],\n): Client => {\n let enhancedFetch = createEnhancedFetch(chainFunctions);\n\n const pushChainFunction = (chainFunction: ChainFunction) => {\n chainFunctions.push(chainFunction);\n enhancedFetch = createEnhancedFetch(chainFunctions);\n };\n\n const executeOperation = async <\n TResponseData = unknown,\n TVariables = GraphQLVariables,\n >(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>> => {\n const response = await enhancedFetch(`${url}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(request),\n ...options,\n });\n\n const body = await response.text();\n const data: GraphQLResponse<TResponseData> = (\n body ? JSON.parse(body) : {}\n ) as GraphQLResponse<TResponseData>;\n\n const resp = {\n body: data,\n status: response.status,\n headers: response.headers,\n };\n\n if (data.errors) {\n throw new FetchError(data, response.status, response.headers);\n }\n\n return resp;\n };\n\n function request<TResponseData = unknown, TVariables = GraphQLVariables>(\n request: GraphQLRequest<TVariables>,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n function request<TResponseData, TVariables = GraphQLVariables>(\n document: TypedDocumentNode<TResponseData, TVariables>,\n variables?: TVariables,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>>;\n function request<TResponseData, TVariables = GraphQLVariables>(\n requestOrDocument:\n | GraphQLRequest<TVariables>\n | TypedDocumentNode<TResponseData, TVariables>,\n variablesOrOptions?: TVariables | RequestInit,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse<TResponseData>>> {\n if (typeof requestOrDocument === 'object' && 'kind' in requestOrDocument) {\n const definition = requestOrDocument.definitions[0];\n\n const request: GraphQLRequest<TVariables> = {\n query: requestOrDocument.loc?.source.body || '',\n variables: variablesOrOptions as TVariables,\n operationName:\n definition && 'name' in definition\n ? definition.name?.value\n : undefined,\n };\n return executeOperation(request, options);\n } else {\n // Handle GraphQLRequest\n const request = requestOrDocument;\n const requestOptions = variablesOrOptions as RequestInit;\n return executeOperation(request, requestOptions);\n }\n }\n\n return {\n request,\n url,\n pushChainFunction,\n } as Client;\n};\n"],"names":["request"],"mappings":";AA+GO,MAAM,kBAAkB,CAC7B,KACA,iBAAkC,OACvB;AACX,MAAI,gBAAgB,oBAAoB,cAAc;AAEtD,QAAM,oBAAoB,CAAC,kBAAiC;AAC1D,mBAAe,KAAK,aAAa;AACjC,oBAAgB,oBAAoB,cAAc;AAAA,EACpD;AAEA,QAAM,mBAAmB,OAIvBA,UACA,YAC2D;AAC3D,UAAM,WAAW,MAAM,cAAc,GAAG,GAAG,IAAI;AAAA,MAC7C,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,MAAA;AAAA,MAElB,MAAM,KAAK,UAAUA,QAAO;AAAA,MAC5B,GAAG;AAAA,IAAA,CACJ;AAED,UAAM,OAAO,MAAM,SAAS,KAAA;AAC5B,UAAM,OACJ,OAAO,KAAK,MAAM,IAAI,IAAI,CAAA;AAG5B,UAAM,OAAO;AAAA,MACX,MAAM;AAAA,MACN,QAAQ,SAAS;AAAA,MACjB,SAAS,SAAS;AAAA,IAAA;AAGpB,QAAI,KAAK,QAAQ;AACf,YAAM,IAAI,WAAW,MAAM,SAAS,QAAQ,SAAS,OAAO;AAAA,IAC9D;AAEA,WAAO;AAAA,EACT;AAWA,WAAS,QACP,mBAGA,oBACA,SACwD;AACxD,QAAI,OAAO,sBAAsB,YAAY,UAAU,mBAAmB;AACxE,YAAM,aAAa,kBAAkB,YAAY,CAAC;AAElD,YAAMA,WAAsC;AAAA,QAC1C,OAAO,kBAAkB,KAAK,OAAO,QAAQ;AAAA,QAC7C,WAAW;AAAA,QACX,eACE,cAAc,UAAU,aACpB,WAAW,MAAM,QACjB;AAAA,MAAA;AAER,aAAO,iBAAiBA,UAAS,OAAO;AAAA,IAC1C,OAAO;AAEL,YAAMA,WAAU;AAChB,YAAM,iBAAiB;AACvB,aAAO,iBAAiBA,UAAS,cAAc;AAAA,IACjD;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"session.cjs","sources":["../../src/session/session.ts","../../src/session/storageBackend.ts","../../src/session/storage.ts"],"sourcesContent":["import type { Session as AuthSession } from '../auth';\n\n/**\n * Decoded JWT token payload with processed timestamps and Hasura claims\n */\nexport interface DecodedToken {\n /** Token expiration time as Date object */\n exp?: number;\n /** Token issued at time as Date object */\n iat?: number;\n /** Token issuer */\n iss?: string;\n /** Token subject (user ID) */\n sub?: string;\n /** Hasura JWT claims with PostgreSQL arrays converted to JavaScript arrays */\n 'https://hasura.io/jwt/claims'?: Record<string, unknown>;\n /** Any other JWT claims */\n [key: string]: unknown;\n}\n\nexport interface Session extends AuthSession {\n /** Decoded JWT token payload with processed timestamps and Hasura claims */\n decodedToken: DecodedToken;\n}\n\n/**\n * Decodes a base64url-encoded string (RFC 4648 Section 5) to a UTF-8 string.\n *\n * JWTs use base64url encoding, which differs from standard base64 by using\n * `-` and `_` instead of `+` and `/`, and omitting padding. The browser's\n * native `atob()` does not support base64url, so we must handle the conversion.\n */\nconst decodeBase64Url = (input: string): string => {\n // Convert base64url to standard base64\n let base64 = input.replace(/-/g, '+').replace(/_/g, '/');\n const pad = base64.length % 4;\n if (pad) {\n base64 += '='.repeat(4 - pad);\n }\n\n // Use TextDecoder for proper UTF-8 support (atob alone mangles multi-byte characters)\n const binaryString = atob(base64);\n const bytes = Uint8Array.from(binaryString, (c) => c.charCodeAt(0));\n return new TextDecoder().decode(bytes);\n};\n\nexport const decodeUserSession = (accessToken: string): DecodedToken => {\n const s = accessToken.split('.');\n if (s.length !== 3 || !s[1]) {\n throw new Error('Invalid access token format');\n }\n\n const decodedToken = JSON.parse(decodeBase64Url(s[1])) as Record<\n string,\n unknown\n >;\n\n // Convert iat and exp to Date objects\n const iat =\n typeof decodedToken['iat'] === 'number'\n ? decodedToken['iat'] * 1000 // Convert seconds to milliseconds\n : undefined;\n const exp =\n typeof decodedToken['exp'] === 'number'\n ? decodedToken['exp'] * 1000 // Convert seconds to milliseconds\n : undefined;\n\n // Process Hasura claims - dynamically convert PostgreSQL array notation to arrays\n const hasuraClaims = decodedToken['https://hasura.io/jwt/claims'] as\n | Record<string, unknown>\n | undefined;\n const processedClaims = hasuraClaims\n ? Object.entries(hasuraClaims).reduce(\n (acc, [key, value]) => {\n if (typeof value === 'string' && isPostgresArray(value)) {\n acc[key] = parsePostgresArray(value);\n } else {\n acc[key] = value;\n }\n return acc;\n },\n {} as Record<string, unknown>,\n )\n : undefined;\n\n return {\n ...decodedToken,\n iat,\n exp,\n 'https://hasura.io/jwt/claims': processedClaims,\n };\n};\n\nconst isPostgresArray = (value: string): boolean => {\n return value.startsWith('{') && value.endsWith('}');\n};\n\nconst parsePostgresArray = (value: string): string[] => {\n if (!value || value === '{}') return [];\n // Remove curly braces and split by comma, handling quoted values\n return value\n .slice(1, -1)\n .split(',')\n .map((item) => item.trim().replace(/^\"(.*)\"$/, '$1'));\n};\n","/**\n * Storage implementations for session persistence in different environments.\n *\n * This module provides different storage adapters for persisting authentication sessions\n * across page reloads and browser sessions.\n */\n\nimport type { Session } from './session';\n\n/**\n * Session storage interface for session persistence.\n * This interface can be implemented to provide custom storage solutions.\n */\nexport interface SessionStorageBackend {\n /**\n * Get the current session from storage\n * @returns The stored session or null if not found\n */\n get(): Session | null;\n\n /**\n * Set the session in storage\n * @param value - The session to store\n */\n set(value: Session): void;\n\n /**\n * Remove the session from storage\n */\n remove(): void;\n}\n\n/**\n * Default storage key used for storing the Nhost session\n */\nexport const DEFAULT_SESSION_KEY = 'nhostSession';\n\n/**\n * Browser localStorage implementation of StorageInterface.\n * Persists the session across page reloads and browser restarts.\n */\nexport class LocalStorage implements SessionStorageBackend {\n private readonly storageKey: string;\n\n /**\n * Creates a new LocalStorage instance\n * @param options - Configuration options\n * @param options.storageKey - The key to use in localStorage (defaults to \"nhostSession\")\n */\n constructor(options?: { storageKey?: string }) {\n this.storageKey = options?.storageKey || DEFAULT_SESSION_KEY;\n }\n\n /**\n * Gets the session from localStorage\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n try {\n const value = window.localStorage.getItem(this.storageKey);\n return value ? (JSON.parse(value) as Session) : null;\n } catch {\n this.remove();\n return null;\n }\n }\n\n /**\n * Sets the session in localStorage\n * @param value - The session to store\n */\n set(value: Session): void {\n window.localStorage.setItem(this.storageKey, JSON.stringify(value));\n }\n\n /**\n * Removes the session from localStorage\n */\n remove(): void {\n window.localStorage.removeItem(this.storageKey);\n }\n}\n\n/**\n * In-memory storage implementation for non-browser environments or when\n * persistent storage is not available or desirable.\n */\nexport class MemoryStorage implements SessionStorageBackend {\n private session: Session | null = null;\n\n /**\n * Gets the session from memory\n * @returns The stored session or null if not set\n */\n get(): Session | null {\n return this.session;\n }\n\n /**\n * Sets the session in memory\n * @param value - The session to store\n */\n set(value: Session): void {\n this.session = value;\n }\n\n /**\n * Clears the session from memory\n */\n remove(): void {\n this.session = null;\n }\n}\n\n/**\n * Cookie-based storage implementation.\n * This storage uses web browser cookies to store the session so it's not\n * available in server-side environments. It is useful though for synchronizing\n * sessions between client and server environments.\n */\nexport class CookieStorage implements SessionStorageBackend {\n private readonly cookieName: string;\n private readonly expirationDays: number;\n private readonly secure: boolean;\n private readonly sameSite: 'strict' | 'lax' | 'none';\n\n /**\n * Creates a new CookieStorage instance\n * @param options - Configuration options\n * @param options.cookieName - Name of the cookie to use (defaults to \"nhostSession\")\n * @param options.expirationDays - Number of days until the cookie expires (defaults to 30)\n * @param options.secure - Whether to set the Secure flag on the cookie (defaults to true)\n * @param options.sameSite - SameSite policy for the cookie (defaults to \"lax\")\n */\n constructor(options?: {\n cookieName?: string;\n expirationDays?: number;\n secure?: boolean;\n sameSite?: 'strict' | 'lax' | 'none';\n }) {\n this.cookieName = options?.cookieName || DEFAULT_SESSION_KEY;\n this.expirationDays = options?.expirationDays ?? 30;\n this.secure = options?.secure ?? true;\n this.sameSite = options?.sameSite || 'lax';\n }\n\n /**\n * Gets the session from cookies\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n const cookies = document.cookie.split(';');\n for (const cookie of cookies) {\n const [name, value] = cookie.trim().split('=');\n if (name === this.cookieName) {\n try {\n return JSON.parse(decodeURIComponent(value || '')) as Session;\n } catch {\n this.remove();\n return null;\n }\n }\n }\n return null;\n }\n\n /**\n * Sets the session in a cookie\n * @param value - The session to store\n */\n set(value: Session): void {\n const expires = new Date();\n expires.setTime(\n expires.getTime() + this.expirationDays * 24 * 60 * 60 * 1000,\n );\n\n const cookieValue = encodeURIComponent(JSON.stringify(value));\n const cookieString = `${this.cookieName}=${cookieValue}; expires=${expires.toUTCString()}; path=/; ${this.secure ? 'secure; ' : ''}SameSite=${this.sameSite}`;\n\n // biome-ignore lint/suspicious/noDocumentCookie: this is unnecessary\n document.cookie = cookieString;\n }\n\n /**\n * Removes the session cookie\n */\n remove(): void {\n // biome-ignore lint/suspicious/noDocumentCookie: this is unnecessary\n document.cookie = `${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; ${this.secure ? 'secure; ' : ''}SameSite=${this.sameSite}`;\n }\n}\n","/**\n * Storage implementations for session persistence in different environments.\n *\n * This module provides different storage adapters for persisting authentication sessions\n * across page reloads and browser sessions.\n */\n\nimport type { Session as AuthSession } from '../auth';\nimport { decodeUserSession, type Session } from './session';\nimport {\n LocalStorage,\n MemoryStorage,\n type SessionStorageBackend,\n} from './storageBackend';\n\n/**\n * Callback function type for session change subscriptions\n */\nexport type SessionChangeCallback = (session: Session | null) => void;\n\n/**\n * A wrapper around any SessionStorageInterface implementation that adds\n * the ability to subscribe to session changes.\n */\nexport class SessionStorage {\n private readonly storage: SessionStorageBackend;\n private subscribers = new Set<SessionChangeCallback>();\n\n /**\n * Creates a new SessionStorage instance\n * @param storage - The underlying storage implementation to use\n */\n constructor(storage: SessionStorageBackend) {\n this.storage = storage;\n }\n\n /**\n * Gets the session from the underlying storage\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n return this.storage.get();\n }\n\n /**\n * Sets the session in the underlying storage and notifies subscribers\n * @param value - The session to store\n */\n set(value: AuthSession): void {\n const decodedToken = decodeUserSession(value.accessToken);\n const decodedSession = {\n ...value,\n decodedToken: decodedToken,\n };\n\n this.storage.set(decodedSession);\n this.notifySubscribers(decodedSession);\n }\n\n /**\n * Removes the session from the underlying storage and notifies subscribers\n */\n remove(): void {\n this.storage.remove();\n this.notifySubscribers(null);\n }\n\n /**\n * Subscribe to session changes\n * @param callback - Function that will be called when the session changes\n * @returns An unsubscribe function to remove this subscription\n */\n onChange(callback: SessionChangeCallback) {\n this.subscribers.add(callback);\n\n return () => {\n this.subscribers.delete(callback);\n };\n }\n\n /**\n * Notify all subscribers of a session change\n * @param session - The new session value or null if removed\n */\n private notifySubscribers(session: Session | null): void {\n for (const subscriber of this.subscribers) {\n try {\n subscriber(session);\n } catch (error) {\n console.error('Error notifying subscriber:', error);\n }\n }\n }\n}\n\n/**\n * Detects the best available storage implementation for the current environment.\n *\n * The detection process follows this order:\n * 1. Try to use localStorage if we're in a browser environment\n * 2. Fall back to in-memory storage if localStorage isn't available\n *\n * @returns The best available storage implementation as a SessionStorageBackend\n */\nexport const detectStorage = (): SessionStorageBackend => {\n if (typeof window !== 'undefined') {\n return new LocalStorage();\n }\n return new MemoryStorage();\n};\n"],"names":["decodeUserSession","accessToken","s","split","length","Error","decodedToken","JSON","parse","input","base64","replace","pad","repeat","binaryString","atob","bytes","Uint8Array","from","c","charCodeAt","TextDecoder","decode","decodeBase64Url","iat","exp","hasuraClaims","processedClaims","Object","entries","reduce","acc","key","value","isPostgresArray","parsePostgresArray","startsWith","endsWith","slice","map","item","trim","DEFAULT_SESSION_KEY","LocalStorage","storageKey","constructor","options","this","get","window","localStorage","getItem","remove","set","setItem","stringify","removeItem","MemoryStorage","session","cookieName","expirationDays","secure","sameSite","cookies","document","cookie","name","decodeURIComponent","expires","Date","setTime","getTime","cookieValue","encodeURIComponent","cookieString","toUTCString","storage","subscribers","Set","decodedSession","notifySubscribers","onChange","callback","add","delete","subscriber","error","console"],"mappings":"kIA8CaA,EAAqBC,IAChC,MAAMC,EAAID,EAAYE,MAAM,KAC5B,GAAiB,IAAbD,EAAEE,SAAiBF,EAAE,GACvB,MAAM,IAAIG,MAAM,+BAGlB,MAAMC,EAAeC,KAAKC,MApBJ,CAACC,IAEvB,IAAIC,EAASD,EAAME,QAAQ,KAAM,KAAKA,QAAQ,KAAM,KACpD,MAAMC,EAAMF,EAAON,OAAS,EACxBQ,IACFF,GAAU,IAAIG,OAAO,EAAID,IAI3B,MAAME,EAAeC,KAAKL,GACpBM,EAAQC,WAAWC,KAAKJ,GAAeK,GAAMA,EAAEC,WAAW,KAChE,OAAO,IAAIC,aAAcC,OAAON,EAAK,EASLO,CAAgBrB,EAAE,KAM5CsB,EAC2B,iBAAxBlB,EAAkB,IACC,IAAtBA,EAAkB,SAClB,EACAmB,EAC2B,iBAAxBnB,EAAkB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S4B,GACPC,QAAQD,MAAM,8BAA+BA,EAC/C,CAEJ,yBAY2B,IACL,oBAAXrC,OACF,IAAIN,EAEN,IAAIc"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"session.js","sources":["../../src/session/session.ts","../../src/session/storageBackend.ts","../../src/session/storage.ts"],"sourcesContent":["import type { Session as AuthSession } from '../auth';\n\n/**\n * Decoded JWT token payload with processed timestamps and Hasura claims\n */\nexport interface DecodedToken {\n /** Token expiration time as Date object */\n exp?: number;\n /** Token issued at time as Date object */\n iat?: number;\n /** Token issuer */\n iss?: string;\n /** Token subject (user ID) */\n sub?: string;\n /** Hasura JWT claims with PostgreSQL arrays converted to JavaScript arrays */\n 'https://hasura.io/jwt/claims'?: Record<string, unknown>;\n /** Any other JWT claims */\n [key: string]: unknown;\n}\n\nexport interface Session extends AuthSession {\n /** Decoded JWT token payload with processed timestamps and Hasura claims */\n decodedToken: DecodedToken;\n}\n\n/**\n * Decodes a base64url-encoded string (RFC 4648 Section 5) to a UTF-8 string.\n *\n * JWTs use base64url encoding, which differs from standard base64 by using\n * `-` and `_` instead of `+` and `/`, and omitting padding. The browser's\n * native `atob()` does not support base64url, so we must handle the conversion.\n */\nconst decodeBase64Url = (input: string): string => {\n // Convert base64url to standard base64\n let base64 = input.replace(/-/g, '+').replace(/_/g, '/');\n const pad = base64.length % 4;\n if (pad) {\n base64 += '='.repeat(4 - pad);\n }\n\n // Use TextDecoder for proper UTF-8 support (atob alone mangles multi-byte characters)\n const binaryString = atob(base64);\n const bytes = Uint8Array.from(binaryString, (c) => c.charCodeAt(0));\n return new TextDecoder().decode(bytes);\n};\n\nexport const decodeUserSession = (accessToken: string): DecodedToken => {\n const s = accessToken.split('.');\n if (s.length !== 3 || !s[1]) {\n throw new Error('Invalid access token format');\n }\n\n const decodedToken = JSON.parse(decodeBase64Url(s[1])) as Record<\n string,\n unknown\n >;\n\n // Convert iat and exp to Date objects\n const iat =\n typeof decodedToken['iat'] === 'number'\n ? decodedToken['iat'] * 1000 // Convert seconds to milliseconds\n : undefined;\n const exp =\n typeof decodedToken['exp'] === 'number'\n ? decodedToken['exp'] * 1000 // Convert seconds to milliseconds\n : undefined;\n\n // Process Hasura claims - dynamically convert PostgreSQL array notation to arrays\n const hasuraClaims = decodedToken['https://hasura.io/jwt/claims'] as\n | Record<string, unknown>\n | undefined;\n const processedClaims = hasuraClaims\n ? Object.entries(hasuraClaims).reduce(\n (acc, [key, value]) => {\n if (typeof value === 'string' && isPostgresArray(value)) {\n acc[key] = parsePostgresArray(value);\n } else {\n acc[key] = value;\n }\n return acc;\n },\n {} as Record<string, unknown>,\n )\n : undefined;\n\n return {\n ...decodedToken,\n iat,\n exp,\n 'https://hasura.io/jwt/claims': processedClaims,\n };\n};\n\nconst isPostgresArray = (value: string): boolean => {\n return value.startsWith('{') && value.endsWith('}');\n};\n\nconst parsePostgresArray = (value: string): string[] => {\n if (!value || value === '{}') return [];\n // Remove curly braces and split by comma, handling quoted values\n return value\n .slice(1, -1)\n .split(',')\n .map((item) => item.trim().replace(/^\"(.*)\"$/, '$1'));\n};\n","/**\n * Storage implementations for session persistence in different environments.\n *\n * This module provides different storage adapters for persisting authentication sessions\n * across page reloads and browser sessions.\n */\n\nimport type { Session } from './session';\n\n/**\n * Session storage interface for session persistence.\n * This interface can be implemented to provide custom storage solutions.\n */\nexport interface SessionStorageBackend {\n /**\n * Get the current session from storage\n * @returns The stored session or null if not found\n */\n get(): Session | null;\n\n /**\n * Set the session in storage\n * @param value - The session to store\n */\n set(value: Session): void;\n\n /**\n * Remove the session from storage\n */\n remove(): void;\n}\n\n/**\n * Default storage key used for storing the Nhost session\n */\nexport const DEFAULT_SESSION_KEY = 'nhostSession';\n\n/**\n * Browser localStorage implementation of StorageInterface.\n * Persists the session across page reloads and browser restarts.\n */\nexport class LocalStorage implements SessionStorageBackend {\n private readonly storageKey: string;\n\n /**\n * Creates a new LocalStorage instance\n * @param options - Configuration options\n * @param options.storageKey - The key to use in localStorage (defaults to \"nhostSession\")\n */\n constructor(options?: { storageKey?: string }) {\n this.storageKey = options?.storageKey || DEFAULT_SESSION_KEY;\n }\n\n /**\n * Gets the session from localStorage\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n try {\n const value = window.localStorage.getItem(this.storageKey);\n return value ? (JSON.parse(value) as Session) : null;\n } catch {\n this.remove();\n return null;\n }\n }\n\n /**\n * Sets the session in localStorage\n * @param value - The session to store\n */\n set(value: Session): void {\n window.localStorage.setItem(this.storageKey, JSON.stringify(value));\n }\n\n /**\n * Removes the session from localStorage\n */\n remove(): void {\n window.localStorage.removeItem(this.storageKey);\n }\n}\n\n/**\n * In-memory storage implementation for non-browser environments or when\n * persistent storage is not available or desirable.\n */\nexport class MemoryStorage implements SessionStorageBackend {\n private session: Session | null = null;\n\n /**\n * Gets the session from memory\n * @returns The stored session or null if not set\n */\n get(): Session | null {\n return this.session;\n }\n\n /**\n * Sets the session in memory\n * @param value - The session to store\n */\n set(value: Session): void {\n this.session = value;\n }\n\n /**\n * Clears the session from memory\n */\n remove(): void {\n this.session = null;\n }\n}\n\n/**\n * Cookie-based storage implementation.\n * This storage uses web browser cookies to store the session so it's not\n * available in server-side environments. It is useful though for synchronizing\n * sessions between client and server environments.\n */\nexport class CookieStorage implements SessionStorageBackend {\n private readonly cookieName: string;\n private readonly expirationDays: number;\n private readonly secure: boolean;\n private readonly sameSite: 'strict' | 'lax' | 'none';\n\n /**\n * Creates a new CookieStorage instance\n * @param options - Configuration options\n * @param options.cookieName - Name of the cookie to use (defaults to \"nhostSession\")\n * @param options.expirationDays - Number of days until the cookie expires (defaults to 30)\n * @param options.secure - Whether to set the Secure flag on the cookie (defaults to true)\n * @param options.sameSite - SameSite policy for the cookie (defaults to \"lax\")\n */\n constructor(options?: {\n cookieName?: string;\n expirationDays?: number;\n secure?: boolean;\n sameSite?: 'strict' | 'lax' | 'none';\n }) {\n this.cookieName = options?.cookieName || DEFAULT_SESSION_KEY;\n this.expirationDays = options?.expirationDays ?? 30;\n this.secure = options?.secure ?? true;\n this.sameSite = options?.sameSite || 'lax';\n }\n\n /**\n * Gets the session from cookies\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n const cookies = document.cookie.split(';');\n for (const cookie of cookies) {\n const [name, value] = cookie.trim().split('=');\n if (name === this.cookieName) {\n try {\n return JSON.parse(decodeURIComponent(value || '')) as Session;\n } catch {\n this.remove();\n return null;\n }\n }\n }\n return null;\n }\n\n /**\n * Sets the session in a cookie\n * @param value - The session to store\n */\n set(value: Session): void {\n const expires = new Date();\n expires.setTime(\n expires.getTime() + this.expirationDays * 24 * 60 * 60 * 1000,\n );\n\n const cookieValue = encodeURIComponent(JSON.stringify(value));\n const cookieString = `${this.cookieName}=${cookieValue}; expires=${expires.toUTCString()}; path=/; ${this.secure ? 'secure; ' : ''}SameSite=${this.sameSite}`;\n\n // biome-ignore lint/suspicious/noDocumentCookie: this is unnecessary\n document.cookie = cookieString;\n }\n\n /**\n * Removes the session cookie\n */\n remove(): void {\n // biome-ignore lint/suspicious/noDocumentCookie: this is unnecessary\n document.cookie = `${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; ${this.secure ? 'secure; ' : ''}SameSite=${this.sameSite}`;\n }\n}\n","/**\n * Storage implementations for session persistence in different environments.\n *\n * This module provides different storage adapters for persisting authentication sessions\n * across page reloads and browser sessions.\n */\n\nimport type { Session as AuthSession } from '../auth';\nimport { decodeUserSession, type Session } from './session';\nimport {\n LocalStorage,\n MemoryStorage,\n type SessionStorageBackend,\n} from './storageBackend';\n\n/**\n * Callback function type for session change subscriptions\n */\nexport type SessionChangeCallback = (session: Session | null) => void;\n\n/**\n * A wrapper around any SessionStorageInterface implementation that adds\n * the ability to subscribe to session changes.\n */\nexport class SessionStorage {\n private readonly storage: SessionStorageBackend;\n private subscribers = new Set<SessionChangeCallback>();\n\n /**\n * Creates a new SessionStorage instance\n * @param storage - The underlying storage implementation to use\n */\n constructor(storage: SessionStorageBackend) {\n this.storage = storage;\n }\n\n /**\n * Gets the session from the underlying storage\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n return this.storage.get();\n }\n\n /**\n * Sets the session in the underlying storage and notifies subscribers\n * @param value - The session to store\n */\n set(value: AuthSession): void {\n const decodedToken = decodeUserSession(value.accessToken);\n const decodedSession = {\n ...value,\n decodedToken: decodedToken,\n };\n\n this.storage.set(decodedSession);\n this.notifySubscribers(decodedSession);\n }\n\n /**\n * Removes the session from the underlying storage and notifies subscribers\n */\n remove(): void {\n this.storage.remove();\n this.notifySubscribers(null);\n }\n\n /**\n * Subscribe to session changes\n * @param callback - Function that will be called when the session changes\n * @returns An unsubscribe function to remove this subscription\n */\n onChange(callback: SessionChangeCallback) {\n this.subscribers.add(callback);\n\n return () => {\n this.subscribers.delete(callback);\n };\n }\n\n /**\n * Notify all subscribers of a session change\n * @param session - The new session value or null if removed\n */\n private notifySubscribers(session: Session | null): void {\n for (const subscriber of this.subscribers) {\n try {\n subscriber(session);\n } catch (error) {\n console.error('Error notifying subscriber:', error);\n }\n }\n }\n}\n\n/**\n * Detects the best available storage implementation for the current environment.\n *\n * The detection process follows this order:\n * 1. Try to use localStorage if we're in a browser environment\n * 2. Fall back to in-memory storage if localStorage isn't available\n *\n * @returns The best available storage implementation as a SessionStorageBackend\n */\nexport const detectStorage = (): SessionStorageBackend => {\n if (typeof window !== 'undefined') {\n return new LocalStorage();\n }\n return new MemoryStorage();\n};\n"],"names":[],"mappings":";AAgCA,MAAM,kBAAkB,CAAC,UAA0B;AAEjD,MAAI,SAAS,MAAM,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,GAAG;AACvD,QAAM,MAAM,OAAO,SAAS;AAC5B,MAAI,KAAK;AACP,cAAU,IAAI,OAAO,IAAI,GAAG;AAAA,EAC9B;AAGA,QAAM,eAAe,KAAK,MAAM;AAChC,QAAM,QAAQ,WAAW,KAAK,cAAc,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;AAClE,SAAO,IAAI,YAAA,EAAc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AAA,EAOA,SAAS,UAAiC;AACxC,SAAK,YAAY,IAAI,QAAQ;AAE7B,WAAO,MAAM;AACX,WAAK,YAAY,OAAO,QAAQ;AAAA,IAClC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,kBAAkB,SAA+B;AACvD,eAAW,cAAc,KAAK,aAAa;AACzC,UAAI;AACF,mBAAW,OAAO;AAAA,MACpB,SAAS,OAAO;AACd,gBAAQ,MAAM,+BAA+B,KAAK;AAAA,MACpD;AAAA,IACF;AAAA,EACF;AACF;AAWO,MAAM,gBAAgB,MAA6B;AACxD,MAAI,OAAO,WAAW,aAAa;AACjC,WAAO,IAAI,aAAA;AAAA,EACb;AACA,SAAO,IAAI,cAAA;AACb;"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const e="undefined"!=typeof navigator&&navigator.locks?navigator.locks:new class{async request(e,s,r){return r()}},s=async(s,n,o=60)=>{const{session:t,needsRefresh:i}=await e.request("nhostSessionLock",{mode:"shared"},(async()=>r(n,o)));if(!t)return null;if(!i)return t;return await e.request("nhostSessionLock",{mode:"exclusive"},(async()=>{const{session:e,needsRefresh:t,sessionExpired:i}=r(n,o);if(!e)return null;if(!t)return e;try{const r=await s.refreshToken({refreshToken:e.refreshToken});return n.set(r.body),r.body}catch(d){if(!i)return e;throw d}}))},r=(e,s=60)=>{const r=e.get();if(!r)return{session:null,needsRefresh:!1,sessionExpired:!1};if(!r.decodedToken||!r.decodedToken.exp)return{session:r,needsRefresh:!0,sessionExpired:!0};if(0===s)return{session:r,needsRefresh:!0,sessionExpired:!1};const n=Date.now();return r.decodedToken.exp-n>1e3*s?{session:r,needsRefresh:!1,sessionExpired:!1}:{session:r,needsRefresh:!0,sessionExpired:r.decodedToken.exp<n}};exports.refreshSession=async(e,r,n=60)=>{try{return await s(e,r,n)}catch(o){try{return console.warn("error refreshing session, retrying:",o),await s(e,r,n)}catch(t){const e=t;return 401===e?.status&&(console.error("session probably expired"),r.remove()),null}}};
|
|
2
|
-
//# sourceMappingURL=refreshSession-Bw715ZmX.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"refreshSession-Bw715ZmX.cjs","sources":["../src/session/refreshSession.ts"],"sourcesContent":["import type { Client as AuthClient, ErrorResponse } from '../auth';\nimport type { FetchResponse } from '../fetch';\nimport type { Session } from './session';\nimport type { SessionStorage } from './storage';\n\nclass DummyLock implements Lock {\n async request(\n _name: string,\n _options: { mode: 'exclusive' | 'shared' },\n // biome-ignore lint/suspicious/noExplicitAny: any\n callback: () => Promise<any>,\n ) {\n return callback();\n }\n}\n\ninterface Lock {\n request: (\n name: string,\n options: { mode: 'exclusive' | 'shared' },\n // biome-ignore lint/suspicious/noExplicitAny: blah\n callback: () => Promise<any>,\n // biome-ignore lint/suspicious/noExplicitAny: blah\n ) => Promise<any>;\n}\n\nconst lock: Lock =\n typeof navigator !== 'undefined' && navigator.locks\n ? navigator.locks\n : new DummyLock();\n\n/**\n * Refreshes the authentication session if needed\n *\n * This function checks if the current session needs to be refreshed based on\n * the access token expiration time. If a refresh is needed, it will attempt to\n * refresh the token using the provided auth client.\n *\n * @param auth - The authentication client to use for token refresh\n * @param storage - The session storage implementation\n * @param marginSeconds - The number of seconds before the token expiration to refresh the session. If the token is still valid for this duration, it will not be refreshed. Set to 0 to force the refresh.\n * @returns A promise that resolves to the current session (refreshed if needed) or null if no session exists\n */\nexport const refreshSession = async (\n auth: AuthClient,\n storage: SessionStorage,\n marginSeconds = 60,\n): Promise<Session | null> => {\n try {\n return await _refreshSession(auth, storage, marginSeconds);\n } catch (error) {\n try {\n // we retry the refresh token in case of transient error\n // or race conditions\n console.warn('error refreshing session, retrying:', error);\n return await _refreshSession(auth, storage, marginSeconds);\n } catch (error) {\n const errResponse = error as FetchResponse<ErrorResponse>;\n if (errResponse?.status === 401) {\n // this probably means the refresh token is invalid\n console.error('session probably expired');\n storage.remove();\n }\n return null;\n }\n }\n};\n\n/**\n * Internal implementation of the refresh session logic\n *\n * @param auth - The authentication client to use for token refresh\n * @param storage - The session storage implementation\n * @param marginSeconds - How many seconds before expiration to trigger a refresh\n * @returns A promise that resolves to the current session (refreshed if needed) or null if no session exists\n * @private\n */\nconst _refreshSession = async (\n auth: AuthClient,\n storage: SessionStorage,\n marginSeconds = 60,\n): Promise<Session | null> => {\n const {\n session,\n needsRefresh,\n }: { session: Session | null; needsRefresh: boolean } = await lock.request(\n 'nhostSessionLock',\n { mode: 'shared' },\n async () => {\n return _needsRefresh(storage, marginSeconds);\n },\n );\n\n if (!session) {\n return null; // No session found\n }\n\n if (!needsRefresh) {\n return session; // No need to refresh\n }\n\n const refreshedSession: Session | null = await lock.request(\n 'nhostSessionLock',\n { mode: 'exclusive' },\n async () => {\n const { session, needsRefresh, sessionExpired } = _needsRefresh(\n storage,\n marginSeconds,\n );\n\n if (!session) {\n return null; // No session found\n }\n\n if (!needsRefresh) {\n return session; // No need to refresh\n }\n\n try {\n const response = await auth.refreshToken({\n refreshToken: session.refreshToken,\n });\n storage.set(response.body);\n\n return response.body;\n } catch (error) {\n if (!sessionExpired) {\n return session;\n }\n\n throw error;\n }\n },\n );\n\n return refreshedSession;\n};\n\n/**\n * Checks if the current session needs to be refreshed based on token expiration\n *\n * @param storage - The session storage implementation\n * @param marginSeconds - How many seconds before expiration to trigger a refresh\n * @returns An object containing the session, whether it needs refreshing, and whether it has expired\n * @private\n */\nconst _needsRefresh = (storage: SessionStorage, marginSeconds = 60) => {\n const session = storage.get();\n if (!session) {\n return { session: null, needsRefresh: false, sessionExpired: false };\n }\n\n if (!session.decodedToken || !session.decodedToken.exp) {\n // if the session does not have a valid decoded token, treat it as expired\n // as we can't determine its validity\n return { session, needsRefresh: true, sessionExpired: true };\n }\n\n // Force refresh if marginSeconds is 0\n if (marginSeconds === 0) {\n return { session, needsRefresh: true, sessionExpired: false };\n }\n\n const currentTime = Date.now();\n if (session.decodedToken.exp - currentTime > marginSeconds * 1000) {\n return { session, needsRefresh: false, sessionExpired: false };\n }\n\n return {\n session,\n needsRefresh: true,\n sessionExpired: session.decodedToken.exp < currentTime,\n };\n};\n"],"names":["lock","navigator","locks","request","_name","_options","callback","_refreshSession","async","auth","storage","marginSeconds","session","needsRefresh","mode","_needsRefresh","sessionExpired","response","refreshToken","set","body","error","get","decodedToken","exp","currentTime","Date","now","console","warn","errResponse","status","remove"],"mappings":"aA0BA,MAAMA,EACiB,oBAAdC,WAA6BA,UAAUC,MAC1CD,UAAUC,MACV,IAxBN,MACE,aAAMC,CACJC,EACAC,EAEAC,GAEA,OAAOA,GACT,GAgEIC,EAAkBC,MACtBC,EACAC,EACAC,EAAgB,MAEhB,MAAMC,QACJA,EAAAC,aACAA,SAC4Db,EAAKG,QACjE,mBACA,CAAEW,KAAM,WACRN,SACSO,EAAcL,EAASC,KAIlC,IAAKC,EACH,OAAO,KAGT,IAAKC,EACH,OAAOD,EAqCT,aAlC+CZ,EAAKG,QAClD,mBACA,CAAEW,KAAM,cACRN,UACE,MAAQI,QAAAA,EAASC,aAAAA,EAAAA,eAAcG,GAAmBD,EAChDL,EACAC,GAGF,IAAKC,EACH,OAAO,KAGT,IAAKC,EACH,OAAOD,EAGT,IACE,MAAMK,QAAiBR,EAAKS,aAAa,CACvCA,aAAcN,EAAQM,eAIxB,OAFAR,EAAQS,IAAIF,EAASG,MAEdH,EAASG,IAClB,OAASC,GACP,IAAKL,EACH,OAAOJ,EAGT,MAAMS,CACR,IAIG,EAWHN,EAAgB,CAACL,EAAyBC,EAAgB,MAC9D,MAAMC,EAAUF,EAAQY,MACxB,IAAKV,EACH,MAAO,CAAEA,QAAS,KAAMC,cAAc,EAAOG,gBAAgB,GAG/D,IAAKJ,EAAQW,eAAiBX,EAAQW,aAAaC,IAGjD,MAAO,CAAEZ,UAASC,cAAc,EAAMG,gBAAgB,GAIxD,GAAsB,IAAlBL,EACF,MAAO,CAAEC,UAASC,cAAc,EAAMG,gBAAgB,GAGxD,MAAMS,EAAcC,KAAKC,MACzB,OAAIf,EAAQW,aAAaC,IAAMC,EAA8B,IAAhBd,EACpC,CAAEC,UAASC,cAAc,EAAOG,gBAAgB,GAGlD,CACLJ,UACAC,cAAc,EACdG,eAAgBJ,EAAQW,aAAaC,IAAMC,EAAA,yBAhIjBjB,MAC5BC,EACAC,EACAC,EAAgB,MAEhB,IACE,aAAaJ,EAAgBE,EAAMC,EAASC,EAC9C,OAASU,GACP,IAIE,OADAO,QAAQC,KAAK,sCAAuCR,SACvCd,EAAgBE,EAAMC,EAASC,EAC9C,OAASU,GACP,MAAMS,EAAcT,EAMpB,OAL4B,MAAxBS,GAAaC,SAEfH,QAAQP,MAAM,4BACdX,EAAQsB,UAEH,IACT,CACF"}
|
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
class DummyLock {
|
|
2
|
-
async request(_name, _options, callback) {
|
|
3
|
-
return callback();
|
|
4
|
-
}
|
|
5
|
-
}
|
|
6
|
-
const lock = typeof navigator !== "undefined" && navigator.locks ? navigator.locks : new DummyLock();
|
|
7
|
-
const refreshSession = async (auth, storage, marginSeconds = 60) => {
|
|
8
|
-
try {
|
|
9
|
-
return await _refreshSession(auth, storage, marginSeconds);
|
|
10
|
-
} catch (error) {
|
|
11
|
-
try {
|
|
12
|
-
console.warn("error refreshing session, retrying:", error);
|
|
13
|
-
return await _refreshSession(auth, storage, marginSeconds);
|
|
14
|
-
} catch (error2) {
|
|
15
|
-
const errResponse = error2;
|
|
16
|
-
if (errResponse?.status === 401) {
|
|
17
|
-
console.error("session probably expired");
|
|
18
|
-
storage.remove();
|
|
19
|
-
}
|
|
20
|
-
return null;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
};
|
|
24
|
-
const _refreshSession = async (auth, storage, marginSeconds = 60) => {
|
|
25
|
-
const {
|
|
26
|
-
session,
|
|
27
|
-
needsRefresh
|
|
28
|
-
} = await lock.request(
|
|
29
|
-
"nhostSessionLock",
|
|
30
|
-
{ mode: "shared" },
|
|
31
|
-
async () => {
|
|
32
|
-
return _needsRefresh(storage, marginSeconds);
|
|
33
|
-
}
|
|
34
|
-
);
|
|
35
|
-
if (!session) {
|
|
36
|
-
return null;
|
|
37
|
-
}
|
|
38
|
-
if (!needsRefresh) {
|
|
39
|
-
return session;
|
|
40
|
-
}
|
|
41
|
-
const refreshedSession = await lock.request(
|
|
42
|
-
"nhostSessionLock",
|
|
43
|
-
{ mode: "exclusive" },
|
|
44
|
-
async () => {
|
|
45
|
-
const { session: session2, needsRefresh: needsRefresh2, sessionExpired } = _needsRefresh(
|
|
46
|
-
storage,
|
|
47
|
-
marginSeconds
|
|
48
|
-
);
|
|
49
|
-
if (!session2) {
|
|
50
|
-
return null;
|
|
51
|
-
}
|
|
52
|
-
if (!needsRefresh2) {
|
|
53
|
-
return session2;
|
|
54
|
-
}
|
|
55
|
-
try {
|
|
56
|
-
const response = await auth.refreshToken({
|
|
57
|
-
refreshToken: session2.refreshToken
|
|
58
|
-
});
|
|
59
|
-
storage.set(response.body);
|
|
60
|
-
return response.body;
|
|
61
|
-
} catch (error) {
|
|
62
|
-
if (!sessionExpired) {
|
|
63
|
-
return session2;
|
|
64
|
-
}
|
|
65
|
-
throw error;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
);
|
|
69
|
-
return refreshedSession;
|
|
70
|
-
};
|
|
71
|
-
const _needsRefresh = (storage, marginSeconds = 60) => {
|
|
72
|
-
const session = storage.get();
|
|
73
|
-
if (!session) {
|
|
74
|
-
return { session: null, needsRefresh: false, sessionExpired: false };
|
|
75
|
-
}
|
|
76
|
-
if (!session.decodedToken || !session.decodedToken.exp) {
|
|
77
|
-
return { session, needsRefresh: true, sessionExpired: true };
|
|
78
|
-
}
|
|
79
|
-
if (marginSeconds === 0) {
|
|
80
|
-
return { session, needsRefresh: true, sessionExpired: false };
|
|
81
|
-
}
|
|
82
|
-
const currentTime = Date.now();
|
|
83
|
-
if (session.decodedToken.exp - currentTime > marginSeconds * 1e3) {
|
|
84
|
-
return { session, needsRefresh: false, sessionExpired: false };
|
|
85
|
-
}
|
|
86
|
-
return {
|
|
87
|
-
session,
|
|
88
|
-
needsRefresh: true,
|
|
89
|
-
sessionExpired: session.decodedToken.exp < currentTime
|
|
90
|
-
};
|
|
91
|
-
};
|
|
92
|
-
export {
|
|
93
|
-
refreshSession as r
|
|
94
|
-
};
|
|
95
|
-
//# sourceMappingURL=refreshSession-WwGlzgtM.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"refreshSession-WwGlzgtM.js","sources":["../src/session/refreshSession.ts"],"sourcesContent":["import type { Client as AuthClient, ErrorResponse } from '../auth';\nimport type { FetchResponse } from '../fetch';\nimport type { Session } from './session';\nimport type { SessionStorage } from './storage';\n\nclass DummyLock implements Lock {\n async request(\n _name: string,\n _options: { mode: 'exclusive' | 'shared' },\n // biome-ignore lint/suspicious/noExplicitAny: any\n callback: () => Promise<any>,\n ) {\n return callback();\n }\n}\n\ninterface Lock {\n request: (\n name: string,\n options: { mode: 'exclusive' | 'shared' },\n // biome-ignore lint/suspicious/noExplicitAny: blah\n callback: () => Promise<any>,\n // biome-ignore lint/suspicious/noExplicitAny: blah\n ) => Promise<any>;\n}\n\nconst lock: Lock =\n typeof navigator !== 'undefined' && navigator.locks\n ? navigator.locks\n : new DummyLock();\n\n/**\n * Refreshes the authentication session if needed\n *\n * This function checks if the current session needs to be refreshed based on\n * the access token expiration time. If a refresh is needed, it will attempt to\n * refresh the token using the provided auth client.\n *\n * @param auth - The authentication client to use for token refresh\n * @param storage - The session storage implementation\n * @param marginSeconds - The number of seconds before the token expiration to refresh the session. If the token is still valid for this duration, it will not be refreshed. Set to 0 to force the refresh.\n * @returns A promise that resolves to the current session (refreshed if needed) or null if no session exists\n */\nexport const refreshSession = async (\n auth: AuthClient,\n storage: SessionStorage,\n marginSeconds = 60,\n): Promise<Session | null> => {\n try {\n return await _refreshSession(auth, storage, marginSeconds);\n } catch (error) {\n try {\n // we retry the refresh token in case of transient error\n // or race conditions\n console.warn('error refreshing session, retrying:', error);\n return await _refreshSession(auth, storage, marginSeconds);\n } catch (error) {\n const errResponse = error as FetchResponse<ErrorResponse>;\n if (errResponse?.status === 401) {\n // this probably means the refresh token is invalid\n console.error('session probably expired');\n storage.remove();\n }\n return null;\n }\n }\n};\n\n/**\n * Internal implementation of the refresh session logic\n *\n * @param auth - The authentication client to use for token refresh\n * @param storage - The session storage implementation\n * @param marginSeconds - How many seconds before expiration to trigger a refresh\n * @returns A promise that resolves to the current session (refreshed if needed) or null if no session exists\n * @private\n */\nconst _refreshSession = async (\n auth: AuthClient,\n storage: SessionStorage,\n marginSeconds = 60,\n): Promise<Session | null> => {\n const {\n session,\n needsRefresh,\n }: { session: Session | null; needsRefresh: boolean } = await lock.request(\n 'nhostSessionLock',\n { mode: 'shared' },\n async () => {\n return _needsRefresh(storage, marginSeconds);\n },\n );\n\n if (!session) {\n return null; // No session found\n }\n\n if (!needsRefresh) {\n return session; // No need to refresh\n }\n\n const refreshedSession: Session | null = await lock.request(\n 'nhostSessionLock',\n { mode: 'exclusive' },\n async () => {\n const { session, needsRefresh, sessionExpired } = _needsRefresh(\n storage,\n marginSeconds,\n );\n\n if (!session) {\n return null; // No session found\n }\n\n if (!needsRefresh) {\n return session; // No need to refresh\n }\n\n try {\n const response = await auth.refreshToken({\n refreshToken: session.refreshToken,\n });\n storage.set(response.body);\n\n return response.body;\n } catch (error) {\n if (!sessionExpired) {\n return session;\n }\n\n throw error;\n }\n },\n );\n\n return refreshedSession;\n};\n\n/**\n * Checks if the current session needs to be refreshed based on token expiration\n *\n * @param storage - The session storage implementation\n * @param marginSeconds - How many seconds before expiration to trigger a refresh\n * @returns An object containing the session, whether it needs refreshing, and whether it has expired\n * @private\n */\nconst _needsRefresh = (storage: SessionStorage, marginSeconds = 60) => {\n const session = storage.get();\n if (!session) {\n return { session: null, needsRefresh: false, sessionExpired: false };\n }\n\n if (!session.decodedToken || !session.decodedToken.exp) {\n // if the session does not have a valid decoded token, treat it as expired\n // as we can't determine its validity\n return { session, needsRefresh: true, sessionExpired: true };\n }\n\n // Force refresh if marginSeconds is 0\n if (marginSeconds === 0) {\n return { session, needsRefresh: true, sessionExpired: false };\n }\n\n const currentTime = Date.now();\n if (session.decodedToken.exp - currentTime > marginSeconds * 1000) {\n return { session, needsRefresh: false, sessionExpired: false };\n }\n\n return {\n session,\n needsRefresh: true,\n sessionExpired: session.decodedToken.exp < currentTime,\n };\n};\n"],"names":["error","session","needsRefresh"],"mappings":"AAKA,MAAM,UAA0B;AAAA,EAC9B,MAAM,QACJ,OACA,UAEA,UACA;AACA,WAAO,SAAA;AAAA,EACT;AACF;AAYA,MAAM,OACJ,OAAO,cAAc,eAAe,UAAU,QAC1C,UAAU,QACV,IAAI,UAAA;AAcH,MAAM,iBAAiB,OAC5B,MACA,SACA,gBAAgB,OACY;AAC5B,MAAI;AACF,WAAO,MAAM,gBAAgB,MAAM,SAAS,aAAa;AAAA,EAC3D,SAAS,OAAO;AACd,QAAI;AAGF,cAAQ,KAAK,uCAAuC,KAAK;AACzD,aAAO,MAAM,gBAAgB,MAAM,SAAS,aAAa;AAAA,IAC3D,SAASA,QAAO;AACd,YAAM,cAAcA;AACpB,UAAI,aAAa,WAAW,KAAK;AAE/B,gBAAQ,MAAM,0BAA0B;AACxC,gBAAQ,OAAA;AAAA,MACV;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAWA,MAAM,kBAAkB,OACtB,MACA,SACA,gBAAgB,OACY;AAC5B,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,EAAA,IACsD,MAAM,KAAK;AAAA,IACjE;AAAA,IACA,EAAE,MAAM,SAAA;AAAA,IACR,YAAY;AACV,aAAO,cAAc,SAAS,aAAa;AAAA,IAC7C;AAAA,EAAA;AAGF,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,MAAI,CAAC,cAAc;AACjB,WAAO;AAAA,EACT;AAEA,QAAM,mBAAmC,MAAM,KAAK;AAAA,IAClD;AAAA,IACA,EAAE,MAAM,YAAA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