@nhost/nhost-js 3.3.0 → 4.0.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.
Files changed (147) hide show
  1. package/README.md +68 -32
  2. package/dist/fetch-2PHmQBIJ.mjs +61 -0
  3. package/dist/fetch-2PHmQBIJ.mjs.map +1 -0
  4. package/dist/fetch-DWXwEnoe.js +2 -0
  5. package/dist/fetch-DWXwEnoe.js.map +1 -0
  6. package/dist/nhost-js/auth.cjs.js +2 -0
  7. package/dist/nhost-js/auth.cjs.js.map +1 -0
  8. package/dist/nhost-js/auth.es.js +917 -0
  9. package/dist/nhost-js/auth.es.js.map +1 -0
  10. package/dist/nhost-js/fetch.cjs.js +2 -0
  11. package/dist/nhost-js/fetch.cjs.js.map +1 -0
  12. package/dist/nhost-js/fetch.es.js +90 -0
  13. package/dist/nhost-js/fetch.es.js.map +1 -0
  14. package/dist/nhost-js/functions.cjs.js +2 -0
  15. package/dist/nhost-js/functions.cjs.js.map +1 -0
  16. package/dist/nhost-js/functions.es.js +45 -0
  17. package/dist/nhost-js/functions.es.js.map +1 -0
  18. package/dist/nhost-js/graphql.cjs.js +2 -0
  19. package/dist/nhost-js/graphql.cjs.js.map +1 -0
  20. package/dist/nhost-js/graphql.es.js +48 -0
  21. package/dist/nhost-js/graphql.es.js.map +1 -0
  22. package/dist/nhost-js/session.cjs.js +2 -0
  23. package/dist/nhost-js/session.cjs.js.map +1 -0
  24. package/dist/nhost-js/session.es.js +234 -0
  25. package/dist/nhost-js/session.es.js.map +1 -0
  26. package/dist/nhost-js/storage.cjs.js +2 -0
  27. package/dist/nhost-js/storage.cjs.js.map +1 -0
  28. package/dist/nhost-js/storage.es.js +324 -0
  29. package/dist/nhost-js/storage.es.js.map +1 -0
  30. package/dist/nhost-js.cjs.js +2 -0
  31. package/dist/nhost-js.cjs.js.map +1 -0
  32. package/dist/nhost-js.es.js +228 -0
  33. package/dist/nhost-js.es.js.map +1 -0
  34. package/dist/nhost-js.umd.js +2 -0
  35. package/dist/nhost-js.umd.js.map +1 -0
  36. package/dist/refreshSession-Bw715ZmX.js +2 -0
  37. package/dist/refreshSession-Bw715ZmX.js.map +1 -0
  38. package/dist/refreshSession-WwGlzgtM.mjs +95 -0
  39. package/dist/refreshSession-WwGlzgtM.mjs.map +1 -0
  40. package/dist/src/auth/client.d.ts +1763 -0
  41. package/dist/src/auth/client.d.ts.map +1 -0
  42. package/dist/src/auth/client.js +1043 -0
  43. package/dist/src/auth/client.js.map +1 -0
  44. package/dist/src/auth/index.d.ts +35 -0
  45. package/dist/src/auth/index.d.ts.map +1 -0
  46. package/dist/src/auth/index.js +35 -0
  47. package/dist/src/auth/index.js.map +1 -0
  48. package/dist/src/fetch/fetch.d.ts +88 -0
  49. package/dist/src/fetch/fetch.d.ts.map +1 -0
  50. package/dist/src/fetch/fetch.js +98 -0
  51. package/dist/src/fetch/fetch.js.map +1 -0
  52. package/dist/src/fetch/index.d.ts +38 -0
  53. package/dist/src/fetch/index.d.ts.map +1 -0
  54. package/dist/src/fetch/index.js +38 -0
  55. package/dist/src/fetch/index.js.map +1 -0
  56. package/dist/src/fetch/middlewareAttachAccessToken.d.ts +24 -0
  57. package/dist/src/fetch/middlewareAttachAccessToken.d.ts.map +1 -0
  58. package/dist/src/fetch/middlewareAttachAccessToken.js +54 -0
  59. package/dist/src/fetch/middlewareAttachAccessToken.js.map +1 -0
  60. package/dist/src/fetch/middlewareSessionRefresh.d.ts +30 -0
  61. package/dist/src/fetch/middlewareSessionRefresh.d.ts.map +1 -0
  62. package/dist/src/fetch/middlewareSessionRefresh.js +61 -0
  63. package/dist/src/fetch/middlewareSessionRefresh.js.map +1 -0
  64. package/dist/src/fetch/middlewareUpdateSessionFromResponse.d.ts +26 -0
  65. package/dist/src/fetch/middlewareUpdateSessionFromResponse.d.ts.map +1 -0
  66. package/dist/src/fetch/middlewareUpdateSessionFromResponse.js +79 -0
  67. package/dist/src/fetch/middlewareUpdateSessionFromResponse.js.map +1 -0
  68. package/dist/src/functions/client.d.ts +52 -0
  69. package/dist/src/functions/client.d.ts.map +1 -0
  70. package/dist/src/functions/client.js +89 -0
  71. package/dist/src/functions/client.js.map +1 -0
  72. package/dist/src/functions/index.d.ts +43 -0
  73. package/dist/src/functions/index.d.ts.map +1 -0
  74. package/dist/src/functions/index.js +43 -0
  75. package/dist/src/functions/index.js.map +1 -0
  76. package/dist/src/graphql/client.d.ts +93 -0
  77. package/dist/src/graphql/client.d.ts.map +1 -0
  78. package/dist/src/graphql/client.js +66 -0
  79. package/dist/src/graphql/client.js.map +1 -0
  80. package/dist/src/graphql/index.d.ts +65 -0
  81. package/dist/src/graphql/index.d.ts.map +1 -0
  82. package/dist/src/graphql/index.js +65 -0
  83. package/dist/src/graphql/index.js.map +1 -0
  84. package/dist/src/index.d.ts +35 -0
  85. package/dist/src/index.d.ts.map +1 -0
  86. package/dist/src/index.js +45 -0
  87. package/dist/src/index.js.map +1 -0
  88. package/dist/src/nhost.d.ts +301 -0
  89. package/dist/src/nhost.d.ts.map +1 -0
  90. package/dist/src/nhost.js +323 -0
  91. package/dist/src/nhost.js.map +1 -0
  92. package/dist/src/session/index.d.ts +20 -0
  93. package/dist/src/session/index.d.ts.map +1 -0
  94. package/dist/src/session/index.js +19 -0
  95. package/dist/src/session/index.js.map +1 -0
  96. package/dist/src/session/refreshSession.d.ts +17 -0
  97. package/dist/src/session/refreshSession.d.ts.map +1 -0
  98. package/dist/src/session/refreshSession.js +120 -0
  99. package/dist/src/session/refreshSession.js.map +1 -0
  100. package/dist/src/session/session.d.ts +24 -0
  101. package/dist/src/session/session.d.ts.map +1 -0
  102. package/dist/src/session/session.js +48 -0
  103. package/dist/src/session/session.js.map +1 -0
  104. package/dist/src/session/storage.d.ts +62 -0
  105. package/dist/src/session/storage.d.ts.map +1 -0
  106. package/dist/src/session/storage.js +91 -0
  107. package/dist/src/session/storage.js.map +1 -0
  108. package/dist/src/session/storageBackend.d.ts +122 -0
  109. package/dist/src/session/storageBackend.d.ts.map +1 -0
  110. package/dist/src/session/storageBackend.js +145 -0
  111. package/dist/src/session/storageBackend.js.map +1 -0
  112. package/dist/src/storage/client.d.ts +546 -0
  113. package/dist/src/storage/client.d.ts.map +1 -0
  114. package/dist/src/storage/client.js +368 -0
  115. package/dist/src/storage/client.js.map +1 -0
  116. package/dist/src/storage/index.d.ts +37 -0
  117. package/dist/src/storage/index.d.ts.map +1 -0
  118. package/dist/src/storage/index.js +37 -0
  119. package/dist/src/storage/index.js.map +1 -0
  120. package/dist/tsconfig.tsbuildinfo +1 -0
  121. package/package.json +103 -59
  122. package/dist/clients/auth.d.ts +0 -8
  123. package/dist/clients/auth.d.ts.map +0 -1
  124. package/dist/clients/functions/index.d.ts +0 -107
  125. package/dist/clients/functions/index.d.ts.map +0 -1
  126. package/dist/clients/functions/types.d.ts +0 -28
  127. package/dist/clients/functions/types.d.ts.map +0 -1
  128. package/dist/clients/graphql.d.ts +0 -8
  129. package/dist/clients/graphql.d.ts.map +0 -1
  130. package/dist/clients/index.d.ts +0 -6
  131. package/dist/clients/index.d.ts.map +0 -1
  132. package/dist/clients/nhost.d.ts +0 -83
  133. package/dist/clients/nhost.d.ts.map +0 -1
  134. package/dist/clients/storage.d.ts +0 -8
  135. package/dist/clients/storage.d.ts.map +0 -1
  136. package/dist/index.cjs.js +0 -2
  137. package/dist/index.cjs.js.map +0 -1
  138. package/dist/index.d.ts +0 -6
  139. package/dist/index.d.ts.map +0 -1
  140. package/dist/index.esm.js +0 -356
  141. package/dist/index.esm.js.map +0 -1
  142. package/dist/utils/helpers.d.ts +0 -20
  143. package/dist/utils/helpers.d.ts.map +0 -1
  144. package/dist/utils/types.d.ts +0 -57
  145. package/dist/utils/types.d.ts.map +0 -1
  146. package/umd/nhost-js.umd.js +0 -22
  147. package/umd/nhost-js.umd.js.map +0 -1
