@nhost/nhost-js 4.0.1 → 4.1.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/middlewareWithAdminSession-BtFo6WUj.js +2 -0
- package/dist/middlewareWithAdminSession-BtFo6WUj.js.map +1 -0
- package/dist/middlewareWithAdminSession-w7fkl0J9.mjs +106 -0
- package/dist/middlewareWithAdminSession-w7fkl0J9.mjs.map +1 -0
- package/dist/nhost-js/auth.cjs.js +1 -1
- package/dist/nhost-js/auth.cjs.js.map +1 -1
- package/dist/nhost-js/auth.es.js +48 -0
- package/dist/nhost-js/auth.es.js.map +1 -1
- package/dist/nhost-js/fetch.cjs.js +1 -1
- package/dist/nhost-js/fetch.cjs.js.map +1 -1
- package/dist/nhost-js/fetch.es.js +19 -79
- package/dist/nhost-js/fetch.es.js.map +1 -1
- package/dist/nhost-js/functions.cjs.js +1 -1
- package/dist/nhost-js/functions.cjs.js.map +1 -1
- package/dist/nhost-js/functions.es.js +7 -2
- package/dist/nhost-js/functions.es.js.map +1 -1
- package/dist/nhost-js/graphql.cjs.js +1 -1
- package/dist/nhost-js/graphql.cjs.js.map +1 -1
- package/dist/nhost-js/graphql.es.js +7 -2
- package/dist/nhost-js/graphql.es.js.map +1 -1
- package/dist/nhost-js/session.es.js +1 -1
- package/dist/nhost-js/storage.cjs.js.map +1 -1
- package/dist/nhost-js/storage.es.js.map +1 -1
- package/dist/nhost-js.cjs.js +1 -1
- package/dist/nhost-js.cjs.js.map +1 -1
- package/dist/nhost-js.es.js +78 -65
- package/dist/nhost-js.es.js.map +1 -1
- package/dist/nhost-js.umd.js +1 -1
- package/dist/nhost-js.umd.js.map +1 -1
- package/dist/refreshSession-Bw715ZmX.js.map +1 -1
- package/dist/{refreshSession-WwGlzgtM.mjs → refreshSession-CG8GIEun.mjs} +5 -2
- package/dist/refreshSession-CG8GIEun.mjs.map +1 -0
- package/dist/src/auth/client.d.ts +72 -1
- package/dist/src/auth/client.d.ts.map +1 -1
- package/dist/src/auth/client.js +56 -0
- package/dist/src/auth/client.js.map +1 -1
- package/dist/src/fetch/index.d.ts +15 -0
- package/dist/src/fetch/index.d.ts.map +1 -1
- package/dist/src/fetch/index.js +15 -0
- package/dist/src/fetch/index.js.map +1 -1
- package/dist/src/fetch/middlewareUpdateSessionFromResponse.js +1 -1
- package/dist/src/fetch/middlewareUpdateSessionFromResponse.js.map +1 -1
- package/dist/src/fetch/middlewareWithAdminSession.d.ts +87 -0
- package/dist/src/fetch/middlewareWithAdminSession.d.ts.map +1 -0
- package/dist/src/fetch/middlewareWithAdminSession.js +79 -0
- package/dist/src/fetch/middlewareWithAdminSession.js.map +1 -0
- package/dist/src/fetch/middlewareWithHeaders.d.ts +23 -0
- package/dist/src/fetch/middlewareWithHeaders.d.ts.map +1 -0
- package/dist/src/fetch/middlewareWithHeaders.js +31 -0
- package/dist/src/fetch/middlewareWithHeaders.js.map +1 -0
- package/dist/src/fetch/middlewareWithRole.d.ts +44 -0
- package/dist/src/fetch/middlewareWithRole.d.ts.map +1 -0
- package/dist/src/fetch/middlewareWithRole.js +50 -0
- package/dist/src/fetch/middlewareWithRole.js.map +1 -0
- package/dist/src/functions/client.d.ts +6 -1
- package/dist/src/functions/client.d.ts.map +1 -1
- package/dist/src/functions/client.js +6 -1
- package/dist/src/functions/client.js.map +1 -1
- package/dist/src/graphql/client.d.ts +4 -0
- package/dist/src/graphql/client.d.ts.map +1 -1
- package/dist/src/graphql/client.js +6 -1
- package/dist/src/graphql/client.js.map +1 -1
- package/dist/src/index.d.ts +12 -2
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +12 -2
- package/dist/src/index.js.map +1 -1
- package/dist/src/nhost.d.ts +109 -0
- package/dist/src/nhost.d.ts.map +1 -1
- package/dist/src/nhost.js +167 -49
- package/dist/src/nhost.js.map +1 -1
- package/dist/src/session/refreshSession.d.ts.map +1 -1
- package/dist/src/session/refreshSession.js +3 -1
- package/dist/src/session/refreshSession.js.map +1 -1
- package/dist/src/storage/client.d.ts +3 -0
- package/dist/src/storage/client.d.ts.map +1 -1
- package/dist/src/storage/client.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
- package/dist/refreshSession-WwGlzgtM.mjs.map +0 -1
package/dist/nhost-js.es.js
CHANGED
|
@@ -1,10 +1,55 @@
|
|
|
1
1
|
import { createAPIClient } from "./nhost-js/auth.es.js";
|
|
2
|
-
import { updateSessionFromResponseMiddleware, attachAccessTokenMiddleware
|
|
2
|
+
import { w as withAdminSessionMiddleware, s as sessionRefreshMiddleware, u as updateSessionFromResponseMiddleware, a as attachAccessTokenMiddleware } from "./middlewareWithAdminSession-w7fkl0J9.mjs";
|
|
3
3
|
import { createAPIClient as createAPIClient$3 } from "./nhost-js/functions.es.js";
|
|
4
4
|
import { createAPIClient as createAPIClient$2 } from "./nhost-js/graphql.es.js";
|
|
5
|
-
import { r as refreshSession } from "./refreshSession-
|
|
5
|
+
import { r as refreshSession } from "./refreshSession-CG8GIEun.mjs";
|
|
6
6
|
import { detectStorage, SessionStorage } from "./nhost-js/session.es.js";
|
|
7
7
|
import { createAPIClient as createAPIClient$1 } from "./nhost-js/storage.es.js";
|
|
8
|
+
const withClientSideSessionMiddleware = ({
|
|
9
|
+
auth,
|
|
10
|
+
storage,
|
|
11
|
+
graphql,
|
|
12
|
+
functions,
|
|
13
|
+
sessionStorage
|
|
14
|
+
}) => {
|
|
15
|
+
const mwChain = [
|
|
16
|
+
sessionRefreshMiddleware(auth, sessionStorage),
|
|
17
|
+
updateSessionFromResponseMiddleware(sessionStorage),
|
|
18
|
+
attachAccessTokenMiddleware(sessionStorage)
|
|
19
|
+
];
|
|
20
|
+
for (const mw of mwChain) {
|
|
21
|
+
auth.pushChainFunction(mw);
|
|
22
|
+
storage.pushChainFunction(mw);
|
|
23
|
+
graphql.pushChainFunction(mw);
|
|
24
|
+
functions.pushChainFunction(mw);
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
const withServerSideSessionMiddleware = ({
|
|
28
|
+
auth,
|
|
29
|
+
storage,
|
|
30
|
+
graphql,
|
|
31
|
+
functions,
|
|
32
|
+
sessionStorage
|
|
33
|
+
}) => {
|
|
34
|
+
const mwChain = [
|
|
35
|
+
updateSessionFromResponseMiddleware(sessionStorage),
|
|
36
|
+
attachAccessTokenMiddleware(sessionStorage)
|
|
37
|
+
];
|
|
38
|
+
for (const mw of mwChain) {
|
|
39
|
+
auth.pushChainFunction(mw);
|
|
40
|
+
storage.pushChainFunction(mw);
|
|
41
|
+
graphql.pushChainFunction(mw);
|
|
42
|
+
functions.pushChainFunction(mw);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
function withAdminSession(adminSession) {
|
|
46
|
+
return ({ storage, graphql, functions }) => {
|
|
47
|
+
const adminMiddleware = withAdminSessionMiddleware(adminSession);
|
|
48
|
+
storage.pushChainFunction(adminMiddleware);
|
|
49
|
+
graphql.pushChainFunction(adminMiddleware);
|
|
50
|
+
functions.pushChainFunction(adminMiddleware);
|
|
51
|
+
};
|
|
52
|
+
}
|
|
8
53
|
class NhostClient {
|
|
9
54
|
/**
|
|
10
55
|
* Authentication client providing methods for user sign-in, sign-up, and session management.
|
|
@@ -109,7 +154,7 @@ class NhostClient {
|
|
|
109
154
|
this.sessionStorage.remove();
|
|
110
155
|
}
|
|
111
156
|
}
|
|
112
|
-
function
|
|
157
|
+
function createNhostClient(options = {}) {
|
|
113
158
|
const {
|
|
114
159
|
subdomain,
|
|
115
160
|
region,
|
|
@@ -117,7 +162,8 @@ function createClient(options = {}) {
|
|
|
117
162
|
storageUrl,
|
|
118
163
|
graphqlUrl,
|
|
119
164
|
functionsUrl,
|
|
120
|
-
storage = detectStorage()
|
|
165
|
+
storage = detectStorage(),
|
|
166
|
+
configure = []
|
|
121
167
|
} = options;
|
|
122
168
|
const sessionStorage = new SessionStorage(storage);
|
|
123
169
|
const authBaseUrl = generateServiceUrl("auth", subdomain, region, authUrl);
|
|
@@ -140,13 +186,18 @@ function createClient(options = {}) {
|
|
|
140
186
|
functionsUrl
|
|
141
187
|
);
|
|
142
188
|
const auth = createAPIClient(authBaseUrl);
|
|
143
|
-
const
|
|
144
|
-
|
|
145
|
-
|
|
189
|
+
const storageClient = createAPIClient$1(storageBaseUrl, []);
|
|
190
|
+
const graphqlClient = createAPIClient$2(graphqlBaseUrl, []);
|
|
191
|
+
const functionsClient = createAPIClient$3(functionsBaseUrl, []);
|
|
192
|
+
for (const configFn of configure) {
|
|
193
|
+
configFn({
|
|
194
|
+
auth,
|
|
195
|
+
storage: storageClient,
|
|
196
|
+
graphql: graphqlClient,
|
|
197
|
+
functions: functionsClient,
|
|
198
|
+
sessionStorage
|
|
199
|
+
});
|
|
146
200
|
}
|
|
147
|
-
const storageClient = createAPIClient$1(storageBaseUrl, mwChain);
|
|
148
|
-
const graphqlClient = createAPIClient$2(graphqlBaseUrl, mwChain);
|
|
149
|
-
const functionsClient = createAPIClient$3(functionsBaseUrl, mwChain);
|
|
150
201
|
return new NhostClient(
|
|
151
202
|
auth,
|
|
152
203
|
storageClient,
|
|
@@ -155,61 +206,19 @@ function createClient(options = {}) {
|
|
|
155
206
|
sessionStorage
|
|
156
207
|
);
|
|
157
208
|
}
|
|
158
|
-
function
|
|
159
|
-
const
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
functionsUrl,
|
|
166
|
-
storage
|
|
167
|
-
} = options;
|
|
168
|
-
const sessionStorage = new SessionStorage(storage);
|
|
169
|
-
const authBaseUrl = generateServiceUrl("auth", subdomain, region, authUrl);
|
|
170
|
-
const storageBaseUrl = generateServiceUrl(
|
|
171
|
-
"storage",
|
|
172
|
-
subdomain,
|
|
173
|
-
region,
|
|
174
|
-
storageUrl
|
|
175
|
-
);
|
|
176
|
-
const graphqlBaseUrl = generateServiceUrl(
|
|
177
|
-
"graphql",
|
|
178
|
-
subdomain,
|
|
179
|
-
region,
|
|
180
|
-
graphqlUrl
|
|
181
|
-
);
|
|
182
|
-
const functionsBaseUrl = generateServiceUrl(
|
|
183
|
-
"functions",
|
|
184
|
-
subdomain,
|
|
185
|
-
region,
|
|
186
|
-
functionsUrl
|
|
187
|
-
);
|
|
188
|
-
const auth = createAPIClient(authBaseUrl);
|
|
189
|
-
const mwChain = getMiddlewareChain(auth, sessionStorage, false);
|
|
190
|
-
for (const mw of mwChain) {
|
|
191
|
-
auth.pushChainFunction(mw);
|
|
192
|
-
}
|
|
193
|
-
const storageClient = createAPIClient$1(storageBaseUrl, mwChain);
|
|
194
|
-
const graphqlClient = createAPIClient$2(graphqlBaseUrl, mwChain);
|
|
195
|
-
const functionsClient = createAPIClient$3(functionsBaseUrl, mwChain);
|
|
196
|
-
return new NhostClient(
|
|
197
|
-
auth,
|
|
198
|
-
storageClient,
|
|
199
|
-
graphqlClient,
|
|
200
|
-
functionsClient,
|
|
201
|
-
sessionStorage
|
|
202
|
-
);
|
|
209
|
+
function createClient(options = {}) {
|
|
210
|
+
const storage = options.storage ?? detectStorage();
|
|
211
|
+
return createNhostClient({
|
|
212
|
+
...options,
|
|
213
|
+
storage,
|
|
214
|
+
configure: [withClientSideSessionMiddleware, ...options.configure ?? []]
|
|
215
|
+
});
|
|
203
216
|
}
|
|
204
|
-
function
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
if (autoRefresh) {
|
|
210
|
-
mwChain.unshift(sessionRefreshMiddleware(auth, storage));
|
|
211
|
-
}
|
|
212
|
-
return mwChain;
|
|
217
|
+
function createServerClient(options) {
|
|
218
|
+
return createNhostClient({
|
|
219
|
+
...options,
|
|
220
|
+
configure: [withServerSideSessionMiddleware, ...options.configure ?? []]
|
|
221
|
+
});
|
|
213
222
|
}
|
|
214
223
|
const generateServiceUrl = (serviceType, subdomain, region, customUrl) => {
|
|
215
224
|
if (customUrl) {
|
|
@@ -222,7 +231,11 @@ const generateServiceUrl = (serviceType, subdomain, region, customUrl) => {
|
|
|
222
231
|
};
|
|
223
232
|
export {
|
|
224
233
|
createClient,
|
|
234
|
+
createNhostClient,
|
|
225
235
|
createServerClient,
|
|
226
|
-
generateServiceUrl
|
|
236
|
+
generateServiceUrl,
|
|
237
|
+
withAdminSession,
|
|
238
|
+
withClientSideSessionMiddleware,
|
|
239
|
+
withServerSideSessionMiddleware
|
|
227
240
|
};
|
|
228
241
|
//# sourceMappingURL=nhost-js.es.js.map
|
package/dist/nhost-js.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nhost-js.es.js","sources":["../src/nhost.ts","../src/index.ts"],"sourcesContent":["import { generateServiceUrl } from \"./\";\nimport {\n type Client as AuthClient,\n createAPIClient as createAuthClient,\n} from \"./auth\";\nimport {\n attachAccessTokenMiddleware,\n type ChainFunction,\n sessionRefreshMiddleware,\n updateSessionFromResponseMiddleware,\n} from \"./fetch\";\nimport {\n createAPIClient as createFunctionsClient,\n type Client as FunctionsClient,\n} from \"./functions\";\nimport {\n createAPIClient as createGraphQLClient,\n type Client as GraphQLClient,\n} from \"./graphql\";\nimport {\n detectStorage,\n refreshSession,\n type Session,\n SessionStorage,\n type SessionStorageBackend,\n} from \"./session/\";\nimport {\n createAPIClient as createStorageClient,\n type Client as StorageClient,\n} from \"./storage\";\n\n/**\n * Main client class that provides unified access to all Nhost services.\n * This class serves as the central interface for interacting with Nhost's\n * authentication, storage, GraphQL, and serverless functions capabilities.\n */\nexport class NhostClient {\n /**\n * Authentication client providing methods for user sign-in, sign-up, and session management.\n * Use this client to handle all authentication-related operations.\n */\n auth: AuthClient;\n\n /**\n * Storage client providing methods for file operations (upload, download, delete).\n * Use this client to manage files in your Nhost storage.\n */\n storage: StorageClient;\n\n /**\n * GraphQL client providing methods for executing GraphQL operations against your Hasura backend.\n * Use this client to query and mutate data in your database through GraphQL.\n */\n graphql: GraphQLClient;\n\n /**\n * Functions client providing methods for invoking serverless functions.\n * Use this client to call your custom serverless functions deployed to Nhost.\n */\n functions: FunctionsClient;\n\n /**\n * Storage implementation used for persisting session information.\n * This handles saving, retrieving, and managing authentication sessions across requests.\n */\n sessionStorage: SessionStorage;\n\n /**\n * Create a new Nhost client. This constructor is reserved for advanced use cases.\n * For typical usage, use [createClient](#createclient) or [createServerClient](#createserverclient) instead.\n *\n * @param auth - Authentication client instance\n * @param storage - Storage client instance\n * @param graphql - GraphQL client instance\n * @param functions - Functions client instance\n * @param sessionStorage - Storage implementation for session persistence\n */\n constructor(\n auth: AuthClient,\n storage: StorageClient,\n graphql: GraphQLClient,\n functions: FunctionsClient,\n sessionStorage: SessionStorage,\n ) {\n this.auth = auth;\n this.storage = storage;\n this.graphql = graphql;\n this.functions = functions;\n this.sessionStorage = sessionStorage;\n }\n\n /**\n * Get the current session from storage.\n * This method retrieves the authenticated user's session information if one exists.\n *\n * @returns The current session or null if no session exists\n *\n * @example\n * ```ts\n * const session = nhost.getUserSession();\n * if (session) {\n * console.log('User is authenticated:', session.user.id);\n * } else {\n * console.log('No active session');\n * }\n * ```\n */\n getUserSession(): Session | null {\n return this.sessionStorage.get();\n }\n\n /**\n * Refresh the session using the current refresh token\n * in the storage and update the storage with the new session.\n *\n * This method can be used to proactively refresh tokens before they expire\n * or to force a refresh when needed.\n *\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 *\n * @returns The new session or null if there is currently no session or if refresh fails\n *\n * @example\n * ```ts\n * // Refresh token if it's about to expire in the next 5 minutes\n * const refreshedSession = await nhost.refreshSession(300);\n *\n * // Force refresh regardless of current token expiration\n * const forcedRefresh = await nhost.refreshSession(0);\n * ```\n */\n async refreshSession(marginSeconds = 60): Promise<Session | null> {\n return refreshSession(this.auth, this.sessionStorage, marginSeconds);\n }\n\n /**\n * Clear the session from storage.\n *\n * This method removes the current authentication session, effectively logging out the user.\n * Note that this is a client-side operation and doesn't invalidate the refresh token on\n * the server, which can be done with `nhost.auth.signOut({refreshToken: session.refreshTokenId})`.\n * If the middle `updateSessionFromResponseMiddleware` is used, the session will be removed\n * from the storage automatically and calling this method is not necessary.\n *\n * @example\n * ```ts\n * // Log out the user\n * nhost.clearSession();\n * ```\n */\n clearSession(): void {\n this.sessionStorage.remove();\n }\n}\n\n/**\n * Configuration options for creating an Nhost client\n */\nexport interface NhostClientOptions {\n /**\n * Nhost project subdomain (e.g., 'abcdefgh'). Used to construct the base URL for services for the Nhost cloud.\n */\n subdomain?: string;\n\n /**\n * Nhost region (e.g., 'eu-central-1'). Used to construct the base URL for services for the Nhost cloud.\n */\n region?: string;\n\n /**\n * Complete base URL for the auth service (overrides subdomain/region)\n */\n authUrl?: string;\n\n /**\n * Complete base URL for the storage service (overrides subdomain/region)\n */\n storageUrl?: string;\n\n /**\n * Complete base URL for the GraphQL service (overrides subdomain/region)\n */\n graphqlUrl?: string;\n\n /**\n * Complete base URL for the functions service (overrides subdomain/region)\n */\n functionsUrl?: string;\n\n /**\n * Storage backend to use for session persistence. If not provided, the SDK will\n * default to localStorage in the browser or memory in other environments.\n */\n storage?: SessionStorageBackend;\n}\n\n/**\n * Creates and configures a new Nhost client instance optimized for client-side usage.\n *\n * This helper method instantiates a fully configured Nhost client by:\n * - Instantiating the various service clients (auth, storage, functions and graphql)\n * - Auto-detecting and configuring an appropriate session storage (localStorage in browsers, memory otherwise)\n * - Setting up a sophisticated middleware chain for seamless authentication management:\n * - Automatically refreshing tokens before they expire\n * - Attaching authorization tokens to all service requests\n * - Updating the session storage when new tokens are received\n *\n * This method includes automatic session refresh middleware, making it ideal for\n * client-side applications where long-lived sessions are expected.\n *\n * @param options - Configuration options for the client\n * @returns A configured Nhost client\n *\n * @example\n * ```ts\n * // Create client using Nhost cloud default URLs\n * const nhost = createClient({\n * subdomain: 'abcdefgh',\n * region: 'eu-central-1'\n * });\n *\n * // Create client with custom service URLs\n * const customNhost = createClient({\n * authUrl: 'https://auth.example.com',\n * storageUrl: 'https://storage.example.com',\n * graphqlUrl: 'https://graphql.example.com',\n * functionsUrl: 'https://functions.example.com'\n * });\n *\n * // Create client using cookies for storing the session\n * import { CookieStorage } from \"@nhost/nhost-js/session\";\n *\n * const nhost = createClient({\n * subdomain: 'abcdefgh',\n * region: 'eu-central-1',\n * storage: new CookieStorage({\n * secure: import.meta.env.ENVIRONMENT === 'production',\n * })\n * });\n * ```\n */\nexport function createClient(options: NhostClientOptions = {}): NhostClient {\n const {\n subdomain,\n region,\n authUrl,\n storageUrl,\n graphqlUrl,\n functionsUrl,\n storage = detectStorage(),\n } = options;\n\n const sessionStorage = new SessionStorage(storage);\n\n // Determine base URLs for each service\n const authBaseUrl = generateServiceUrl(\"auth\", subdomain, region, authUrl);\n const storageBaseUrl = generateServiceUrl(\n \"storage\",\n subdomain,\n region,\n storageUrl,\n );\n const graphqlBaseUrl = generateServiceUrl(\n \"graphql\",\n subdomain,\n region,\n graphqlUrl,\n );\n\n const functionsBaseUrl = generateServiceUrl(\n \"functions\",\n subdomain,\n region,\n functionsUrl,\n );\n\n // Create auth client\n const auth = createAuthClient(authBaseUrl);\n\n const mwChain = getMiddlewareChain(auth, sessionStorage, true);\n\n for (const mw of mwChain) {\n auth.pushChainFunction(mw);\n }\n\n // Create storage and graphql clients with the refresh and attach token middlewares\n const storageClient = createStorageClient(storageBaseUrl, mwChain);\n const graphqlClient = createGraphQLClient(graphqlBaseUrl, mwChain);\n const functionsClient = createFunctionsClient(functionsBaseUrl, mwChain);\n\n // Return an initialized NhostClient\n return new NhostClient(\n auth,\n storageClient,\n graphqlClient,\n functionsClient,\n sessionStorage,\n );\n}\n\nexport interface NhostServerClientOptions extends NhostClientOptions {\n /**\n * Storage backend to use for session persistence in server environments.\n * Unlike the base options, this field is required for server-side usage\n * as the SDK cannot auto-detect an appropriate storage mechanism.\n */\n storage: SessionStorageBackend;\n}\n\n/**\n * Creates and configures a new Nhost client instance optimized for server-side usage.\n *\n * This helper method instantiates a fully configured Nhost client specifically designed for:\n * - Server components (in frameworks like Next.js or Remix)\n * - API routes and middleware\n * - Backend services and server-side rendering contexts\n *\n * Key differences from the standard client:\n * - Requires explicit storage implementation (must be provided)\n * - Disables automatic session refresh middleware (to prevent race conditions in server contexts)\n * - Still attaches authorization tokens and updates session storage from responses\n *\n * The server client is ideal for short-lived request contexts where session tokens\n * are passed in (like cookie-based authentication flows) and automatic refresh\n * mechanisms could cause issues with concurrent requests.\n *\n * @param options - Configuration options for the server client (requires storage implementation)\n * @returns A configured Nhost client optimized for server-side usage\n *\n * @example\n * ```ts\n * // Example with cookie storage for Next.js API route or server component\n * import { cookies } from 'next/headers';\n *\n * const nhost = createServerClient({\n * region: process.env[\"NHOST_REGION\"] || \"local\",\n * subdomain: process.env[\"NHOST_SUBDOMAIN\"] || \"local\",\n * storage: {\n * // storage compatible with Next.js server components\n * get: (): Session | null => {\n * const s = cookieStore.get(key)?.value || null;\n * if (!s) {\n * return null;\n * }\n * const session = JSON.parse(s) as Session;\n * return session;\n * },\n * set: (value: Session) => {\n * cookieStore.set(key, JSON.stringify(value));\n * },\n * remove: () => {\n * cookieStore.delete(key);\n * },\n * },\n * });\n *\n * // Example with cookie storage for Next.js middleware\n * const nhost = createServerClient({\n * region: process.env[\"NHOST_REGION\"] || \"local\",\n * subdomain: process.env[\"NHOST_SUBDOMAIN\"] || \"local\",\n * storage: {\n * // storage compatible with Next.js middleware\n * get: (): Session | null => {\n * const raw = request.cookies.get(key)?.value || null;\n * if (!raw) {\n * return null;\n * }\n * const session = JSON.parse(raw) as Session;\n * return session;\n * },\n * set: (value: Session) => {\n * response.cookies.set({\n * name: key,\n * value: JSON.stringify(value),\n * path: \"/\",\n * httpOnly: false, //if set to true we can't access it in the client\n * secure: process.env.NODE_ENV === \"production\",\n * sameSite: \"lax\",\n * maxAge: 60 * 60 * 24 * 30, // 30 days in seconds\n * });\n * },\n * remove: () => {\n * response.cookies.delete(key);\n * },\n * },\n * });\n *\n * // Example for express reading session from a cookie\n *\n * import express, { Request, Response } from \"express\";\n * import cookieParser from \"cookie-parser\";\n *\n * app.use(cookieParser());\n *\n * const nhostClientFromCookies = (req: Request) => {\n * return createServerClient({\n * subdomain: \"local\",\n * region: \"local\",\n * storage: {\n * get: (): Session | null => {\n * const s = req.cookies.nhostSession || null;\n * if (!s) {\n * return null;\n * }\n * const session = JSON.parse(s) as Session;\n * return session;\n * },\n * set: (_value: Session) => {\n * throw new Error(\"It is easier to handle the session in the client\");\n * },\n * remove: () => {\n * throw new Error(\"It is easier to handle the session in the client\");\n * },\n * },\n * });\n * };\n * ```\n */\nexport function createServerClient(\n options: NhostServerClientOptions,\n): NhostClient {\n const {\n subdomain,\n region,\n authUrl,\n storageUrl,\n graphqlUrl,\n functionsUrl,\n storage,\n } = options;\n const sessionStorage = new SessionStorage(storage);\n\n // Determine base URLs for each service\n const authBaseUrl = generateServiceUrl(\"auth\", subdomain, region, authUrl);\n const storageBaseUrl = generateServiceUrl(\n \"storage\",\n subdomain,\n region,\n storageUrl,\n );\n const graphqlBaseUrl = generateServiceUrl(\n \"graphql\",\n subdomain,\n region,\n graphqlUrl,\n );\n\n const functionsBaseUrl = generateServiceUrl(\n \"functions\",\n subdomain,\n region,\n functionsUrl,\n );\n\n // Create auth client\n const auth = createAuthClient(authBaseUrl);\n\n const mwChain = getMiddlewareChain(auth, sessionStorage, false);\n\n for (const mw of mwChain) {\n auth.pushChainFunction(mw);\n }\n\n // Create storage and graphql clients with the refresh and attach token middlewares\n const storageClient = createStorageClient(storageBaseUrl, mwChain);\n const graphqlClient = createGraphQLClient(graphqlBaseUrl, mwChain);\n const functionsClient = createFunctionsClient(functionsBaseUrl, mwChain);\n\n // Return an initialized NhostClient\n return new NhostClient(\n auth,\n storageClient,\n graphqlClient,\n functionsClient,\n sessionStorage,\n );\n}\n\nfunction getMiddlewareChain(\n auth: AuthClient,\n storage: SessionStorage,\n autoRefresh: boolean,\n): ChainFunction[] {\n const mwChain = [\n updateSessionFromResponseMiddleware(storage),\n attachAccessTokenMiddleware(storage),\n ];\n\n if (autoRefresh) {\n mwChain.unshift(sessionRefreshMiddleware(auth, storage));\n }\n\n return mwChain;\n}\n","/**\n * Main entry point for the Nhost JavaScript SDK.\n *\n * This package provides a unified client for interacting with Nhost services:\n * - Authentication\n * - Storage\n * - GraphQL\n * - Functions\n *\n * ## Import\n *\n * ```ts\n * import { createClient } from \"@nhost/nhost-js\";\n * ```\n *\n * ## Usage\n *\n * Create a client instance to interact with Nhost services:\n *\n * {@includeCode ./__tests__/docstrings.test.ts:11-115}\n *\n * @packageDocumentation\n */\n\nexport {\n createClient,\n createServerClient,\n type NhostClient,\n type NhostClientOptions,\n type NhostServerClientOptions,\n} from \"./nhost\";\n\n/**\n * Generates a base URL for a Nhost service based on configuration\n *\n * @param serviceType - Type of service (auth, storage, graphql, functions)\n * @param subdomain - Nhost project subdomain\n * @param region - Nhost region\n * @param customUrl - Custom URL override if provided\n * @returns The base URL for the service\n */\nexport const generateServiceUrl = (\n serviceType: \"auth\" | \"storage\" | \"graphql\" | \"functions\",\n subdomain?: string,\n region?: string,\n customUrl?: string,\n): string => {\n if (customUrl) {\n return customUrl;\n } else if (subdomain && region) {\n return `https://${subdomain}.${serviceType}.${region}.nhost.run/v1`;\n } else {\n return `https://local.${serviceType}.local.nhost.run/v1`;\n }\n};\n"],"names":["createAuthClient","createStorageClient","createGraphQLClient","createFunctionsClient"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"nhost-js.es.js","sources":["../src/nhost.ts","../src/index.ts"],"sourcesContent":["import { generateServiceUrl } from \"./\";\nimport {\n type Client as AuthClient,\n createAPIClient as createAuthClient,\n} from \"./auth\";\nimport {\n type AdminSessionOptions,\n attachAccessTokenMiddleware,\n type ChainFunction,\n sessionRefreshMiddleware,\n updateSessionFromResponseMiddleware,\n withAdminSessionMiddleware,\n} from \"./fetch\";\nimport {\n createAPIClient as createFunctionsClient,\n type Client as FunctionsClient,\n} from \"./functions\";\nimport {\n createAPIClient as createGraphQLClient,\n type Client as GraphQLClient,\n} from \"./graphql\";\nimport {\n detectStorage,\n refreshSession,\n type Session,\n SessionStorage,\n type SessionStorageBackend,\n} from \"./session/\";\nimport {\n createAPIClient as createStorageClient,\n type Client as StorageClient,\n} from \"./storage\";\n\n/**\n * Configuration function that receives all clients and can configure them\n * (e.g., by attaching middleware, setting up interceptors, etc.)\n */\nexport type ClientConfigurationFn = (clients: {\n auth: AuthClient;\n storage: StorageClient;\n graphql: GraphQLClient;\n functions: FunctionsClient;\n sessionStorage: SessionStorage;\n}) => void;\n\n/**\n * Built-in configuration for client-side applications.\n * Includes automatic session refresh, token attachment, and session updates.\n */\nexport const withClientSideSessionMiddleware: ClientConfigurationFn = ({\n auth,\n storage,\n graphql,\n functions,\n sessionStorage,\n}) => {\n const mwChain: ChainFunction[] = [\n sessionRefreshMiddleware(auth, sessionStorage),\n updateSessionFromResponseMiddleware(sessionStorage),\n attachAccessTokenMiddleware(sessionStorage),\n ];\n\n for (const mw of mwChain) {\n auth.pushChainFunction(mw);\n storage.pushChainFunction(mw);\n graphql.pushChainFunction(mw);\n functions.pushChainFunction(mw);\n }\n};\n\n/**\n * Built-in configuration for server-side applications.\n * Includes token attachment and session updates, but NOT automatic session refresh\n * to prevent race conditions in server contexts.\n */\nexport const withServerSideSessionMiddleware: ClientConfigurationFn = ({\n auth,\n storage,\n graphql,\n functions,\n sessionStorage,\n}) => {\n const mwChain: ChainFunction[] = [\n updateSessionFromResponseMiddleware(sessionStorage),\n attachAccessTokenMiddleware(sessionStorage),\n ];\n\n for (const mw of mwChain) {\n auth.pushChainFunction(mw);\n storage.pushChainFunction(mw);\n graphql.pushChainFunction(mw);\n functions.pushChainFunction(mw);\n }\n};\n\n/**\n * Configuration for admin clients with elevated privileges.\n * Applies admin session middleware to storage, graphql, and functions clients only.\n *\n * **Security Warning**: Never use this in client-side code. Admin secrets grant\n * unrestricted access to your entire database.\n *\n * @param adminSession - Admin session options including admin secret, role, and session variables\n * @returns Configuration function that sets up admin middleware\n */\nexport function withAdminSession(\n adminSession: AdminSessionOptions,\n): ClientConfigurationFn {\n return ({ storage, graphql, functions }) => {\n const adminMiddleware = withAdminSessionMiddleware(adminSession);\n\n storage.pushChainFunction(adminMiddleware);\n graphql.pushChainFunction(adminMiddleware);\n functions.pushChainFunction(adminMiddleware);\n };\n}\n\n/**\n * Configuration for adding custom chain functions to all clients.\n * Useful for adding custom middleware like logging, caching, or custom headers.\n *\n * @param chainFunctions - Array of chain functions to apply to all clients\n * @returns Configuration function that sets up custom middleware\n */\nexport function withChainFunctions(\n chainFunctions: ChainFunction[],\n): ClientConfigurationFn {\n return ({ auth, storage, graphql, functions }) => {\n for (const mw of chainFunctions) {\n auth.pushChainFunction(mw);\n storage.pushChainFunction(mw);\n graphql.pushChainFunction(mw);\n functions.pushChainFunction(mw);\n }\n };\n}\n\n/**\n * Main client class that provides unified access to all Nhost services.\n * This class serves as the central interface for interacting with Nhost's\n * authentication, storage, GraphQL, and serverless functions capabilities.\n */\nexport class NhostClient {\n /**\n * Authentication client providing methods for user sign-in, sign-up, and session management.\n * Use this client to handle all authentication-related operations.\n */\n auth: AuthClient;\n\n /**\n * Storage client providing methods for file operations (upload, download, delete).\n * Use this client to manage files in your Nhost storage.\n */\n storage: StorageClient;\n\n /**\n * GraphQL client providing methods for executing GraphQL operations against your Hasura backend.\n * Use this client to query and mutate data in your database through GraphQL.\n */\n graphql: GraphQLClient;\n\n /**\n * Functions client providing methods for invoking serverless functions.\n * Use this client to call your custom serverless functions deployed to Nhost.\n */\n functions: FunctionsClient;\n\n /**\n * Storage implementation used for persisting session information.\n * This handles saving, retrieving, and managing authentication sessions across requests.\n */\n sessionStorage: SessionStorage;\n\n /**\n * Create a new Nhost client. This constructor is reserved for advanced use cases.\n * For typical usage, use [createClient](#createclient) or [createServerClient](#createserverclient) instead.\n *\n * @param auth - Authentication client instance\n * @param storage - Storage client instance\n * @param graphql - GraphQL client instance\n * @param functions - Functions client instance\n * @param sessionStorage - Storage implementation for session persistence\n */\n constructor(\n auth: AuthClient,\n storage: StorageClient,\n graphql: GraphQLClient,\n functions: FunctionsClient,\n sessionStorage: SessionStorage,\n ) {\n this.auth = auth;\n this.storage = storage;\n this.graphql = graphql;\n this.functions = functions;\n this.sessionStorage = sessionStorage;\n }\n\n /**\n * Get the current session from storage.\n * This method retrieves the authenticated user's session information if one exists.\n *\n * @returns The current session or null if no session exists\n *\n * @example\n * ```ts\n * const session = nhost.getUserSession();\n * if (session) {\n * console.log('User is authenticated:', session.user.id);\n * } else {\n * console.log('No active session');\n * }\n * ```\n */\n getUserSession(): Session | null {\n return this.sessionStorage.get();\n }\n\n /**\n * Refresh the session using the current refresh token\n * in the storage and update the storage with the new session.\n *\n * This method can be used to proactively refresh tokens before they expire\n * or to force a refresh when needed.\n *\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 *\n * @returns The new session or null if there is currently no session or if refresh fails\n *\n * @example\n * ```ts\n * // Refresh token if it's about to expire in the next 5 minutes\n * const refreshedSession = await nhost.refreshSession(300);\n *\n * // Force refresh regardless of current token expiration\n * const forcedRefresh = await nhost.refreshSession(0);\n * ```\n */\n async refreshSession(marginSeconds = 60): Promise<Session | null> {\n return refreshSession(this.auth, this.sessionStorage, marginSeconds);\n }\n\n /**\n * Clear the session from storage.\n *\n * This method removes the current authentication session, effectively logging out the user.\n * Note that this is a client-side operation and doesn't invalidate the refresh token on\n * the server, which can be done with `nhost.auth.signOut({refreshToken: session.refreshTokenId})`.\n * If the middle `updateSessionFromResponseMiddleware` is used, the session will be removed\n * from the storage automatically and calling this method is not necessary.\n *\n * @example\n * ```ts\n * // Log out the user\n * nhost.clearSession();\n * ```\n */\n clearSession(): void {\n this.sessionStorage.remove();\n }\n}\n\n/**\n * Configuration options for creating an Nhost client\n */\nexport interface NhostClientOptions {\n /**\n * Nhost project subdomain (e.g., 'abcdefgh'). Used to construct the base URL for services for the Nhost cloud.\n */\n subdomain?: string;\n\n /**\n * Nhost region (e.g., 'eu-central-1'). Used to construct the base URL for services for the Nhost cloud.\n */\n region?: string;\n\n /**\n * Complete base URL for the auth service (overrides subdomain/region)\n */\n authUrl?: string;\n\n /**\n * Complete base URL for the storage service (overrides subdomain/region)\n */\n storageUrl?: string;\n\n /**\n * Complete base URL for the GraphQL service (overrides subdomain/region)\n */\n graphqlUrl?: string;\n\n /**\n * Complete base URL for the functions service (overrides subdomain/region)\n */\n functionsUrl?: string;\n\n /**\n * Storage backend to use for session persistence. If not provided, the SDK will\n * default to localStorage in the browser or memory in other environments.\n */\n storage?: SessionStorageBackend;\n\n /**\n * Configuration functions to be applied to the client after initialization.\n * These functions receive all clients and can attach middleware or perform other setup.\n */\n configure?: ClientConfigurationFn[];\n}\n\n/**\n * Creates and configures a new Nhost client instance with custom configuration.\n *\n * This is the main factory function for creating Nhost clients. It instantiates\n * all service clients (auth, storage, graphql, functions) and applies the provided\n * configuration functions to set up middleware and other customizations.\n *\n * @param options - Configuration options for the client\n * @returns A configured Nhost client\n *\n * @example\n * ```ts\n * // Create a basic client with no middleware\n * const nhost = createNhostClient({\n * subdomain: 'abcdefgh',\n * region: 'eu-central-1',\n * configure: []\n * });\n *\n * // Create a client with custom configuration\n * const nhost = createNhostClient({\n * subdomain: 'abcdefgh',\n * region: 'eu-central-1',\n * configure: [\n * withClientSideSessionMiddleware,\n * withChainFunctions([customLoggingMiddleware])\n * ]\n * });\n *\n * // Create an admin client\n * const nhost = createNhostClient({\n * subdomain,\n * region,\n * configure: [\n * withAdminSession({\n * adminSecret: \"nhost-admin-secret\",\n * role: \"user\",\n * sessionVariables: {\n * \"user-id\": \"54058C42-51F7-4B37-8B69-C89A841D2221\",\n * },\n * }),\n * ],\n * });\n\n * ```\n */\nexport function createNhostClient(\n options: NhostClientOptions = {},\n): NhostClient {\n const {\n subdomain,\n region,\n authUrl,\n storageUrl,\n graphqlUrl,\n functionsUrl,\n storage = detectStorage(),\n configure = [],\n } = options;\n\n const sessionStorage = new SessionStorage(storage);\n\n // Determine base URLs for each service\n const authBaseUrl = generateServiceUrl(\"auth\", subdomain, region, authUrl);\n const storageBaseUrl = generateServiceUrl(\n \"storage\",\n subdomain,\n region,\n storageUrl,\n );\n const graphqlBaseUrl = generateServiceUrl(\n \"graphql\",\n subdomain,\n region,\n graphqlUrl,\n );\n const functionsBaseUrl = generateServiceUrl(\n \"functions\",\n subdomain,\n region,\n functionsUrl,\n );\n\n // Create all clients\n const auth = createAuthClient(authBaseUrl);\n const storageClient = createStorageClient(storageBaseUrl, []);\n const graphqlClient = createGraphQLClient(graphqlBaseUrl, []);\n const functionsClient = createFunctionsClient(functionsBaseUrl, []);\n\n // Apply configuration functions\n for (const configFn of configure) {\n configFn({\n auth,\n storage: storageClient,\n graphql: graphqlClient,\n functions: functionsClient,\n sessionStorage,\n });\n }\n\n // Return an initialized NhostClient\n return new NhostClient(\n auth,\n storageClient,\n graphqlClient,\n functionsClient,\n sessionStorage,\n );\n}\n\n/**\n * Creates and configures a new Nhost client instance optimized for client-side usage.\n *\n * This helper method instantiates a fully configured Nhost client by:\n * - Instantiating the various service clients (auth, storage, functions and graphql)\n * - Auto-detecting and configuring an appropriate session storage (localStorage in browsers, memory otherwise)\n * - Setting up a sophisticated middleware chain for seamless authentication management:\n * - Automatically refreshing tokens before they expire\n * - Attaching authorization tokens to all service requests\n * - Updating the session storage when new tokens are received\n *\n * This method includes automatic session refresh middleware, making it ideal for\n * client-side applications where long-lived sessions are expected.\n *\n * @param options - Configuration options for the client\n * @returns A configured Nhost client\n *\n * @example\n * ```ts\n * // Create client using Nhost cloud default URLs\n * const nhost = createClient({\n * subdomain: 'abcdefgh',\n * region: 'eu-central-1'\n * });\n *\n * // Create client with custom service URLs\n * const customNhost = createClient({\n * authUrl: 'https://auth.example.com',\n * storageUrl: 'https://storage.example.com',\n * graphqlUrl: 'https://graphql.example.com',\n * functionsUrl: 'https://functions.example.com'\n * });\n *\n * // Create client using cookies for storing the session\n * import { CookieStorage } from \"@nhost/nhost-js/session\";\n *\n * const nhost = createClient({\n * subdomain: 'abcdefgh',\n * region: 'eu-central-1',\n * storage: new CookieStorage({\n * secure: import.meta.env.ENVIRONMENT === 'production',\n * })\n * });\n *\n * // Create client with additional custom middleware\n * const nhost = createClient({\n * subdomain: 'abcdefgh',\n * region: 'eu-central-1',\n * configure: [customLoggingMiddleware]\n * });\n * ```\n */\nexport function createClient(options: NhostClientOptions = {}): NhostClient {\n const storage = options.storage ?? detectStorage();\n\n return createNhostClient({\n ...options,\n storage,\n configure: [withClientSideSessionMiddleware, ...(options.configure ?? [])],\n });\n}\n\nexport interface NhostServerClientOptions extends NhostClientOptions {\n /**\n * Storage backend to use for session persistence in server environments.\n * Unlike the base options, this field is required for server-side usage\n * as the SDK cannot auto-detect an appropriate storage mechanism.\n */\n storage: SessionStorageBackend;\n}\n\n/**\n * Creates and configures a new Nhost client instance optimized for server-side usage.\n *\n * This helper method instantiates a fully configured Nhost client specifically designed for:\n * - Server components (in frameworks like Next.js or Remix)\n * - API routes and middleware\n * - Backend services and server-side rendering contexts\n *\n * Key differences from the standard client:\n * - Requires explicit storage implementation (must be provided)\n * - Disables automatic session refresh middleware (to prevent race conditions in server contexts)\n * - Still attaches authorization tokens and updates session storage from responses\n *\n * The server client is ideal for short-lived request contexts where session tokens\n * are passed in (like cookie-based authentication flows) and automatic refresh\n * mechanisms could cause issues with concurrent requests.\n *\n * @param options - Configuration options for the server client (requires storage implementation)\n * @returns A configured Nhost client optimized for server-side usage\n *\n * @example\n * ```ts\n * // Example with cookie storage for Next.js API route or server component\n * import { cookies } from 'next/headers';\n *\n * const nhost = createServerClient({\n * region: process.env[\"NHOST_REGION\"] || \"local\",\n * subdomain: process.env[\"NHOST_SUBDOMAIN\"] || \"local\",\n * storage: {\n * // storage compatible with Next.js server components\n * get: (): Session | null => {\n * const s = cookieStore.get(key)?.value || null;\n * if (!s) {\n * return null;\n * }\n * const session = JSON.parse(s) as Session;\n * return session;\n * },\n * set: (value: Session) => {\n * cookieStore.set(key, JSON.stringify(value));\n * },\n * remove: () => {\n * cookieStore.delete(key);\n * },\n * },\n * });\n *\n * // Example with cookie storage for Next.js middleware\n * const nhost = createServerClient({\n * region: process.env[\"NHOST_REGION\"] || \"local\",\n * subdomain: process.env[\"NHOST_SUBDOMAIN\"] || \"local\",\n * storage: {\n * // storage compatible with Next.js middleware\n * get: (): Session | null => {\n * const raw = request.cookies.get(key)?.value || null;\n * if (!raw) {\n * return null;\n * }\n * const session = JSON.parse(raw) as Session;\n * return session;\n * },\n * set: (value: Session) => {\n * response.cookies.set({\n * name: key,\n * value: JSON.stringify(value),\n * path: \"/\",\n * httpOnly: false, //if set to true we can't access it in the client\n * secure: process.env.NODE_ENV === \"production\",\n * sameSite: \"lax\",\n * maxAge: 60 * 60 * 24 * 30, // 30 days in seconds\n * });\n * },\n * remove: () => {\n * response.cookies.delete(key);\n * },\n * },\n * });\n *\n * // Example for express reading session from a cookie\n *\n * import express, { Request, Response } from \"express\";\n * import cookieParser from \"cookie-parser\";\n *\n * app.use(cookieParser());\n *\n * const nhostClientFromCookies = (req: Request) => {\n * return createServerClient({\n * subdomain: \"local\",\n * region: \"local\",\n * storage: {\n * get: (): Session | null => {\n * const s = req.cookies.nhostSession || null;\n * if (!s) {\n * return null;\n * }\n * const session = JSON.parse(s) as Session;\n * return session;\n * },\n * set: (_value: Session) => {\n * throw new Error(\"It is easier to handle the session in the client\");\n * },\n * remove: () => {\n * throw new Error(\"It is easier to handle the session in the client\");\n * },\n * },\n * });\n * };\n *\n * // Example with additional custom middleware\n * const nhost = createServerClient({\n * region: process.env[\"NHOST_REGION\"] || \"local\",\n * subdomain: process.env[\"NHOST_SUBDOMAIN\"] || \"local\",\n * storage: myStorage,\n * configure: [customLoggingMiddleware]\n * });\n * ```\n */\nexport function createServerClient(\n options: NhostServerClientOptions,\n): NhostClient {\n return createNhostClient({\n ...options,\n configure: [withServerSideSessionMiddleware, ...(options.configure ?? [])],\n });\n}\n","/**\n * Main entry point for the Nhost JavaScript SDK.\n *\n * This package provides a unified client for interacting with Nhost services:\n * - Authentication\n * - Storage\n * - GraphQL\n * - Functions\n *\n * ## Import\n *\n * ```ts\n * import { createClient } from \"@nhost/nhost-js\";\n * ```\n *\n * ## Usage\n *\n * Create a client instance to interact with Nhost services:\n *\n * {@includeCode ./__tests__/docstrings.test.ts:15-119}\n *\n * ### Creating an admin client\n *\n * You can also create an admin client if needed. This client will have admin access to the database\n * and will bypass permissions. Additionally, it can impersonate users and set any role or session\n * variable.\n *\n * IMPORTANT!!! Keep your admin secret safe and never expose it in client-side code.\n *\n * {@includeCode ./__tests__/docstrings.test.ts:142-201}\n *\n * @packageDocumentation\n */\n\nexport {\n type ClientConfigurationFn,\n createClient,\n createNhostClient,\n createServerClient,\n type NhostClient,\n type NhostClientOptions,\n type NhostServerClientOptions,\n withAdminSession,\n withClientSideSessionMiddleware,\n withServerSideSessionMiddleware,\n} from \"./nhost\";\n\n/**\n * Generates a base URL for a Nhost service based on configuration\n *\n * @param serviceType - Type of service (auth, storage, graphql, functions)\n * @param subdomain - Nhost project subdomain\n * @param region - Nhost region\n * @param customUrl - Custom URL override if provided\n * @returns The base URL for the service\n */\nexport const generateServiceUrl = (\n serviceType: \"auth\" | \"storage\" | \"graphql\" | \"functions\",\n subdomain?: string,\n region?: string,\n customUrl?: string,\n): string => {\n if (customUrl) {\n return customUrl;\n } else if (subdomain && region) {\n return `https://${subdomain}.${serviceType}.${region}.nhost.run/v1`;\n } else {\n return `https://local.${serviceType}.local.nhost.run/v1`;\n }\n};\n"],"names":["createAuthClient","createStorageClient","createGraphQLClient","createFunctionsClient"],"mappings":"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"}
|
package/dist/nhost-js.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(t,s){"object"==typeof exports&&"undefined"!=typeof module?s(exports):"function"==typeof define&&define.amd?define(["exports"],s):s((t="undefined"!=typeof globalThis?globalThis:t||self).NhostJs={})}(this,(function(t){"use strict";function s(t=[]){return t.reduceRight(((t,s)=>s(t)),fetch)}class e extends Error{body;status;headers;constructor(t,s,e){super(function(t){if(t&&"string"==typeof t)return t;if(t&&"object"==typeof t){const s=t;if("message"in s&&"string"==typeof s.message)return s.message;if("error"in s&&"string"==typeof s.error)return s.error;if("error"in s&&s.error&&"object"==typeof s.error){const t=s.error;if("message"in t&&"string"==typeof t.message)return t.message}if("errors"in s&&Array.isArray(s.errors)){const t=s.errors.filter((t=>"object"==typeof t&&null!==t&&"message"in t&&"string"==typeof t.message)).map((t=>t.message));if(t.length>0)return t.join(", ")}}return"An unexpected error occurred"}(t)),this.body=t,this.status=s,this.headers=e}}const a=t=>s=>async(e,a={})=>{const r=new Headers(a.headers||{});if(r.has("Authorization"))return s(e,a);const o=t.get();if(o?.accessToken){const t={...a,headers:n(r,o)};return s(e,t)}return s(e,a)};function n(t,s){return s.accessToken&&t.set("Authorization",`Bearer ${s.accessToken}`),t}const r="undefined"!=typeof navigator&&navigator.locks?navigator.locks:new class{async request(t,s,e){return e()}},o=async(t,s,e=60)=>{try{return await i(t,s,e)}catch(a){try{return console.warn("error refreshing session, retrying:",a),await i(t,s,e)}catch(n){const t=n;return 401===t?.status&&(console.error("session probably expired"),s.remove()),null}}},i=async(t,s,e=60)=>{const{session:a,needsRefresh:n}=await r.request("nhostSessionLock",{mode:"shared"},(async()=>u(s,e)));if(!a)return null;if(!n)return a;return await r.request("nhostSessionLock",{mode:"exclusive"},(async()=>{const{session:a,needsRefresh:n,sessionExpired:r}=u(s,e);if(!a)return null;if(!n)return a;try{const e=await t.refreshToken({refreshToken:a.refreshToken});return s.set(e.body),e.body}catch(o){if(!r)return a;throw o}}))},u=(t,s=60)=>{const e=t.get();if(!e)return{session:null,needsRefresh:!1,sessionExpired:!1};if(!e.decodedToken||!e.decodedToken.exp)return{session:e,needsRefresh:!0,sessionExpired:!0};if(0===s)return{session:e,needsRefresh:!0,sessionExpired:!1};const a=Date.now();return e.decodedToken.exp-a>1e3*s?{session:e,needsRefresh:!1,sessionExpired:!1}:{session:e,needsRefresh:!0,sessionExpired:e.decodedToken.exp<a}},d=(t,s,e)=>{const{marginSeconds:a=60}={};return e=>async(n,r={})=>{if(function(t,s){const e=new Headers(s.headers||{});if(e.has("Authorization"))return!0;if(t.endsWith("/v1/token"))return!0;return!1}(n,r))return e(n,r);try{await o(t,s,a)}catch{}return e(n,r)}};const c=t=>s=>async(e,a)=>{const n=await s(e,a);try{if(e.endsWith("/signout"))return t.remove(),n;if(e.endsWith("/token")||e.includes("/signin/")||e.includes("/signup/")){const s=n.clone(),e=await s.json().catch((()=>null));if(e){const s=(t=>"string"==typeof t?null:"session"in t?t.session||null:"accessToken"in t&&"refreshToken"in t?t:null)(e);s?.accessToken&&s.refreshToken&&t.set(s)}}}catch(r){console.warn("Error in session response middleware:",r)}return n},h=(t,a=[])=>{let n=s(a);return{baseURL:t,pushChainFunction:t=>{a.push(t),n=s(a)},getJWKs:async s=>{const a=`${t}/.well-known/jwks.json`,r=await n(a,{...s,method:"GET",headers:{...s?.headers}});if(r.status>=300){const t=[412].includes(r.status)?null:await r.text(),s=t?JSON.parse(t):{};throw new e(s,r.status,r.headers)}const o=[204,205,304].includes(r.status)?null:await r.text();return{body:o?JSON.parse(o):{},status:r.status,headers:r.headers}},elevateWebauthn:async s=>{const a=`${t}/elevate/webauthn`,r=await n(a,{...s,method:"POST",headers:{...s?.headers}});if(r.status>=300){const t=[412].includes(r.status)?null:await r.text(),s=t?JSON.parse(t):{};throw new e(s,r.status,r.headers)}const o=[204,205,304].includes(r.status)?null:await r.text();return{body:o?JSON.parse(o):{},status:r.status,headers:r.headers}},verifyElevateWebauthn:async(s,a)=>{const r=`${t}/elevate/webauthn/verify`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},healthCheckGet:async s=>{const a=`${t}/healthz`,r=await n(a,{...s,method:"GET",headers:{...s?.headers}});if(r.status>=300){const t=[412].includes(r.status)?null:await r.text(),s=t?JSON.parse(t):{};throw new e(s,r.status,r.headers)}const o=[204,205,304].includes(r.status)?null:await r.text();return{body:o?JSON.parse(o):{},status:r.status,headers:r.headers}},healthCheckHead:async s=>{const a=`${t}/healthz`,r=await n(a,{...s,method:"HEAD",headers:{...s?.headers}});if(r.status>=300){const t=[412].includes(r.status)?null:await r.text(),s=t?JSON.parse(t):{};throw new e(s,r.status,r.headers)}return{body:void 0,status:r.status,headers:r.headers}},linkIdToken:async(s,a)=>{const r=`${t}/link/idtoken`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},changeUserMfa:async s=>{const a=`${t}/mfa/totp/generate`,r=await n(a,{...s,method:"GET",headers:{...s?.headers}});if(r.status>=300){const t=[412].includes(r.status)?null:await r.text(),s=t?JSON.parse(t):{};throw new e(s,r.status,r.headers)}const o=[204,205,304].includes(r.status)?null:await r.text();return{body:o?JSON.parse(o):{},status:r.status,headers:r.headers}},createPAT:async(s,a)=>{const r=`${t}/pat`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},signInAnonymous:async(s,a)=>{const r=`${t}/signin/anonymous`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},signInEmailPassword:async(s,a)=>{const r=`${t}/signin/email-password`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},signInIdToken:async(s,a)=>{const r=`${t}/signin/idtoken`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},verifySignInMfaTotp:async(s,a)=>{const r=`${t}/signin/mfa/totp`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},signInOTPEmail:async(s,a)=>{const r=`${t}/signin/otp/email`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},verifySignInOTPEmail:async(s,a)=>{const r=`${t}/signin/otp/email/verify`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},signInPasswordlessEmail:async(s,a)=>{const r=`${t}/signin/passwordless/email`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},signInPasswordlessSms:async(s,a)=>{const r=`${t}/signin/passwordless/sms`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},verifySignInPasswordlessSms:async(s,a)=>{const r=`${t}/signin/passwordless/sms/otp`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},signInPAT:async(s,a)=>{const r=`${t}/signin/pat`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},signInProviderURL:(s,e)=>{const a=e&&Object.entries(e).map((([t,s])=>{const e=Array.isArray(s)?s.join(","):"object"==typeof s?JSON.stringify(s):s;return`${t}=${encodeURIComponent(e)}`})).join("&");return a?`${t}/signin/provider/${s}?${a}`:`${t}/signin/provider/${s}`},signInWebauthn:async(s,a)=>{const r=`${t}/signin/webauthn`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},verifySignInWebauthn:async(s,a)=>{const r=`${t}/signin/webauthn/verify`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},signOut:async(s,a)=>{const r=`${t}/signout`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},signUpEmailPassword:async(s,a)=>{const r=`${t}/signup/email-password`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},signUpWebauthn:async(s,a)=>{const r=`${t}/signup/webauthn`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},verifySignUpWebauthn:async(s,a)=>{const r=`${t}/signup/webauthn/verify`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},refreshToken:async(s,a)=>{const r=`${t}/token`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},verifyToken:async(s,a)=>{const r=`${t}/token/verify`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},getUser:async s=>{const a=`${t}/user`,r=await n(a,{...s,method:"GET",headers:{...s?.headers}});if(r.status>=300){const t=[412].includes(r.status)?null:await r.text(),s=t?JSON.parse(t):{};throw new e(s,r.status,r.headers)}const o=[204,205,304].includes(r.status)?null:await r.text();return{body:o?JSON.parse(o):{},status:r.status,headers:r.headers}},deanonymizeUser:async(s,a)=>{const r=`${t}/user/deanonymize`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},changeUserEmail:async(s,a)=>{const r=`${t}/user/email/change`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},sendVerificationEmail:async(s,a)=>{const r=`${t}/user/email/send-verification-email`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},verifyChangeUserMfa:async(s,a)=>{const r=`${t}/user/mfa`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},changeUserPassword:async(s,a)=>{const r=`${t}/user/password`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},sendPasswordResetEmail:async(s,a)=>{const r=`${t}/user/password/reset`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},addSecurityKey:async s=>{const a=`${t}/user/webauthn/add`,r=await n(a,{...s,method:"POST",headers:{...s?.headers}});if(r.status>=300){const t=[412].includes(r.status)?null:await r.text(),s=t?JSON.parse(t):{};throw new e(s,r.status,r.headers)}const o=[204,205,304].includes(r.status)?null:await r.text();return{body:o?JSON.parse(o):{},status:r.status,headers:r.headers}},verifyAddSecurityKey:async(s,a)=>{const r=`${t}/user/webauthn/verify`,o=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(s)});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},verifyTicketURL:s=>{const e=s&&Object.entries(s).map((([t,s])=>{const e=Array.isArray(s)?s.join(","):"object"==typeof s?JSON.stringify(s):s;return`${t}=${encodeURIComponent(e)}`})).join("&");return e?`${t}/verify?${e}`:`${t}/verify`},getVersion:async s=>{const a=`${t}/version`,r=await n(a,{...s,method:"GET",headers:{...s?.headers}});if(r.status>=300){const t=[412].includes(r.status)?null:await r.text(),s=t?JSON.parse(t):{};throw new e(s,r.status,r.headers)}const o=[204,205,304].includes(r.status)?null:await r.text();return{body:o?JSON.parse(o):{},status:r.status,headers:r.headers}}}},l=(t,a=[])=>{const n=s(a),r=async(s,a)=>{const r=await n(`${t}${s}`,a);let o;if(o=r.headers.get("content-type")?.includes("application/json")?await r.json():r.headers.get("content-type")?.startsWith("text/")?await r.text():await r.blob(),!r.ok)throw new e(o,r.status,r.headers);return{status:r.status,body:o,headers:r.headers}};return{baseURL:t,fetch:r,post:async(t,s,e={})=>{const a={...e,method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...e.headers},body:s?JSON.stringify(s):void 0};return r(t,a)}}},p=(t,a=[])=>{const n=s(a),r=async(s,a)=>{const r=await n(`${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),...a}),o=await r.text(),i=o?JSON.parse(o):{},u={body:i,status:r.status,headers:r.headers};if(i.errors)throw new e(i,r.status,r.headers);return u};return{request:function(t,s,e){if("object"==typeof t&&"kind"in t){const a=t.definitions[0],n={query:t.loc?.source.body||"",variables:s,operationName:a&&"name"in a?a.name?.value:void 0};return r(n,e)}return r(t,s)},url:t}},w=t=>t.startsWith("{")&&t.endsWith("}"),y=t=>t&&"{}"!==t?t.slice(1,-1).split(",").map((t=>t.trim().replace(/^"(.*)"$/,"$1"))):[];class f{storageKey;constructor(t){this.storageKey=t?.storageKey||"nhostSession"}get(){try{const t=window.localStorage.getItem(this.storageKey);return t?JSON.parse(t):null}catch{return this.remove(),null}}set(t){window.localStorage.setItem(this.storageKey,JSON.stringify(t))}remove(){window.localStorage.removeItem(this.storageKey)}}class S{session=null;get(){return this.session}set(t){this.session=t}remove(){this.session=null}}class O{storage;subscribers=new Set;constructor(t){this.storage=t}get(){return this.storage.get()}set(t){const s=(t=>{const s=t.split(".");if(3!==s.length||!s[1])throw new Error("Invalid access token format");const e=JSON.parse("undefined"!=typeof atob?atob(s[1]):Buffer.from(s[1],"base64").toString("utf-8")),a="number"==typeof e.iat?1e3*e.iat:void 0,n="number"==typeof e.exp?1e3*e.exp:void 0,r=e["https://hasura.io/jwt/claims"],o=r?Object.entries(r).reduce(((t,[s,e])=>("string"==typeof e&&w(e)?t[s]=y(e):t[s]=e,t)),{}):void 0;return{...e,iat:a,exp:n,"https://hasura.io/jwt/claims":o}})(t.accessToken),e={...t,decodedToken:s};this.storage.set(e),this.notifySubscribers(e)}remove(){this.storage.remove(),this.notifySubscribers(null)}onChange(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}notifySubscribers(t){for(const e of this.subscribers)try{e(t)}catch(s){console.error("Error notifying subscriber:",s)}}}const g=()=>"undefined"!=typeof window?new f:new S,b=(t,a=[])=>{let n=s(a);return{baseURL:t,pushChainFunction:t=>{a.push(t),n=s(a)},uploadFiles:async(s,a)=>{const r=`${t}/files`,o=new FormData;void 0!==s["bucket-id"]&&o.append("bucket-id",s["bucket-id"]),void 0!==s["metadata[]"]&&s["metadata[]"].forEach((t=>{o.append("metadata[]",new Blob([JSON.stringify(t)],{type:"application/json"}),"")})),void 0!==s["file[]"]&&s["file[]"].forEach((t=>{o.append("file[]",t)}));const i=await n(r,{...a,method:"POST",body:o});if(i.status>=300){const t=[412].includes(i.status)?null:await i.text(),s=t?JSON.parse(t):{};throw new e(s,i.status,i.headers)}const u=[204,205,304].includes(i.status)?null:await i.text();return{body:u?JSON.parse(u):{},status:i.status,headers:i.headers}},deleteFile:async(s,a)=>{const r=`${t}/files/${s}`,o=await n(r,{...a,method:"DELETE",headers:{...a?.headers}});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}return{body:void 0,status:o.status,headers:o.headers}},getFile:async(s,a,r)=>{const o=a&&Object.entries(a).map((([t,s])=>{const e=Array.isArray(s)?s.join(","):"object"==typeof s?JSON.stringify(s):s;return`${t}=${encodeURIComponent(e)}`})).join("&"),i=o?`${t}/files/${s}?${o}`:`${t}/files/${s}`,u=await n(i,{...r,method:"GET",headers:{...r?.headers}});if(u.status>=300){const t=[412].includes(u.status)?null:await u.text(),s=t?JSON.parse(t):{};throw new e(s,u.status,u.headers)}return{body:await u.blob(),status:u.status,headers:u.headers}},getFileMetadataHeaders:async(s,a,r)=>{const o=a&&Object.entries(a).map((([t,s])=>{const e=Array.isArray(s)?s.join(","):"object"==typeof s?JSON.stringify(s):s;return`${t}=${encodeURIComponent(e)}`})).join("&"),i=o?`${t}/files/${s}?${o}`:`${t}/files/${s}`,u=await n(i,{...r,method:"HEAD",headers:{...r?.headers}});if(u.status>=300){const t=[412].includes(u.status)?null:await u.text(),s=t?JSON.parse(t):{};throw new e(s,u.status,u.headers)}return{body:void 0,status:u.status,headers:u.headers}},replaceFile:async(s,a,r)=>{const o=`${t}/files/${s}`,i=new FormData;void 0!==a.metadata&&i.append("metadata",new Blob([JSON.stringify(a.metadata)],{type:"application/json"}),""),void 0!==a.file&&i.append("file",a.file);const u=await n(o,{...r,method:"PUT",body:i});if(u.status>=300){const t=[412].includes(u.status)?null:await u.text(),s=t?JSON.parse(t):{};throw new e(s,u.status,u.headers)}const d=[204,205,304].includes(u.status)?null:await u.text();return{body:d?JSON.parse(d):{},status:u.status,headers:u.headers}},getFilePresignedURL:async(s,a)=>{const r=`${t}/files/${s}/presignedurl`,o=await n(r,{...a,method:"GET",headers:{...a?.headers}});if(o.status>=300){const t=[412].includes(o.status)?null:await o.text(),s=t?JSON.parse(t):{};throw new e(s,o.status,o.headers)}const i=[204,205,304].includes(o.status)?null:await o.text();return{body:i?JSON.parse(i):{},status:o.status,headers:o.headers}},deleteBrokenMetadata:async s=>{const a=`${t}/ops/delete-broken-metadata`,r=await n(a,{...s,method:"POST",headers:{...s?.headers}});if(r.status>=300){const t=[412].includes(r.status)?null:await r.text(),s=t?JSON.parse(t):{};throw new e(s,r.status,r.headers)}const o=[204,205,304].includes(r.status)?null:await r.text();return{body:o?JSON.parse(o):{},status:r.status,headers:r.headers}},deleteOrphanedFiles:async s=>{const a=`${t}/ops/delete-orphans`,r=await n(a,{...s,method:"POST",headers:{...s?.headers}});if(r.status>=300){const t=[412].includes(r.status)?null:await r.text(),s=t?JSON.parse(t):{};throw new e(s,r.status,r.headers)}const o=[204,205,304].includes(r.status)?null:await r.text();return{body:o?JSON.parse(o):{},status:r.status,headers:r.headers}},listBrokenMetadata:async s=>{const a=`${t}/ops/list-broken-metadata`,r=await n(a,{...s,method:"POST",headers:{...s?.headers}});if(r.status>=300){const t=[412].includes(r.status)?null:await r.text(),s=t?JSON.parse(t):{};throw new e(s,r.status,r.headers)}const o=[204,205,304].includes(r.status)?null:await r.text();return{body:o?JSON.parse(o):{},status:r.status,headers:r.headers}},listFilesNotUploaded:async s=>{const a=`${t}/ops/list-not-uploaded`,r=await n(a,{...s,method:"POST",headers:{...s?.headers}});if(r.status>=300){const t=[412].includes(r.status)?null:await r.text(),s=t?JSON.parse(t):{};throw new e(s,r.status,r.headers)}const o=[204,205,304].includes(r.status)?null:await r.text();return{body:o?JSON.parse(o):{},status:r.status,headers:r.headers}},listOrphanedFiles:async s=>{const a=`${t}/ops/list-orphans`,r=await n(a,{...s,method:"POST",headers:{...s?.headers}});if(r.status>=300){const t=[412].includes(r.status)?null:await r.text(),s=t?JSON.parse(t):{};throw new e(s,r.status,r.headers)}const o=[204,205,304].includes(r.status)?null:await r.text();return{body:o?JSON.parse(o):{},status:r.status,headers:r.headers}},getVersion:async s=>{const a=`${t}/version`,r=await n(a,{...s,method:"GET",headers:{...s?.headers}});if(r.status>=300){const t=[412].includes(r.status)?null:await r.text(),s=t?JSON.parse(t):{};throw new e(s,r.status,r.headers)}const o=[204,205,304].includes(r.status)?null:await r.text();return{body:o?JSON.parse(o):{},status:r.status,headers:r.headers}}}};class m{auth;storage;graphql;functions;sessionStorage;constructor(t,s,e,a,n){this.auth=t,this.storage=s,this.graphql=e,this.functions=a,this.sessionStorage=n}getUserSession(){return this.sessionStorage.get()}async refreshSession(t=60){return o(this.auth,this.sessionStorage,t)}clearSession(){this.sessionStorage.remove()}}function N(t,s,e){const n=[c(s),a(s)];return e&&n.unshift(d(t,s)),n}const J=(t,s,e,a)=>a||(s&&e?`https://${s}.${t}.${e}.nhost.run/v1`:`https://local.${t}.local.nhost.run/v1`);t.createClient=function(t={}){const{subdomain:s,region:e,authUrl:a,storageUrl:n,graphqlUrl:r,functionsUrl:o,storage:i=g()}=t,u=new O(i),d=J("auth",s,e,a),c=J("storage",s,e,n),w=J("graphql",s,e,r),y=J("functions",s,e,o),f=h(d),S=N(f,u,!0);for(const h of S)f.pushChainFunction(h);const x=b(c,S),T=p(w,S),$=l(y,S);return new m(f,x,T,$,u)},t.createServerClient=function(t){const{subdomain:s,region:e,authUrl:a,storageUrl:n,graphqlUrl:r,functionsUrl:o,storage:i}=t,u=new O(i),d=J("auth",s,e,a),c=J("storage",s,e,n),w=J("graphql",s,e,r),y=J("functions",s,e,o),f=h(d),S=N(f,u,!1);for(const h of S)f.pushChainFunction(h);const g=b(c,S),x=p(w,S),T=l(y,S);return new m(f,g,x,T,u)},t.generateServiceUrl=J,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})}));
|
|
1
|
+
!function(s,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((s="undefined"!=typeof globalThis?globalThis:s||self).NhostJs={})}(this,(function(s){"use strict";function t(s=[]){return s.reduceRight(((s,t)=>t(s)),fetch)}class e extends Error{body;status;headers;constructor(s,t,e){super(function(s){if(s&&"string"==typeof s)return s;if(s&&"object"==typeof s){const t=s;if("message"in t&&"string"==typeof t.message)return t.message;if("error"in t&&"string"==typeof t.error)return t.error;if("error"in t&&t.error&&"object"==typeof t.error){const s=t.error;if("message"in s&&"string"==typeof s.message)return s.message}if("errors"in t&&Array.isArray(t.errors)){const s=t.errors.filter((s=>"object"==typeof s&&null!==s&&"message"in s&&"string"==typeof s.message)).map((s=>s.message));if(s.length>0)return s.join(", ")}}return"An unexpected error occurred"}(s)),this.body=s,this.status=t,this.headers=e}}const a=s=>t=>async(e,a={})=>{const r=new Headers(a.headers||{});if(r.has("Authorization"))return t(e,a);const i=s.get();if(i?.accessToken){const s={...a,headers:n(r,i)};return t(e,s)}return t(e,a)};function n(s,t){return t.accessToken&&s.set("Authorization",`Bearer ${t.accessToken}`),s}const r="undefined"!=typeof navigator&&navigator.locks?navigator.locks:new class{async request(s,t,e){return e()}},i=async(s,t,e=60)=>{try{return await o(s,t,e)}catch(a){try{return console.warn("error refreshing session, retrying:",a),await o(s,t,e)}catch(n){const s=n;return 401===s?.status&&(console.error("session probably expired"),t.remove()),null}}},o=async(s,t,e=60)=>{const{session:a,needsRefresh:n}=await r.request("nhostSessionLock",{mode:"shared"},(async()=>u(t,e)));if(!a)return null;if(!n)return a;return await r.request("nhostSessionLock",{mode:"exclusive"},(async()=>{const{session:a,needsRefresh:n,sessionExpired:r}=u(t,e);if(!a)return null;if(!n)return a;try{const e=await s.refreshToken({refreshToken:a.refreshToken});return t.set(e.body),e.body}catch(i){if(!r)return a;throw i}}))},u=(s,t=60)=>{const e=s.get();if(!e)return{session:null,needsRefresh:!1,sessionExpired:!1};if(!e.decodedToken||!e.decodedToken.exp)return{session:e,needsRefresh:!0,sessionExpired:!0};if(0===t)return{session:e,needsRefresh:!0,sessionExpired:!1};const a=Date.now();return e.decodedToken.exp-a>1e3*t?{session:e,needsRefresh:!1,sessionExpired:!1}:{session:e,needsRefresh:!0,sessionExpired:e.decodedToken.exp<a}},d=(s,t,e)=>{const{marginSeconds:a=60}={};return e=>async(n,r={})=>{if(function(s,t){const e=new Headers(t.headers||{});if(e.has("Authorization"))return!0;if(s.endsWith("/v1/token"))return!0;return!1}(n,r))return e(n,r);try{await i(s,t,a)}catch{}return e(n,r)}};const c=s=>t=>async(e,a)=>{const n=await t(e,a);try{if(e.endsWith("/signout"))return s.remove(),n;if(e.endsWith("/token")||e.includes("/signin/")||e.includes("/signup/")){const t=n.clone(),e=await t.json().catch((()=>null));if(e){const t=(s=>"string"==typeof s?null:"session"in s?s.session||null:"accessToken"in s&&"refreshToken"in s&&"user"in s?s:null)(e);t?.accessToken&&t.refreshToken&&s.set(t)}}}catch(r){console.warn("Error in session response middleware:",r)}return n},h=s=>s.startsWith("{")&&s.endsWith("}"),l=s=>s&&"{}"!==s?s.slice(1,-1).split(",").map((s=>s.trim().replace(/^"(.*)"$/,"$1"))):[];class p{storageKey;constructor(s){this.storageKey=s?.storageKey||"nhostSession"}get(){try{const s=window.localStorage.getItem(this.storageKey);return s?JSON.parse(s):null}catch{return this.remove(),null}}set(s){window.localStorage.setItem(this.storageKey,JSON.stringify(s))}remove(){window.localStorage.removeItem(this.storageKey)}}class w{session=null;get(){return this.session}set(s){this.session=s}remove(){this.session=null}}class y{storage;subscribers=new Set;constructor(s){this.storage=s}get(){return this.storage.get()}set(s){const t=(s=>{const t=s.split(".");if(3!==t.length||!t[1])throw new Error("Invalid access token format");const e=JSON.parse("undefined"!=typeof atob?atob(t[1]):Buffer.from(t[1],"base64").toString("utf-8")),a="number"==typeof e.iat?1e3*e.iat:void 0,n="number"==typeof e.exp?1e3*e.exp:void 0,r=e["https://hasura.io/jwt/claims"],i=r?Object.entries(r).reduce(((s,[t,e])=>("string"==typeof e&&h(e)?s[t]=l(e):s[t]=e,s)),{}):void 0;return{...e,iat:a,exp:n,"https://hasura.io/jwt/claims":i}})(s.accessToken),e={...s,decodedToken:t};this.storage.set(e),this.notifySubscribers(e)}remove(){this.storage.remove(),this.notifySubscribers(null)}onChange(s){return this.subscribers.add(s),()=>{this.subscribers.delete(s)}}notifySubscribers(s){for(const e of this.subscribers)try{e(s)}catch(t){console.error("Error notifying subscriber:",t)}}}const f=()=>"undefined"!=typeof window?new p:new w,S=({auth:s,storage:t,graphql:e,functions:n,sessionStorage:r})=>{const i=[d(s,r),c(r),a(r)];for(const a of i)s.pushChainFunction(a),t.pushChainFunction(a),e.pushChainFunction(a),n.pushChainFunction(a)},O=({auth:s,storage:t,graphql:e,functions:n,sessionStorage:r})=>{const i=[c(r),a(r)];for(const a of i)s.pushChainFunction(a),t.pushChainFunction(a),e.pushChainFunction(a),n.pushChainFunction(a)};class g{auth;storage;graphql;functions;sessionStorage;constructor(s,t,e,a,n){this.auth=s,this.storage=t,this.graphql=e,this.functions=a,this.sessionStorage=n}getUserSession(){return this.sessionStorage.get()}async refreshSession(s=60){return i(this.auth,this.sessionStorage,s)}clearSession(){this.sessionStorage.remove()}}function b(s={}){const{subdomain:a,region:n,authUrl:r,storageUrl:i,graphqlUrl:o,functionsUrl:u,storage:d=f(),configure:c=[]}=s,h=new y(d),l=m("auth",a,n,r),p=m("storage",a,n,i),w=m("graphql",a,n,o),S=m("functions",a,n,u),O=((s,a=[])=>{let n=t(a);return{baseURL:s,pushChainFunction:s=>{a.push(s),n=t(a)},getJWKs:async t=>{const a=`${s}/.well-known/jwks.json`,r=await n(a,{...t,method:"GET",headers:{...t?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),t=s?JSON.parse(s):{};throw new e(t,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},elevateWebauthn:async t=>{const a=`${s}/elevate/webauthn`,r=await n(a,{...t,method:"POST",headers:{...t?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),t=s?JSON.parse(s):{};throw new e(t,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},verifyElevateWebauthn:async(t,a)=>{const r=`${s}/elevate/webauthn/verify`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},healthCheckGet:async t=>{const a=`${s}/healthz`,r=await n(a,{...t,method:"GET",headers:{...t?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),t=s?JSON.parse(s):{};throw new e(t,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},healthCheckHead:async t=>{const a=`${s}/healthz`,r=await n(a,{...t,method:"HEAD",headers:{...t?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),t=s?JSON.parse(s):{};throw new e(t,r.status,r.headers)}return{body:void 0,status:r.status,headers:r.headers}},linkIdToken:async(t,a)=>{const r=`${s}/link/idtoken`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},changeUserMfa:async t=>{const a=`${s}/mfa/totp/generate`,r=await n(a,{...t,method:"GET",headers:{...t?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),t=s?JSON.parse(s):{};throw new e(t,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},createPAT:async(t,a)=>{const r=`${s}/pat`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInAnonymous:async(t,a)=>{const r=`${s}/signin/anonymous`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInEmailPassword:async(t,a)=>{const r=`${s}/signin/email-password`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInIdToken:async(t,a)=>{const r=`${s}/signin/idtoken`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},verifySignInMfaTotp:async(t,a)=>{const r=`${s}/signin/mfa/totp`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInOTPEmail:async(t,a)=>{const r=`${s}/signin/otp/email`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},verifySignInOTPEmail:async(t,a)=>{const r=`${s}/signin/otp/email/verify`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInPasswordlessEmail:async(t,a)=>{const r=`${s}/signin/passwordless/email`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInPasswordlessSms:async(t,a)=>{const r=`${s}/signin/passwordless/sms`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},verifySignInPasswordlessSms:async(t,a)=>{const r=`${s}/signin/passwordless/sms/otp`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInPAT:async(t,a)=>{const r=`${s}/signin/pat`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInProviderURL:(t,e)=>{const a=e&&Object.entries(e).map((([s,t])=>{const e=Array.isArray(t)?t.join(","):"object"==typeof t?JSON.stringify(t):t;return`${s}=${encodeURIComponent(e)}`})).join("&");return a?`${s}/signin/provider/${t}?${a}`:`${s}/signin/provider/${t}`},getProviderTokens:async(t,a)=>{const r=`${s}/signin/provider/${t}/callback/tokens`,i=await n(r,{...a,method:"GET",headers:{...a?.headers}});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInWebauthn:async(t,a)=>{const r=`${s}/signin/webauthn`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},verifySignInWebauthn:async(t,a)=>{const r=`${s}/signin/webauthn/verify`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signOut:async(t,a)=>{const r=`${s}/signout`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signUpEmailPassword:async(t,a)=>{const r=`${s}/signup/email-password`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signUpWebauthn:async(t,a)=>{const r=`${s}/signup/webauthn`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},verifySignUpWebauthn:async(t,a)=>{const r=`${s}/signup/webauthn/verify`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},refreshToken:async(t,a)=>{const r=`${s}/token`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},refreshProviderToken:async(t,a,r)=>{const i=`${s}/token/provider/${t}`,o=await n(i,{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(a)});if(o.status>=300){const s=[412].includes(o.status)?null:await o.text(),t=s?JSON.parse(s):{};throw new e(t,o.status,o.headers)}const u=[204,205,304].includes(o.status)?null:await o.text();return{body:u?JSON.parse(u):{},status:o.status,headers:o.headers}},verifyToken:async(t,a)=>{const r=`${s}/token/verify`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},getUser:async t=>{const a=`${s}/user`,r=await n(a,{...t,method:"GET",headers:{...t?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),t=s?JSON.parse(s):{};throw new e(t,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},deanonymizeUser:async(t,a)=>{const r=`${s}/user/deanonymize`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},changeUserEmail:async(t,a)=>{const r=`${s}/user/email/change`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},sendVerificationEmail:async(t,a)=>{const r=`${s}/user/email/send-verification-email`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},verifyChangeUserMfa:async(t,a)=>{const r=`${s}/user/mfa`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},changeUserPassword:async(t,a)=>{const r=`${s}/user/password`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},sendPasswordResetEmail:async(t,a)=>{const r=`${s}/user/password/reset`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},addSecurityKey:async t=>{const a=`${s}/user/webauthn/add`,r=await n(a,{...t,method:"POST",headers:{...t?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),t=s?JSON.parse(s):{};throw new e(t,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},verifyAddSecurityKey:async(t,a)=>{const r=`${s}/user/webauthn/verify`,i=await n(r,{...a,method:"POST",headers:{"Content-Type":"application/json",...a?.headers},body:JSON.stringify(t)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},verifyTicketURL:t=>{const e=t&&Object.entries(t).map((([s,t])=>{const e=Array.isArray(t)?t.join(","):"object"==typeof t?JSON.stringify(t):t;return`${s}=${encodeURIComponent(e)}`})).join("&");return e?`${s}/verify?${e}`:`${s}/verify`},getVersion:async t=>{const a=`${s}/version`,r=await n(a,{...t,method:"GET",headers:{...t?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),t=s?JSON.parse(s):{};throw new e(t,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}}}})(l),b=((s,a=[])=>{let n=t(a);return{baseURL:s,pushChainFunction:s=>{a.push(s),n=t(a)},uploadFiles:async(t,a)=>{const r=`${s}/files`,i=new FormData;void 0!==t["bucket-id"]&&i.append("bucket-id",t["bucket-id"]),void 0!==t["metadata[]"]&&t["metadata[]"].forEach((s=>{i.append("metadata[]",new Blob([JSON.stringify(s)],{type:"application/json"}),"")})),void 0!==t["file[]"]&&t["file[]"].forEach((s=>{i.append("file[]",s)}));const o=await n(r,{...a,method:"POST",body:i});if(o.status>=300){const s=[412].includes(o.status)?null:await o.text(),t=s?JSON.parse(s):{};throw new e(t,o.status,o.headers)}const u=[204,205,304].includes(o.status)?null:await o.text();return{body:u?JSON.parse(u):{},status:o.status,headers:o.headers}},deleteFile:async(t,a)=>{const r=`${s}/files/${t}`,i=await n(r,{...a,method:"DELETE",headers:{...a?.headers}});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}return{body:void 0,status:i.status,headers:i.headers}},getFile:async(t,a,r)=>{const i=a&&Object.entries(a).map((([s,t])=>{const e=Array.isArray(t)?t.join(","):"object"==typeof t?JSON.stringify(t):t;return`${s}=${encodeURIComponent(e)}`})).join("&"),o=i?`${s}/files/${t}?${i}`:`${s}/files/${t}`,u=await n(o,{...r,method:"GET",headers:{...r?.headers}});if(u.status>=300){const s=[412].includes(u.status)?null:await u.text(),t=s?JSON.parse(s):{};throw new e(t,u.status,u.headers)}return{body:await u.blob(),status:u.status,headers:u.headers}},getFileMetadataHeaders:async(t,a,r)=>{const i=a&&Object.entries(a).map((([s,t])=>{const e=Array.isArray(t)?t.join(","):"object"==typeof t?JSON.stringify(t):t;return`${s}=${encodeURIComponent(e)}`})).join("&"),o=i?`${s}/files/${t}?${i}`:`${s}/files/${t}`,u=await n(o,{...r,method:"HEAD",headers:{...r?.headers}});if(u.status>=300){const s=[412].includes(u.status)?null:await u.text(),t=s?JSON.parse(s):{};throw new e(t,u.status,u.headers)}return{body:void 0,status:u.status,headers:u.headers}},replaceFile:async(t,a,r)=>{const i=`${s}/files/${t}`,o=new FormData;void 0!==a.metadata&&o.append("metadata",new Blob([JSON.stringify(a.metadata)],{type:"application/json"}),""),void 0!==a.file&&o.append("file",a.file);const u=await n(i,{...r,method:"PUT",body:o});if(u.status>=300){const s=[412].includes(u.status)?null:await u.text(),t=s?JSON.parse(s):{};throw new e(t,u.status,u.headers)}const d=[204,205,304].includes(u.status)?null:await u.text();return{body:d?JSON.parse(d):{},status:u.status,headers:u.headers}},getFilePresignedURL:async(t,a)=>{const r=`${s}/files/${t}/presignedurl`,i=await n(r,{...a,method:"GET",headers:{...a?.headers}});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),t=s?JSON.parse(s):{};throw new e(t,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},deleteBrokenMetadata:async t=>{const a=`${s}/ops/delete-broken-metadata`,r=await n(a,{...t,method:"POST",headers:{...t?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),t=s?JSON.parse(s):{};throw new e(t,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},deleteOrphanedFiles:async t=>{const a=`${s}/ops/delete-orphans`,r=await n(a,{...t,method:"POST",headers:{...t?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),t=s?JSON.parse(s):{};throw new e(t,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},listBrokenMetadata:async t=>{const a=`${s}/ops/list-broken-metadata`,r=await n(a,{...t,method:"POST",headers:{...t?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),t=s?JSON.parse(s):{};throw new e(t,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},listFilesNotUploaded:async t=>{const a=`${s}/ops/list-not-uploaded`,r=await n(a,{...t,method:"POST",headers:{...t?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),t=s?JSON.parse(s):{};throw new e(t,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},listOrphanedFiles:async t=>{const a=`${s}/ops/list-orphans`,r=await n(a,{...t,method:"POST",headers:{...t?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),t=s?JSON.parse(s):{};throw new e(t,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},getVersion:async t=>{const a=`${s}/version`,r=await n(a,{...t,method:"GET",headers:{...t?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),t=s?JSON.parse(s):{};throw new e(t,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}}}})(p,[]),N=((s,a=[])=>{let n=t(a);const r=async(t,a)=>{const r=await n(`${s}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),...a}),i=await r.text(),o=i?JSON.parse(i):{},u={body:o,status:r.status,headers:r.headers};if(o.errors)throw new e(o,r.status,r.headers);return u};return{request:function(s,t,e){if("object"==typeof s&&"kind"in s){const a=s.definitions[0],n={query:s.loc?.source.body||"",variables:t,operationName:a&&"name"in a?a.name?.value:void 0};return r(n,e)}return r(s,t)},url:s,pushChainFunction:s=>{a.push(s),n=t(a)}}})(w,[]),J=((s,a=[])=>{let n=t(a);const r=async(t,a)=>{const r=await n(`${s}${t}`,a);let i;if(i=r.headers.get("content-type")?.includes("application/json")?await r.json():r.headers.get("content-type")?.startsWith("text/")?await r.text():await r.blob(),!r.ok)throw new e(i,r.status,r.headers);return{status:r.status,body:i,headers:r.headers}};return{baseURL:s,fetch:r,post:async(s,t,e={})=>{const a={...e,method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",...e.headers},body:t?JSON.stringify(t):void 0};return r(s,a)},pushChainFunction:s=>{a.push(s),n=t(a)}}})(S,[]);for(const t of c)t({auth:O,storage:b,graphql:N,functions:J,sessionStorage:h});return new g(O,b,N,J,h)}const m=(s,t,e,a)=>a||(t&&e?`https://${t}.${s}.${e}.nhost.run/v1`:`https://local.${s}.local.nhost.run/v1`);s.createClient=function(s={}){const t=s.storage??f();return b({...s,storage:t,configure:[S,...s.configure??[]]})},s.createNhostClient=b,s.createServerClient=function(s){return b({...s,configure:[O,...s.configure??[]]})},s.generateServiceUrl=m,s.withAdminSession=function(s){return({storage:t,graphql:e,functions:a})=>{const n=(r=s,s=>async(t,e={})=>{const a=new Headers(e.headers||{});if(a.has("x-hasura-admin-secret")||a.set("x-hasura-admin-secret",r.adminSecret),r.role&&!a.has("x-hasura-role")&&a.set("x-hasura-role",r.role),r.sessionVariables)for(const[s,n]of Object.entries(r.sessionVariables)){const t=s.startsWith("x-hasura-")?s:`x-hasura-${s}`;a.has(t)||a.set(t,n)}return s(t,{...e,headers:a})});var r;t.pushChainFunction(n),e.pushChainFunction(n),a.pushChainFunction(n)}},s.withClientSideSessionMiddleware=S,s.withServerSideSessionMiddleware=O,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})}));
|
|
2
2
|
//# sourceMappingURL=nhost-js.umd.js.map
|