@@ -0,0 +1,323 @@
1
+ import { generateServiceUrl } from "./";
2
+ import { createAPIClient as createAuthClient, } from "./auth";
3
+ import { attachAccessTokenMiddleware, sessionRefreshMiddleware, updateSessionFromResponseMiddleware, } from "./fetch";
4
+ import { createAPIClient as createFunctionsClient, } from "./functions";
5
+ import { createAPIClient as createGraphQLClient, } from "./graphql";
6
+ import { detectStorage, refreshSession, SessionStorage, } from "./session/";
7
+ import { createAPIClient as createStorageClient, } from "./storage";
8
+ /**
9
+ * Main client class that provides unified access to all Nhost services.
10
+ * This class serves as the central interface for interacting with Nhost's
11
+ * authentication, storage, GraphQL, and serverless functions capabilities.
12
+ */
13
+ export class NhostClient {
14
+ /**
15
+ * Authentication client providing methods for user sign-in, sign-up, and session management.
16
+ * Use this client to handle all authentication-related operations.
17
+ */
18
+ auth;
19
+ /**
20
+ * Storage client providing methods for file operations (upload, download, delete).
21
+ * Use this client to manage files in your Nhost storage.
22
+ */
23
+ storage;
24
+ /**
25
+ * GraphQL client providing methods for executing GraphQL operations against your Hasura backend.
26
+ * Use this client to query and mutate data in your database through GraphQL.
27
+ */
28
+ graphql;
29
+ /**
30
+ * Functions client providing methods for invoking serverless functions.
31
+ * Use this client to call your custom serverless functions deployed to Nhost.
32
+ */
33
+ functions;
34
+ /**
35
+ * Storage implementation used for persisting session information.
36
+ * This handles saving, retrieving, and managing authentication sessions across requests.
37
+ */
38
+ sessionStorage;
39
+ /**
40
+ * Create a new Nhost client. This constructor is reserved for advanced use cases.
41
+ * For typical usage, use [createClient](#createclient) or [createServerClient](#createserverclient) instead.
42
+ *
43
+ * @param auth - Authentication client instance
44
+ * @param storage - Storage client instance
45
+ * @param graphql - GraphQL client instance
46
+ * @param functions - Functions client instance
47
+ * @param sessionStorage - Storage implementation for session persistence
48
+ */
49
+ constructor(auth, storage, graphql, functions, sessionStorage) {
50
+ this.auth = auth;
51
+ this.storage = storage;
52
+ this.graphql = graphql;
53
+ this.functions = functions;
54
+ this.sessionStorage = sessionStorage;
55
+ }
56
+ /**
57
+ * Get the current session from storage.
58
+ * This method retrieves the authenticated user's session information if one exists.
59
+ *
60
+ * @returns The current session or null if no session exists
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * const session = nhost.getUserSession();
65
+ * if (session) {
66
+ * console.log('User is authenticated:', session.user.id);
67
+ * } else {
68
+ * console.log('No active session');
69
+ * }
70
+ * ```
71
+ */
72
+ getUserSession() {
73
+ return this.sessionStorage.get();
74
+ }
75
+ /**
76
+ * Refresh the session using the current refresh token
77
+ * in the storage and update the storage with the new session.
78
+ *
79
+ * This method can be used to proactively refresh tokens before they expire
80
+ * or to force a refresh when needed.
81
+ *
82
+ * @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.
83
+ *
84
+ * @returns The new session or null if there is currently no session or if refresh fails
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * // Refresh token if it's about to expire in the next 5 minutes
89
+ * const refreshedSession = await nhost.refreshSession(300);
90
+ *
91
+ * // Force refresh regardless of current token expiration
92
+ * const forcedRefresh = await nhost.refreshSession(0);
93
+ * ```
94
+ */
95
+ async refreshSession(marginSeconds = 60) {
96
+ return refreshSession(this.auth, this.sessionStorage, marginSeconds);
97
+ }
98
+ /**
99
+ * Clear the session from storage.
100
+ *
101
+ * This method removes the current authentication session, effectively logging out the user.
102
+ * Note that this is a client-side operation and doesn't invalidate the refresh token on
103
+ * the server, which can be done with `nhost.auth.signOut({refreshToken: session.refreshTokenId})`.
104
+ * If the middle `updateSessionFromResponseMiddleware` is used, the session will be removed
105
+ * from the storage automatically and calling this method is not necessary.
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * // Log out the user
110
+ * nhost.clearSession();
111
+ * ```
112
+ */
113
+ clearSession() {
114
+ this.sessionStorage.remove();
115
+ }
116
+ }
117
+ /**
118
+ * Creates and configures a new Nhost client instance optimized for client-side usage.
119
+ *
120
+ * This helper method instantiates a fully configured Nhost client by:
121
+ * - Instantiating the various service clients (auth, storage, functions and graphql)
122
+ * - Auto-detecting and configuring an appropriate session storage (localStorage in browsers, memory otherwise)
123
+ * - Setting up a sophisticated middleware chain for seamless authentication management:
124
+ * - Automatically refreshing tokens before they expire
125
+ * - Attaching authorization tokens to all service requests
126
+ * - Updating the session storage when new tokens are received
127
+ *
128
+ * This method includes automatic session refresh middleware, making it ideal for
129
+ * client-side applications where long-lived sessions are expected.
130
+ *
131
+ * @param options - Configuration options for the client
132
+ * @returns A configured Nhost client
133
+ *
134
+ * @example
135
+ * ```ts
136
+ * // Create client using Nhost cloud default URLs
137
+ * const nhost = createClient({
138
+ * subdomain: 'abcdefgh',
139
+ * region: 'eu-central-1'
140
+ * });
141
+ *
142
+ * // Create client with custom service URLs
143
+ * const customNhost = createClient({
144
+ * authUrl: 'https://auth.example.com',
145
+ * storageUrl: 'https://storage.example.com',
146
+ * graphqlUrl: 'https://graphql.example.com',
147
+ * functionsUrl: 'https://functions.example.com'
148
+ * });
149
+ *
150
+ * // Create client using cookies for storing the session
151
+ * import { CookieStorage } from "@nhost/nhost-js/session";
152
+ *
153
+ * const nhost = createClient({
154
+ * subdomain: 'abcdefgh',
155
+ * region: 'eu-central-1',
156
+ * storage: new CookieStorage({
157
+ * secure: import.meta.env.ENVIRONMENT === 'production',
158
+ * })
159
+ * });
160
+ * ```
161
+ */
162
+ export function createClient(options = {}) {
163
+ const { subdomain, region, authUrl, storageUrl, graphqlUrl, functionsUrl, storage = detectStorage(), } = options;
164
+ const sessionStorage = new SessionStorage(storage);
165
+ // Determine base URLs for each service
166
+ const authBaseUrl = generateServiceUrl("auth", subdomain, region, authUrl);
167
+ const storageBaseUrl = generateServiceUrl("storage", subdomain, region, storageUrl);
168
+ const graphqlBaseUrl = generateServiceUrl("graphql", subdomain, region, graphqlUrl);
169
+ const functionsBaseUrl = generateServiceUrl("functions", subdomain, region, functionsUrl);
170
+ // Create auth client
171
+ const auth = createAuthClient(authBaseUrl);
172
+ const mwChain = getMiddlewareChain(auth, sessionStorage, true);
173
+ for (const mw of mwChain) {
174
+ auth.pushChainFunction(mw);
175
+ }
176
+ // Create storage and graphql clients with the refresh and attach token middlewares
177
+ const storageClient = createStorageClient(storageBaseUrl, mwChain);
178
+ const graphqlClient = createGraphQLClient(graphqlBaseUrl, mwChain);
179
+ const functionsClient = createFunctionsClient(functionsBaseUrl, mwChain);
180
+ // Return an initialized NhostClient
181
+ return new NhostClient(auth, storageClient, graphqlClient, functionsClient, sessionStorage);
182
+ }
183
+ /**
184
+ * Creates and configures a new Nhost client instance optimized for server-side usage.
185
+ *
186
+ * This helper method instantiates a fully configured Nhost client specifically designed for:
187
+ * - Server components (in frameworks like Next.js or Remix)
188
+ * - API routes and middleware
189
+ * - Backend services and server-side rendering contexts
190
+ *
191
+ * Key differences from the standard client:
192
+ * - Requires explicit storage implementation (must be provided)
193
+ * - Disables automatic session refresh middleware (to prevent race conditions in server contexts)
194
+ * - Still attaches authorization tokens and updates session storage from responses
195
+ *
196
+ * The server client is ideal for short-lived request contexts where session tokens
197
+ * are passed in (like cookie-based authentication flows) and automatic refresh
198
+ * mechanisms could cause issues with concurrent requests.
199
+ *
200
+ * @param options - Configuration options for the server client (requires storage implementation)
201
+ * @returns A configured Nhost client optimized for server-side usage
202
+ *
203
+ * @example
204
+ * ```ts
205
+ * // Example with cookie storage for Next.js API route or server component
206
+ * import { cookies } from 'next/headers';
207
+ *
208
+ * const nhost = createServerClient({
209
+ * region: process.env["NHOST_REGION"] || "local",
210
+ * subdomain: process.env["NHOST_SUBDOMAIN"] || "local",
211
+ * storage: {
212
+ * // storage compatible with Next.js server components
213
+ * get: (): Session | null => {
214
+ * const s = cookieStore.get(key)?.value || null;
215
+ * if (!s) {
216
+ * return null;
217
+ * }
218
+ * const session = JSON.parse(s) as Session;
219
+ * return session;
220
+ * },
221
+ * set: (value: Session) => {
222
+ * cookieStore.set(key, JSON.stringify(value));
223
+ * },
224
+ * remove: () => {
225
+ * cookieStore.delete(key);
226
+ * },
227
+ * },
228
+ * });
229
+ *
230
+ * // Example with cookie storage for Next.js middleware
231
+ * const nhost = createServerClient({
232
+ * region: process.env["NHOST_REGION"] || "local",
233
+ * subdomain: process.env["NHOST_SUBDOMAIN"] || "local",
234
+ * storage: {
235
+ * // storage compatible with Next.js middleware
236
+ * get: (): Session | null => {
237
+ * const raw = request.cookies.get(key)?.value || null;
238
+ * if (!raw) {
239
+ * return null;
240
+ * }
241
+ * const session = JSON.parse(raw) as Session;
242
+ * return session;
243
+ * },
244
+ * set: (value: Session) => {
245
+ * response.cookies.set({
246
+ * name: key,
247
+ * value: JSON.stringify(value),
248
+ * path: "/",
249
+ * httpOnly: false, //if set to true we can't access it in the client
250
+ * secure: process.env.NODE_ENV === "production",
251
+ * sameSite: "lax",
252
+ * maxAge: 60 * 60 * 24 * 30, // 30 days in seconds
253
+ * });
254
+ * },
255
+ * remove: () => {
256
+ * response.cookies.delete(key);
257
+ * },
258
+ * },
259
+ * });
260
+ *
261
+ * // Example for express reading session from a cookie
262
+ *
263
+ * import express, { Request, Response } from "express";
264
+ * import cookieParser from "cookie-parser";
265
+ *
266
+ * app.use(cookieParser());
267
+ *
268
+ * const nhostClientFromCookies = (req: Request) => {
269
+ * return createServerClient({
270
+ * subdomain: "local",
271
+ * region: "local",
272
+ * storage: {
273
+ * get: (): Session | null => {
274
+ * const s = req.cookies.nhostSession || null;
275
+ * if (!s) {
276
+ * return null;
277
+ * }
278
+ * const session = JSON.parse(s) as Session;
279
+ * return session;
280
+ * },
281
+ * set: (_value: Session) => {
282
+ * throw new Error("It is easier to handle the session in the client");
283
+ * },
284
+ * remove: () => {
285
+ * throw new Error("It is easier to handle the session in the client");
286
+ * },
287
+ * },
288
+ * });
289
+ * };
290
+ * ```
291
+ */
292
+ export function createServerClient(options) {
293
+ const { subdomain, region, authUrl, storageUrl, graphqlUrl, functionsUrl, storage, } = options;
294
+ const sessionStorage = new SessionStorage(storage);
295
+ // Determine base URLs for each service
296
+ const authBaseUrl = generateServiceUrl("auth", subdomain, region, authUrl);
297
+ const storageBaseUrl = generateServiceUrl("storage", subdomain, region, storageUrl);
298
+ const graphqlBaseUrl = generateServiceUrl("graphql", subdomain, region, graphqlUrl);
299
+ const functionsBaseUrl = generateServiceUrl("functions", subdomain, region, functionsUrl);
300
+ // Create auth client
301
+ const auth = createAuthClient(authBaseUrl);
302
+ const mwChain = getMiddlewareChain(auth, sessionStorage, false);
303
+ for (const mw of mwChain) {
304
+ auth.pushChainFunction(mw);
305
+ }
306
+ // Create storage and graphql clients with the refresh and attach token middlewares
307
+ const storageClient = createStorageClient(storageBaseUrl, mwChain);
308
+ const graphqlClient = createGraphQLClient(graphqlBaseUrl, mwChain);
309
+ const functionsClient = createFunctionsClient(functionsBaseUrl, mwChain);
310
+ // Return an initialized NhostClient
311
+ return new NhostClient(auth, storageClient, graphqlClient, functionsClient, sessionStorage);
312
+ }
313
+ function getMiddlewareChain(auth, storage, autoRefresh) {
314
+ const mwChain = [
315
+ updateSessionFromResponseMiddleware(storage),
316
+ attachAccessTokenMiddleware(storage),
317
+ ];
318
+ if (autoRefresh) {
319
+ mwChain.unshift(sessionRefreshMiddleware(auth, storage));
320
+ }
321
+ return mwChain;
322
+ }
323
+ //# sourceMappingURL=nhost.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nhost.js","sourceRoot":"","sources":["../../src/nhost.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,IAAI,CAAC;AACxC,OAAO,EAEL,eAAe,IAAI,gBAAgB,GACpC,MAAM,QAAQ,CAAC;AAChB,OAAO,EACL,2BAA2B,EAE3B,wBAAwB,EACxB,mCAAmC,GACpC,MAAM,SAAS,CAAC;AACjB,OAAO,EACL,eAAe,IAAI,qBAAqB,GAEzC,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,eAAe,IAAI,mBAAmB,GAEvC,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,aAAa,EACb,cAAc,EAEd,cAAc,GAEf,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,eAAe,IAAI,mBAAmB,GAEvC,MAAM,WAAW,CAAC;AAEnB;;;;GAIG;AACH,MAAM,O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QAChB,OAAO,CAAC,OAAO,CAAC,wBAAwB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;IAC3D,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Session management module for Nhost authentication
3
+ *
4
+ * This module exports utilities for managing authentication sessions across
5
+ * different environments and storage backends. It provides:
6
+ *
7
+ * - Session storage abstractions for different environments
8
+ * - Session persistence and synchronization
9
+ * - Automatic token refresh mechanisms
10
+ *
11
+ * This is an advanced submodule of the Nhost SDK, primarily used internally but it is exposed
12
+ * for advanced use cases.
13
+ *
14
+ * @packageDocumentation
15
+ */
16
+ export { refreshSession } from "./refreshSession";
17
+ export type { DecodedToken, Session } from "./session";
18
+ export { detectStorage, type SessionChangeCallback, SessionStorage, } from "./storage";
19
+ export { CookieStorage, DEFAULT_SESSION_KEY, LocalStorage, MemoryStorage, type SessionStorageBackend, } from "./storageBackend";
20
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/session/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,YAAY,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACvD,OAAO,EACL,aAAa,EACb,KAAK,qBAAqB,EAC1B,cAAc,GACf,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,aAAa,EACb,mBAAmB,EACnB,YAAY,EACZ,aAAa,EACb,KAAK,qBAAqB,GAC3B,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Session management module for Nhost authentication
3
+ *
4
+ * This module exports utilities for managing authentication sessions across
5
+ * different environments and storage backends. It provides:
6
+ *
7
+ * - Session storage abstractions for different environments
8
+ * - Session persistence and synchronization
9
+ * - Automatic token refresh mechanisms
10
+ *
11
+ * This is an advanced submodule of the Nhost SDK, primarily used internally but it is exposed
12
+ * for advanced use cases.
13
+ *
14
+ * @packageDocumentation
15
+ */
16
+ export { refreshSession } from "./refreshSession";
17
+ export { detectStorage, SessionStorage, } from "./storage";
18
+ export { CookieStorage, DEFAULT_SESSION_KEY, LocalStorage, MemoryStorage, } from "./storageBackend";
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/session/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,OAAO,EACL,aAAa,EAEb,cAAc,GACf,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,aAAa,EACb,mBAAmB,EACnB,YAAY,EACZ,aAAa,GAEd,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1,17 @@
1
+ import type { Client as AuthClient } from "../auth";
2
+ import type { Session } from "./session";
3
+ import type { SessionStorage } from "./storage";
4
+ /**
5
+ * Refreshes the authentication session if needed
6
+ *
7
+ * This function checks if the current session needs to be refreshed based on
8
+ * the access token expiration time. If a refresh is needed, it will attempt to
9
+ * refresh the token using the provided auth client.
10
+ *
11
+ * @param auth - The authentication client to use for token refresh
12
+ * @param storage - The session storage implementation
13
+ * @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.
14
+ * @returns A promise that resolves to the current session (refreshed if needed) or null if no session exists
15
+ */
16
+ export declare const refreshSession: (auth: AuthClient, storage: SessionStorage, marginSeconds?: number) => Promise<Session | null>;
17
+ //# sourceMappingURL=refreshSession.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"refreshSession.d.ts","sourceRoot":"","sources":["../../../src/session/refreshSession.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,UAAU,EAAiB,MAAM,SAAS,CAAC;AAEnE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AA4BhD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,cAAc,GACzB,MAAM,UAAU,EAChB,SAAS,cAAc,EACvB,sBAAkB,KACjB,OAAO,CAAC,OAAO,GAAG,IAAI,CAmBxB,CAAC"}
@@ -0,0 +1,120 @@
1
+ class DummyLock {
2
+ async request(_name, _options,
3
+ // biome-ignore lint/suspicious/noExplicitAny: any
4
+ callback) {
5
+ return callback();
6
+ }
7
+ }
8
+ const lock = typeof navigator !== "undefined" && navigator.locks
9
+ ? navigator.locks
10
+ : new DummyLock();
11
+ /**
12
+ * Refreshes the authentication session if needed
13
+ *
14
+ * This function checks if the current session needs to be refreshed based on
15
+ * the access token expiration time. If a refresh is needed, it will attempt to
16
+ * refresh the token using the provided auth client.
17
+ *
18
+ * @param auth - The authentication client to use for token refresh
19
+ * @param storage - The session storage implementation
20
+ * @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.
21
+ * @returns A promise that resolves to the current session (refreshed if needed) or null if no session exists
22
+ */
23
+ export const refreshSession = async (auth, storage, marginSeconds = 60) => {
24
+ try {
25
+ return await _refreshSession(auth, storage, marginSeconds);
26
+ }
27
+ catch (error) {
28
+ try {
29
+ // we retry the refresh token in case of transient error
30
+ // or race conditions
31
+ console.warn("error refreshing session, retrying:", error);
32
+ return await _refreshSession(auth, storage, marginSeconds);
33
+ }
34
+ catch (error) {
35
+ const errResponse = error;
36
+ if (errResponse?.status === 401) {
37
+ // this probably means the refresh token is invalid
38
+ console.error("session probably expired");
39
+ storage.remove();
40
+ }
41
+ return null;
42
+ }
43
+ }
44
+ };
45
+ /**
46
+ * Internal implementation of the refresh session logic
47
+ *
48
+ * @param auth - The authentication client to use for token refresh
49
+ * @param storage - The session storage implementation
50
+ * @param marginSeconds - How many seconds before expiration to trigger a refresh
51
+ * @returns A promise that resolves to the current session (refreshed if needed) or null if no session exists
52
+ * @private
53
+ */
54
+ const _refreshSession = async (auth, storage, marginSeconds = 60) => {
55
+ const { session, needsRefresh, } = await lock.request("nhostSessionLock", { mode: "shared" }, async () => {
56
+ return _needsRefresh(storage, marginSeconds);
57
+ });
58
+ if (!session) {
59
+ return null; // No session found
60
+ }
61
+ if (!needsRefresh) {
62
+ return session; // No need to refresh
63
+ }
64
+ const refreshedSession = await lock.request("nhostSessionLock", { mode: "exclusive" }, async () => {
65
+ const { session, needsRefresh, sessionExpired } = _needsRefresh(storage, marginSeconds);
66
+ if (!session) {
67
+ return null; // No session found
68
+ }
69
+ if (!needsRefresh) {
70
+ return session; // No need to refresh
71
+ }
72
+ try {
73
+ const response = await auth.refreshToken({
74
+ refreshToken: session.refreshToken,
75
+ });
76
+ storage.set(response.body);
77
+ return response.body;
78
+ }
79
+ catch (error) {
80
+ if (!sessionExpired) {
81
+ return session;
82
+ }
83
+ throw error;
84
+ }
85
+ });
86
+ return refreshedSession;
87
+ };
88
+ /**
89
+ * Checks if the current session needs to be refreshed based on token expiration
90
+ *
91
+ * @param storage - The session storage implementation
92
+ * @param marginSeconds - How many seconds before expiration to trigger a refresh
93
+ * @returns An object containing the session, whether it needs refreshing, and whether it has expired
94
+ * @private
95
+ */
96
+ const _needsRefresh = (storage, marginSeconds = 60) => {
97
+ const session = storage.get();
98
+ if (!session) {
99
+ return { session: null, needsRefresh: false, sessionExpired: false };
100
+ }
101
+ if (!session.decodedToken || !session.decodedToken.exp) {
102
+ // if the session does not have a valid decoded token, treat it as expired
103
+ // as we can't determine its validity
104
+ return { session, needsRefresh: true, sessionExpired: true };
105
+ }
106
+ // Force refresh if marginSeconds is 0
107
+ if (marginSeconds === 0) {
108
+ return { session, needsRefresh: true, sessionExpired: false };
109
+ }
110
+ const currentTime = Date.now();
111
+ if (session.decodedToken.exp - currentTime > marginSeconds * 1000) {
112
+ return { session, needsRefresh: false, sessionExpired: false };
113
+ }
114
+ return {
115
+ session,
116
+ needsRefresh: true,
117
+ sessionExpired: session.decodedToken.exp < currentTime,
118
+ };
119
+ };
120
+ //# sourceMappingURL=refreshSession.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"refreshSession.js","sourceRoot":"","sources":["../../../src/session/refreshSession.ts"],"names":[],"mappings":"AAKA,MAAM,SAAS;IACb,KAAK,CAAC,OAAO,CACX,KAAa,EACb,QAA0C;IAC1C,kDAAkD;IAClD,QAA4B;QAE5B,OAAO,QAAQ,EAAE,CAAC;IACpB,CAAC;CACF;AAYD,MAAM,IAAI,GACR,OAAO,SAAS,KAAK,WAAW,IAAI,SAAS,CAAC,KAAK;IACjD,CAAC,CAAC,SAAS,CAAC,KAAK;IACjB,CAAC,CAAC,IAAI,SAAS,EAAE,CAAC;AAEtB;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,KAAK,EACjC,IAAgB,EAChB,OAAuB,EACvB,aAAa,GAAG,EAAE,EACO,EAAE;IAC3B,IAAI,CAAC;QACH,OAAO,MAAM,eAAe,CAAC,IAAI,EAAE,OAAO,EAAE,aAAa,CAAC,CAAC;IAC7D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC;YACH,wDAAwD;YACxD,qBAAqB;YACrB,OAAO,CAAC,IAAI,CAAC,qCAAqC,EAAE,KAAK,CAAC,CAAC;YAC3D,OAAO,MAAM,eAAe,CAAC,IAAI,EAAE,OAAO,EAAE,aAAa,CAAC,CAAC;QAC7D,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,WAAW,GAAG,KAAqC,CAAC;YAC1D,IAAI,WAAW,EAAE,MAAM,KAAK,GAAG,EAAE,CAAC;gBAChC,mDAAmD;gBACnD,OAAO,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;gBAC1C,OAAO,CAAC,MAAM,EAAE,CAAC;YACnB,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC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JWT token payload with processed timestamps and Hasura claims
4
+ */
5
+ export interface DecodedToken {
6
+ /** Token expiration time as Date object */
7
+ exp?: number;
8
+ /** Token issued at time as Date object */
9
+ iat?: number;
10
+ /** Token issuer */
11
+ iss?: string;
12
+ /** Token subject (user ID) */
13
+ sub?: string;
14
+ /** Hasura JWT claims with PostgreSQL arrays converted to JavaScript arrays */
15
+ "https://hasura.io/jwt/claims"?: Record<string, unknown>;
16
+ /** Any other JWT claims */
17
+ [key: string]: unknown;
18
+ }
19
+ export interface Session extends AuthSession {
20
+ /** Decoded JWT token payload with processed timestamps and Hasura claims */
21
+ decodedToken: DecodedToken;
22
+ }
23
+ export declare const decodeUserSession: (accessToken: string) => DecodedToken;
24
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../../src/session/session.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,SAAS,CAAC;AAEtD;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,2CAA2C;IAC3C,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,0CAA0C;IAC1C,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,mBAAmB;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,8BAA8B;IAC9B,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,8EAA8E;IAC9E,8BAA8B,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACzD,2BAA2B;IAC3B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,OAAQ,SAAQ,WAAW;IAC1C,4EAA4E;IAC5E,YAAY,EAAE,YAAY,CAAC;CAC5B;AAED,eAAO,MAAM,iBAAiB,GAAI,aAAa,MAAM,KAAG,YA8CvD,CAAC"}
@@ -0,0 +1,48 @@
1
+ export const decodeUserSession = (accessToken) => {
2
+ const s = accessToken.split(".");
3
+ if (s.length !== 3 || !s[1]) {
4
+ throw new Error("Invalid access token format");
5
+ }
6
+ const decodedToken = JSON.parse(typeof atob !== "undefined"
7
+ ? atob(s[1])
8
+ : Buffer.from(s[1], "base64").toString("utf-8"));
9
+ // Convert iat and exp to Date objects
10
+ const iat = typeof decodedToken["iat"] === "number"
11
+ ? decodedToken["iat"] * 1000 // Convert seconds to milliseconds
12
+ : undefined;
13
+ const exp = typeof decodedToken["exp"] === "number"
14
+ ? decodedToken["exp"] * 1000 // Convert seconds to milliseconds
15
+ : undefined;
16
+ // Process Hasura claims - dynamically convert PostgreSQL array notation to arrays
17
+ const hasuraClaims = decodedToken["https://hasura.io/jwt/claims"];
18
+ const processedClaims = hasuraClaims
19
+ ? Object.entries(hasuraClaims).reduce((acc, [key, value]) => {
20
+ if (typeof value === "string" && isPostgresArray(value)) {
21
+ acc[key] = parsePostgresArray(value);
22
+ }
23
+ else {
24
+ acc[key] = value;
25
+ }
26
+ return acc;
27
+ }, {})
28
+ : undefined;
29
+ return {
30
+ ...decodedToken,
31
+ iat,
32
+ exp,
33
+ "https://hasura.io/jwt/claims": processedClaims,
34
+ };
35
+ };
36
+ const isPostgresArray = (value) => {
37
+ return value.startsWith("{") && value.endsWith("}");
38
+ };
39
+ const parsePostgresArray = (value) => {
40
+ if (!value || value === "{}")
41
+ return [];
42
+ // Remove curly braces and split by comma, handling quoted values
43
+ return value
44
+ .slice(1, -1)
45
+ .split(",")
46
+ .map((item) => item.trim().replace(/^"(.*)"$/, "$1"));
47
+ };
48
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/session/session.ts"],"names":[],"mappings":"AAyBA,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,WAAmB,EAAgB,EAAE;IACrE,MAAM,CAAC,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACjC,IAAI,CAAC,CAAC,MAAM,KAAK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