@nhost/nhost-js 2.1.2 → 2.2.1
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/clients/functions/index.d.ts +33 -2
- package/dist/clients/functions/index.d.ts.map +1 -1
- package/dist/clients/functions/types.d.ts +3 -3
- package/dist/clients/functions/types.d.ts.map +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.esm.js +61 -52
- package/dist/index.esm.js.map +1 -1
- package/dist/utils/types.d.ts +22 -3
- package/dist/utils/types.d.ts.map +1 -1
- package/package.json +6 -5
- package/umd/nhost-js.umd.js +1 -1
- package/umd/nhost-js.umd.js.map +1 -1
|
@@ -13,16 +13,47 @@ export declare class NhostFunctionsClient {
|
|
|
13
13
|
private adminSecret?;
|
|
14
14
|
constructor(params: NhostFunctionsConstructorParams);
|
|
15
15
|
/**
|
|
16
|
-
* Use `nhost.functions.call` to call (sending a POST request to) a serverless function.
|
|
16
|
+
* Use `nhost.functions.call` to call (sending a POST request to) a serverless function. Use generic
|
|
17
|
+
* types to specify the expected response data, request body and error message.
|
|
17
18
|
*
|
|
18
19
|
* @example
|
|
20
|
+
* ### Without generic types
|
|
19
21
|
* ```ts
|
|
20
22
|
* await nhost.functions.call('send-welcome-email', { email: 'joe@example.com', name: 'Joe Doe' })
|
|
21
23
|
* ```
|
|
22
24
|
*
|
|
25
|
+
* @example
|
|
26
|
+
* ### Using generic types
|
|
27
|
+
* ```ts
|
|
28
|
+
* type Data = {
|
|
29
|
+
* message: string
|
|
30
|
+
* }
|
|
31
|
+
*
|
|
32
|
+
* type Body = {
|
|
33
|
+
* email: string
|
|
34
|
+
* name: string
|
|
35
|
+
* }
|
|
36
|
+
*
|
|
37
|
+
* type ErrorMessage = {
|
|
38
|
+
* details: string
|
|
39
|
+
* }
|
|
40
|
+
*
|
|
41
|
+
* // The function will only accept a body of type `Body`
|
|
42
|
+
* const { res, error } = await nhost.functions.call<Data, Body, ErrorMessage>(
|
|
43
|
+
* 'send-welcome-email',
|
|
44
|
+
* { email: 'joe@example.com', name: 'Joe Doe' }
|
|
45
|
+
* )
|
|
46
|
+
*
|
|
47
|
+
* // Now the response data is typed as `Data`
|
|
48
|
+
* console.log(res?.data.message)
|
|
49
|
+
*
|
|
50
|
+
* // Now the error message is typed as `ErrorMessage`
|
|
51
|
+
* console.log(error?.message.details)
|
|
52
|
+
* ```
|
|
53
|
+
*
|
|
23
54
|
* @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call
|
|
24
55
|
*/
|
|
25
|
-
call<
|
|
56
|
+
call<TData = unknown, TBody = any, TErrorMessage = any>(url: string, body?: TBody | null, config?: NhostFunctionCallConfig): Promise<NhostFunctionCallResponse<TData, TErrorMessage>>;
|
|
26
57
|
/**
|
|
27
58
|
* Use `nhost.functions.setAccessToken` to a set an access token to be used in subsequent functions requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically.
|
|
28
59
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/clients/functions/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAA;AAChE,OAAO,EACL,uBAAuB,EACvB,yBAAyB,EACzB,+BAA+B,EAChC,MAAM,SAAS,CAAA;AAChB;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,4BAA4B,wBAWzE;AAED;;GAEG;AACH,qBAAa,oBAAoB;IAC/B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,OAAO,CAAC,WAAW,CAAe;IAClC,OAAO,CAAC,WAAW,CAAC,CAAQ;gBAEhB,MAAM,EAAE,+BAA+B;IAQnD
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/clients/functions/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAA;AAChE,OAAO,EACL,uBAAuB,EACvB,yBAAyB,EACzB,+BAA+B,EAChC,MAAM,SAAS,CAAA;AAChB;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,4BAA4B,wBAWzE;AAED;;GAEG;AACH,qBAAa,oBAAoB;IAC/B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,OAAO,CAAC,WAAW,CAAe;IAClC,OAAO,CAAC,WAAW,CAAC,CAAQ;gBAEhB,MAAM,EAAE,+BAA+B;IAQnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAwCG;IACG,IAAI,CAAC,KAAK,GAAG,OAAO,EAAE,KAAK,GAAG,GAAG,EAAE,aAAa,GAAG,GAAG,EAC1D,GAAG,EAAE,MAAM,EACX,IAAI,CAAC,EAAE,KAAK,GAAG,IAAI,EACnB,MAAM,CAAC,EAAE,uBAAuB,GAC/B,OAAO,CAAC,yBAAyB,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;IA4D3D;;;;;;;;;OASG;IACH,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS;IAS9C,0BAA0B,IAAI,uBAAuB,CAAC,SAAS,CAAC;CAajE"}
|
|
@@ -9,16 +9,16 @@ export interface NhostFunctionsConstructorParams {
|
|
|
9
9
|
*/
|
|
10
10
|
adminSecret?: string;
|
|
11
11
|
}
|
|
12
|
-
export type NhostFunctionCallResponse<
|
|
12
|
+
export type NhostFunctionCallResponse<TData = unknown, TErrorMessage = any> = {
|
|
13
13
|
res: {
|
|
14
|
-
data:
|
|
14
|
+
data: TData;
|
|
15
15
|
status: number;
|
|
16
16
|
statusText: string;
|
|
17
17
|
};
|
|
18
18
|
error: null;
|
|
19
19
|
} | {
|
|
20
20
|
res: null;
|
|
21
|
-
error: ErrorPayload
|
|
21
|
+
error: ErrorPayload<TErrorMessage>;
|
|
22
22
|
};
|
|
23
23
|
/** Subset of RequestInit parameters that are supported by the functions client */
|
|
24
24
|
export interface NhostFunctionCallConfig {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/clients/functions/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAEhD,MAAM,WAAW,+BAA+B;IAC9C;;OAEG;IACH,GAAG,EAAE,MAAM,CAAA;IACX;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,MAAM,MAAM,yBAAyB,CAAC,
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/clients/functions/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAEhD,MAAM,WAAW,+BAA+B;IAC9C;;OAEG;IACH,GAAG,EAAE,MAAM,CAAA;IACX;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,MAAM,MAAM,yBAAyB,CAAC,KAAK,GAAG,OAAO,EAAE,aAAa,GAAG,GAAG,IACtE;IACE,GAAG,EAAE;QACH,IAAI,EAAE,KAAK,CAAA;QACX,MAAM,EAAE,MAAM,CAAA;QACd,UAAU,EAAE,MAAM,CAAA;KACnB,CAAA;IACD,KAAK,EAAE,IAAI,CAAA;CACZ,GACD;IACE,GAAG,EAAE,IAAI,CAAA;IACT,KAAK,EAAE,YAAY,CAAC,aAAa,CAAC,CAAA;CACnC,CAAA;AAEL,kFAAkF;AAClF,MAAM,WAAW,uBAAuB;IACtC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CACjC"}
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("@nhost/hasura-auth-js"),g=require("@nhost/hasura-storage-js"),U=require("isomorphic-unfetch"),C=require("@nhost/graphql-js"),A=/^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;function d(t,e){const{backendUrl:i,subdomain:
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("@nhost/hasura-auth-js"),g=require("@nhost/hasura-storage-js"),U=require("isomorphic-unfetch"),C=require("@nhost/graphql-js"),A=/^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;function d(t,e){const{backendUrl:i,subdomain:s,region:l}=t;if(i)return`${i}/v1/${e}`;if(!s)throw new Error("Either `backendUrl` or `subdomain` must be set.");const c=s.match(A);if(c!=null&&c.groups){const{protocol:o,host:u,port:r}=c.groups,n=v(e);return n||(u==="localhost"?(console.warn('The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.'),`${o||"http"}://localhost:${r||1337}/v1/${e}`):r?`${o||"https"}://local.${e}.nhost.run:${r}/v1`:`${o||"https"}://local.${e}.nhost.run/v1`)}if(!l)throw new Error('`region` must be set when using a `subdomain` other than "local".');return`https://${s}.${e}.${l}.nhost.run/v1`}function m(){return typeof window<"u"}function $(){return typeof process<"u"&&process.env}function v(t){return m()||!$()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function y(t,e){const s=e.startsWith("/")?e:`/${e}`;return t+s}function p(t){const e="subdomain"in t||"backendUrl"in t?d(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new f.HasuraAuthClient({url:e,...t})}function b(t){const e="subdomain"in t||"backendUrl"in t?d(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new w({url:e,...t})}class w{constructor(e){const{url:i,adminSecret:s}=e;this.url=i,this.accessToken=null,this.adminSecret=s}async call(e,i,s){var o,u;const l={"Content-Type":"application/json",...this.generateAccessTokenHeaders(),...s==null?void 0:s.headers},c=y(this.url,e);try{const r=await U(c,{body:i?JSON.stringify(i):null,headers:l,method:"POST"});if(!r.ok){let a;return(o=r.headers.get("content-type"))!=null&&o.includes("application/json")?a=await r.json():a=await r.text(),{res:null,error:{message:a,error:r.statusText,status:r.status}}}let n;return(u=r.headers.get("content-type"))!=null&&u.includes("application/json")?n=await r.json():n=await r.text(),{res:{data:n,status:r.status,statusText:r.statusText},error:null}}catch(r){const n=r;return{res:null,error:{message:n.message,status:n.name==="AbortError"?0:500,error:n.name==="AbortError"?"abort-error":"unknown"}}}}setAccessToken(e){if(!e){this.accessToken=null;return}this.accessToken=e}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function T(t){const e="subdomain"in t||"backendUrl"in t?d(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new C.NhostGraphqlClient({url:e,...t})}function k(t){const e="subdomain"in t||"backendUrl"in t?d(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new g.HasuraStorageClient({url:e,...t})}const q=t=>new S(t);class S{constructor({refreshIntervalTime:e,clientStorage:i,clientStorageType:s,autoRefreshToken:l,autoSignIn:c,adminSecret:o,devTools:u,start:r=!0,...n}){this.auth=p({refreshIntervalTime:e,clientStorage:i,clientStorageType:s,autoRefreshToken:l,autoSignIn:c,start:r,...n}),this.storage=k({adminSecret:o,...n}),this.functions=b({adminSecret:o,...n}),this.graphql=T({adminSecret:o,...n}),this.auth.onAuthStateChanged((a,h)=>{a==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(a=>{const h=a==null?void 0:a.accessToken;this.storage.setAccessToken(h),this.functions.setAccessToken(h),this.graphql.setAccessToken(h)}),this._adminSecret=o,this.devTools=u}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}exports.NhostClient=S;exports.NhostFunctionsClient=w;exports.createAuthClient=p;exports.createFunctionsClient=b;exports.createGraphqlClient=T;exports.createNhostClient=q;exports.createStorageClient=k;for(const t in f)t!=="default"&&!Object.prototype.hasOwnProperty.call(exports,t)&&Object.defineProperty(exports,t,{enumerable:!0,get:()=>f[t]});for(const t in g)t!=="default"&&!Object.prototype.hasOwnProperty.call(exports,t)&&Object.defineProperty(exports,t,{enumerable:!0,get:()=>g[t]});
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/utils/helpers.ts","../src/clients/auth.ts","../src/clients/functions/index.ts","../src/clients/graphql.ts","../src/clients/storage.ts","../src/clients/nhost.ts"],"sourcesContent":["import { NhostClientConstructorParams } from './types'\n\n// a port can be a number or a placeholder string with leading and trailing double underscores, f.e. \"8080\" or \"__PLACEHOLDER_NAME__\"\nexport const LOCALHOST_REGEX =\n /^((?<protocol>http[s]?):\\/\\/)?(?<host>(localhost|local))(:(?<port>(\\d+|__\\w+__)))?$/\n\n/**\n * `backendUrl` should now be used only when self-hosting\n * `subdomain` and `region` should be used instead when using the Nhost platform\n * `\n * @param backendOrSubdomain\n * @param service\n * @returns\n */\nexport function urlFromSubdomain(\n backendOrSubdomain: Pick<NhostClientConstructorParams, 'region' | 'subdomain' | 'backendUrl'>,\n service: string\n): string {\n const { backendUrl, subdomain, region } = backendOrSubdomain\n\n if (backendUrl) {\n return `${backendUrl}/v1/${service}`\n }\n\n if (!subdomain) {\n throw new Error('Either `backendUrl` or `subdomain` must be set.')\n }\n\n // check if subdomain is [http[s]://]localhost[:port] or [http[s]://]local[:port]\n const subdomainLocalhostFound = subdomain.match(LOCALHOST_REGEX)\n if (subdomainLocalhostFound?.groups) {\n const { protocol, host, port } = subdomainLocalhostFound.groups\n\n const urlFromEnv = getValueFromEnv(service)\n if (urlFromEnv) {\n return urlFromEnv\n }\n\n if (host === 'localhost') {\n console.warn(\n 'The `subdomain` is set to \"localhost\". Support for this will be removed in a future release. Please use \"local\" instead.'\n )\n\n return `${protocol || 'http'}://localhost:${port || 1337}/v1/${service}`\n }\n\n return port\n ? `${protocol || 'https'}://local.${service}.nhost.run:${port}/v1`\n : `${protocol || 'https'}://local.${service}.nhost.run/v1`\n }\n\n if (!region) {\n throw new Error('`region` must be set when using a `subdomain` other than \"local\".')\n }\n\n return `https://${subdomain}.${service}.${region}.nhost.run/v1`\n}\n\n/**\n *\n * @returns whether the code is running in a browser\n */\nfunction isBrowser(): boolean {\n return typeof window !== 'undefined'\n}\n\n/**\n *\n * @returns whether the code is running in a Node.js environment\n */\nfunction environmentIsAvailable() {\n return typeof process !== 'undefined' && process.env\n}\n\n/**\n *\n * @param service auth | storage | graphql | functions\n * @returns the service's url if the corresponding env var is set\n * NHOST_${service}_URL\n */\nfunction getValueFromEnv(service: string) {\n if (isBrowser() || !environmentIsAvailable()) {\n return null\n }\n\n return process.env[`NHOST_${service.toUpperCase()}_URL`]\n}\n\n/**\n * Combines a base URL and a path into a single URL string.\n *\n * @param baseUrl - The base URL to use.\n * @param path - The path to append to the base URL.\n * @returns The combined URL string.\n */\nexport function buildUrl(baseUrl: string, path: string) {\n const hasLeadingSlash = path.startsWith('/')\n const urlPath = hasLeadingSlash ? path : `/${path}`\n return baseUrl + urlPath\n}\n","import { HasuraAuthClient } from '@nhost/hasura-auth-js'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for Auth from either a subdomain or a URL\n */\nexport function createAuthClient(params: NhostClientConstructorParams) {\n const authUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'auth')\n : params.authUrl\n\n if (!authUrl) {\n throw new Error('Please provide `subdomain` or `authUrl`.')\n }\n\n return new HasuraAuthClient({ url: authUrl, ...params })\n}\n","import fetch from 'isomorphic-unfetch'\nimport { buildUrl, urlFromSubdomain } from '../../utils/helpers'\nimport { NhostClientConstructorParams } from '../../utils/types'\nimport {\n NhostFunctionCallConfig,\n NhostFunctionCallResponse,\n NhostFunctionsConstructorParams\n} from './types'\n/**\n * Creates a client for Functions from either a subdomain or a URL\n */\nexport function createFunctionsClient(params: NhostClientConstructorParams) {\n const functionsUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'functions')\n : params.functionsUrl\n\n if (!functionsUrl) {\n throw new Error('Please provide `subdomain` or `functionsUrl`.')\n }\n\n return new NhostFunctionsClient({ url: functionsUrl, ...params })\n}\n\n/**\n * @alias Functions\n */\nexport class NhostFunctionsClient {\n readonly url: string\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostFunctionsConstructorParams) {\n const { url, adminSecret } = params\n\n this.url = url\n this.accessToken = null\n this.adminSecret = adminSecret\n }\n\n /**\n * Use `nhost.functions.call` to call (sending a POST request to) a serverless function.\n *\n * @example\n * ```ts\n * await nhost.functions.call('send-welcome-email', { email: 'joe@example.com', name: 'Joe Doe' })\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call\n */\n async call<T = unknown, D = any>(\n url: string,\n body: D | null,\n config?: NhostFunctionCallConfig\n ): Promise<NhostFunctionCallResponse<T>> {\n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n const fullUrl = buildUrl(this.url, url)\n\n try {\n const result = await fetch(fullUrl, {\n body: body ? JSON.stringify(body) : null,\n headers,\n method: 'POST'\n })\n\n if (!result.ok) {\n throw new Error(result.statusText)\n }\n\n let data: T\n\n if (result.headers.get('content-type')?.includes('application/json')) {\n data = await result.json()\n } else {\n data = (await result.text()) as unknown as T\n }\n\n return {\n res: { data, status: result.status, statusText: result.statusText },\n error: null\n }\n } catch (e) {\n const error = e as Error\n return {\n res: null,\n error: {\n message: error.message,\n status: error.name === 'AbortError' ? 0 : 500,\n error: error.name === 'AbortError' ? 'abort-error' : 'unknown'\n }\n }\n }\n }\n\n /**\n * Use `nhost.functions.setAccessToken` to a set an access token to be used in subsequent functions requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically.\n *\n * @example\n * ```ts\n * nhost.functions.setAccessToken('some-access-token')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/set-access-token\n */\n setAccessToken(accessToken: string | undefined) {\n if (!accessToken) {\n this.accessToken = null\n return\n }\n\n this.accessToken = accessToken\n }\n\n generateAccessTokenHeaders(): NhostFunctionCallConfig['headers'] {\n if (this.adminSecret) {\n return {\n 'x-hasura-admin-secret': this.adminSecret\n }\n }\n if (this.accessToken) {\n return {\n Authorization: `Bearer ${this.accessToken}`\n }\n }\n return {}\n }\n}\n","import { NhostGraphqlClient } from '@nhost/graphql-js'\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for GraphQL from either a subdomain or a URL\n */\nexport function createGraphqlClient(params: NhostClientConstructorParams) {\n const graphqlUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'graphql')\n : params.graphqlUrl\n\n if (!graphqlUrl) {\n throw new Error('Please provide `subdomain` or `graphqlUrl`.')\n }\n\n return new NhostGraphqlClient({ url: graphqlUrl, ...params })\n}\n","import { HasuraStorageClient } from '@nhost/hasura-storage-js'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for Storage from either a subdomain or a URL\n */\nexport function createStorageClient(params: NhostClientConstructorParams) {\n const storageUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'storage')\n : params.storageUrl\n\n if (!storageUrl) {\n throw new Error('Please provide `subdomain` or `storageUrl`.')\n }\n\n return new HasuraStorageClient({ url: storageUrl, ...params })\n}\n","import { NhostGraphqlClient } from '@nhost/graphql-js'\nimport { HasuraAuthClient } from '@nhost/hasura-auth-js'\nimport { HasuraStorageClient } from '@nhost/hasura-storage-js'\nimport { NhostClientConstructorParams } from '../utils/types'\nimport { createAuthClient } from './auth'\nimport { createFunctionsClient, NhostFunctionsClient } from './functions'\nimport { createGraphqlClient } from './graphql'\nimport { createStorageClient } from './storage'\n\nexport const createNhostClient = (params: NhostClientConstructorParams) => new NhostClient(params)\n\nexport class NhostClient {\n auth: HasuraAuthClient\n storage: HasuraStorageClient\n functions: NhostFunctionsClient\n graphql: NhostGraphqlClient\n private _adminSecret?: string\n readonly devTools?: boolean\n\n /**\n * Nhost Client\n *\n * @example\n * ```ts\n * const nhost = new NhostClient({ subdomain, region });\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript\n */\n constructor({\n refreshIntervalTime,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n adminSecret,\n devTools,\n start = true,\n ...urlParams\n }: NhostClientConstructorParams) {\n // * Set clients for all services\n this.auth = createAuthClient({\n refreshIntervalTime,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n start,\n ...urlParams\n })\n this.storage = createStorageClient({ adminSecret, ...urlParams })\n this.functions = createFunctionsClient({ adminSecret, ...urlParams })\n this.graphql = createGraphqlClient({ adminSecret, ...urlParams })\n\n this.auth.onAuthStateChanged((_event, session) => {\n if (_event === 'SIGNED_OUT') {\n this.storage.setAccessToken(undefined)\n this.functions.setAccessToken(undefined)\n this.graphql.setAccessToken(undefined)\n }\n })\n\n // * Update access token for clients, including when signin in\n this.auth.onTokenChanged((session) => {\n const accessToken = session?.accessToken\n this.storage.setAccessToken(accessToken)\n this.functions.setAccessToken(accessToken)\n this.graphql.setAccessToken(accessToken)\n })\n\n this._adminSecret = adminSecret\n this.devTools = devTools\n }\n\n get adminSecret(): string | undefined {\n return this._adminSecret\n }\n\n set adminSecret(newValue: string | undefined) {\n this._adminSecret = newValue\n this.storage.setAdminSecret(newValue)\n // TODO inconsistent API: storage can change admin secret, but functions/graphql cannot\n // this.functions.setAdminSecret(newValue)\n // this.graphql.setAdminSecret(newValue)\n }\n}\n"],"names":["LOCALHOST_REGEX","urlFromSubdomain","backendOrSubdomain","service","backendUrl","subdomain","region","subdomainLocalhostFound","protocol","host","port","urlFromEnv","getValueFromEnv","isBrowser","environmentIsAvailable","buildUrl","baseUrl","path","urlPath","createAuthClient","params","authUrl","HasuraAuthClient","createFunctionsClient","functionsUrl","NhostFunctionsClient","url","adminSecret","body","config","headers","fullUrl","result","fetch","data","_a","e","error","accessToken","createGraphqlClient","graphqlUrl","NhostGraphqlClient","createStorageClient","storageUrl","HasuraStorageClient","createNhostClient","NhostClient","refreshIntervalTime","clientStorage","clientStorageType","autoRefreshToken","autoSignIn","devTools","start","urlParams","_event","session","newValue"],"mappings":"8NAGaA,EACX,sFAUc,SAAAC,EACdC,EACAC,EACQ,CACR,KAAM,CAAE,WAAAC,EAAY,UAAAC,EAAW,OAAAC,CAAA,EAAWJ,EAE1C,GAAIE,EACF,MAAO,GAAGA,QAAiBD,IAG7B,GAAI,CAACE,EACG,MAAA,IAAI,MAAM,iDAAiD,EAI7D,MAAAE,EAA0BF,EAAU,MAAML,CAAe,EAC/D,GAAIO,GAAA,MAAAA,EAAyB,OAAQ,CACnC,KAAM,CAAE,SAAAC,EAAU,KAAAC,EAAM,KAAAC,CAAA,EAASH,EAAwB,OAEnDI,EAAaC,EAAgBT,CAAO,EAC1C,OAAIQ,IAIAF,IAAS,aACH,QAAA,KACN,0HAAA,EAGK,GAAGD,GAAY,sBAAsBE,GAAQ,WAAWP,KAG1DO,EACH,GAAGF,GAAY,mBAAmBL,eAAqBO,OACvD,GAAGF,GAAY,mBAAmBL,iBACxC,CAEA,GAAI,CAACG,EACG,MAAA,IAAI,MAAM,mEAAmE,EAG9E,MAAA,WAAWD,KAAaF,KAAWG,gBAC5C,CAMA,SAASO,GAAqB,CAC5B,OAAO,OAAO,OAAW,GAC3B,CAMA,SAASC,GAAyB,CACzB,OAAA,OAAO,QAAY,KAAe,QAA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V,oBAAAC,EACA,cAAAC,EACA,kBAAAC,EACA,iBAAAC,EACA,WAAAC,EACA,YAAAxB,EACA,SAAAyB,EACA,MAAAC,EAAQ,MACLC,CAAA,EAC4B,CAE/B,KAAK,KAAOnC,EAAiB,CAC3B,oBAAA4B,EACA,cAAAC,EACA,kBAAAC,EACA,iBAAAC,EACA,WAAAC,EACA,MAAAE,EACA,GAAGC,CAAA,CACJ,EACD,KAAK,QAAUZ,EAAoB,CAAE,YAAAf,EAAa,GAAG2B,EAAW,EAChE,KAAK,UAAY/B,EAAsB,CAAE,YAAAI,EAAa,GAAG2B,EAAW,EACpE,KAAK,QAAUf,EAAoB,CAAE,YAAAZ,EAAa,GAAG2B,EAAW,EAEhE,KAAK,KAAK,mBAAmB,CAACC,EAAQC,IAAY,CAC5CD,IAAW,eACR,KAAA,QAAQ,eAAe,MAAS,EAChC,KAAA,UAAU,eAAe,MAAS,EAClC,KAAA,QAAQ,eAAe,MAAS,EACvC,CACD,EAGI,KAAA,KAAK,eAAgBC,GAAY,CACpC,MAAMlB,EAAckB,GAAA,YAAAA,EAAS,YACxB,KAAA,QAAQ,eAAelB,CAAW,EAClC,KAAA,UAAU,eAAeA,CAAW,EACpC,KAAA,QAAQ,eAAeA,CAAW,CAAA,CACxC,EAED,KAAK,aAAeX,EACpB,KAAK,SAAWyB,CAClB,CAEA,IAAI,aAAkC,CACpC,OAAO,KAAK,YACd,CAEA,IAAI,YAAYK,EAA8B,CAC5C,KAAK,aAAeA,EACf,KAAA,QAAQ,eAAeA,CAAQ,CAItC,CACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/utils/helpers.ts","../src/clients/auth.ts","../src/clients/functions/index.ts","../src/clients/graphql.ts","../src/clients/storage.ts","../src/clients/nhost.ts"],"sourcesContent":["import { NhostClientConstructorParams } from './types'\n\n// a port can be a number or a placeholder string with leading and trailing double underscores, f.e. \"8080\" or \"__PLACEHOLDER_NAME__\"\nexport const LOCALHOST_REGEX =\n /^((?<protocol>http[s]?):\\/\\/)?(?<host>(localhost|local))(:(?<port>(\\d+|__\\w+__)))?$/\n\n/**\n * `backendUrl` should now be used only when self-hosting\n * `subdomain` and `region` should be used instead when using the Nhost platform\n * `\n * @param backendOrSubdomain\n * @param service\n * @returns\n */\nexport function urlFromSubdomain(\n backendOrSubdomain: Pick<NhostClientConstructorParams, 'region' | 'subdomain' | 'backendUrl'>,\n service: string\n): string {\n const { backendUrl, subdomain, region } = backendOrSubdomain\n\n if (backendUrl) {\n return `${backendUrl}/v1/${service}`\n }\n\n if (!subdomain) {\n throw new Error('Either `backendUrl` or `subdomain` must be set.')\n }\n\n // check if subdomain is [http[s]://]localhost[:port] or [http[s]://]local[:port]\n const subdomainLocalhostFound = subdomain.match(LOCALHOST_REGEX)\n if (subdomainLocalhostFound?.groups) {\n const { protocol, host, port } = subdomainLocalhostFound.groups\n\n const urlFromEnv = getValueFromEnv(service)\n if (urlFromEnv) {\n return urlFromEnv\n }\n\n if (host === 'localhost') {\n console.warn(\n 'The `subdomain` is set to \"localhost\". Support for this will be removed in a future release. Please use \"local\" instead.'\n )\n\n return `${protocol || 'http'}://localhost:${port || 1337}/v1/${service}`\n }\n\n return port\n ? `${protocol || 'https'}://local.${service}.nhost.run:${port}/v1`\n : `${protocol || 'https'}://local.${service}.nhost.run/v1`\n }\n\n if (!region) {\n throw new Error('`region` must be set when using a `subdomain` other than \"local\".')\n }\n\n return `https://${subdomain}.${service}.${region}.nhost.run/v1`\n}\n\n/**\n *\n * @returns whether the code is running in a browser\n */\nfunction isBrowser(): boolean {\n return typeof window !== 'undefined'\n}\n\n/**\n *\n * @returns whether the code is running in a Node.js environment\n */\nfunction environmentIsAvailable() {\n return typeof process !== 'undefined' && process.env\n}\n\n/**\n *\n * @param service auth | storage | graphql | functions\n * @returns the service's url if the corresponding env var is set\n * NHOST_${service}_URL\n */\nfunction getValueFromEnv(service: string) {\n if (isBrowser() || !environmentIsAvailable()) {\n return null\n }\n\n return process.env[`NHOST_${service.toUpperCase()}_URL`]\n}\n\n/**\n * Combines a base URL and a path into a single URL string.\n *\n * @param baseUrl - The base URL to use.\n * @param path - The path to append to the base URL.\n * @returns The combined URL string.\n */\nexport function buildUrl(baseUrl: string, path: string) {\n const hasLeadingSlash = path.startsWith('/')\n const urlPath = hasLeadingSlash ? path : `/${path}`\n return baseUrl + urlPath\n}\n","import { HasuraAuthClient } from '@nhost/hasura-auth-js'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for Auth from either a subdomain or a URL\n */\nexport function createAuthClient(params: NhostClientConstructorParams) {\n const authUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'auth')\n : params.authUrl\n\n if (!authUrl) {\n throw new Error('Please provide `subdomain` or `authUrl`.')\n }\n\n return new HasuraAuthClient({ url: authUrl, ...params })\n}\n","import fetch from 'isomorphic-unfetch'\nimport { buildUrl, urlFromSubdomain } from '../../utils/helpers'\nimport { NhostClientConstructorParams } from '../../utils/types'\nimport {\n NhostFunctionCallConfig,\n NhostFunctionCallResponse,\n NhostFunctionsConstructorParams\n} from './types'\n/**\n * Creates a client for Functions from either a subdomain or a URL\n */\nexport function createFunctionsClient(params: NhostClientConstructorParams) {\n const functionsUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'functions')\n : params.functionsUrl\n\n if (!functionsUrl) {\n throw new Error('Please provide `subdomain` or `functionsUrl`.')\n }\n\n return new NhostFunctionsClient({ url: functionsUrl, ...params })\n}\n\n/**\n * @alias Functions\n */\nexport class NhostFunctionsClient {\n readonly url: string\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostFunctionsConstructorParams) {\n const { url, adminSecret } = params\n\n this.url = url\n this.accessToken = null\n this.adminSecret = adminSecret\n }\n\n /**\n * Use `nhost.functions.call` to call (sending a POST request to) a serverless function. Use generic\n * types to specify the expected response data, request body and error message.\n *\n * @example\n * ### Without generic types\n * ```ts\n * await nhost.functions.call('send-welcome-email', { email: 'joe@example.com', name: 'Joe Doe' })\n * ```\n *\n * @example\n * ### Using generic types\n * ```ts\n * type Data = {\n * message: string\n * }\n *\n * type Body = {\n * email: string\n * name: string\n * }\n *\n * type ErrorMessage = {\n * details: string\n * }\n *\n * // The function will only accept a body of type `Body`\n * const { res, error } = await nhost.functions.call<Data, Body, ErrorMessage>(\n * 'send-welcome-email',\n * { email: 'joe@example.com', name: 'Joe Doe' }\n * )\n *\n * // Now the response data is typed as `Data`\n * console.log(res?.data.message)\n *\n * // Now the error message is typed as `ErrorMessage`\n * console.log(error?.message.details)\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call\n */\n async call<TData = unknown, TBody = any, TErrorMessage = any>(\n url: string,\n body?: TBody | null,\n config?: NhostFunctionCallConfig\n ): Promise<NhostFunctionCallResponse<TData, TErrorMessage>> {\n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n const fullUrl = buildUrl(this.url, url)\n\n try {\n const result = await fetch(fullUrl, {\n body: body ? JSON.stringify(body) : null,\n headers,\n method: 'POST'\n })\n\n if (!result.ok) {\n let message: TErrorMessage\n\n if (result.headers.get('content-type')?.includes('application/json')) {\n message = await result.json()\n } else {\n message = (await result.text()) as unknown as TErrorMessage\n }\n\n return {\n res: null,\n error: {\n message,\n error: result.statusText,\n status: result.status\n }\n }\n }\n\n let data: TData\n\n if (result.headers.get('content-type')?.includes('application/json')) {\n data = await result.json()\n } else {\n data = (await result.text()) as unknown as TData\n }\n\n return {\n res: { data, status: result.status, statusText: result.statusText },\n error: null\n }\n } catch (e) {\n const error = e as Error\n return {\n res: null,\n error: {\n message: error.message as unknown as TErrorMessage,\n status: error.name === 'AbortError' ? 0 : 500,\n error: error.name === 'AbortError' ? 'abort-error' : 'unknown'\n }\n }\n }\n }\n\n /**\n * Use `nhost.functions.setAccessToken` to a set an access token to be used in subsequent functions requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically.\n *\n * @example\n * ```ts\n * nhost.functions.setAccessToken('some-access-token')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/set-access-token\n */\n setAccessToken(accessToken: string | undefined) {\n if (!accessToken) {\n this.accessToken = null\n return\n }\n\n this.accessToken = accessToken\n }\n\n generateAccessTokenHeaders(): NhostFunctionCallConfig['headers'] {\n if (this.adminSecret) {\n return {\n 'x-hasura-admin-secret': this.adminSecret\n }\n }\n if (this.accessToken) {\n return {\n Authorization: `Bearer ${this.accessToken}`\n }\n }\n return {}\n }\n}\n","import { NhostGraphqlClient } from '@nhost/graphql-js'\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for GraphQL from either a subdomain or a URL\n */\nexport function createGraphqlClient(params: NhostClientConstructorParams) {\n const graphqlUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'graphql')\n : params.graphqlUrl\n\n if (!graphqlUrl) {\n throw new Error('Please provide `subdomain` or `graphqlUrl`.')\n }\n\n return new NhostGraphqlClient({ url: graphqlUrl, ...params })\n}\n","import { HasuraStorageClient } from '@nhost/hasura-storage-js'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for Storage from either a subdomain or a URL\n */\nexport function createStorageClient(params: NhostClientConstructorParams) {\n const storageUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'storage')\n : params.storageUrl\n\n if (!storageUrl) {\n throw new Error('Please provide `subdomain` or `storageUrl`.')\n }\n\n return new HasuraStorageClient({ url: storageUrl, ...params })\n}\n","import { NhostGraphqlClient } from '@nhost/graphql-js'\nimport { HasuraAuthClient } from '@nhost/hasura-auth-js'\nimport { HasuraStorageClient } from '@nhost/hasura-storage-js'\nimport { NhostClientConstructorParams } from '../utils/types'\nimport { createAuthClient } from './auth'\nimport { createFunctionsClient, NhostFunctionsClient } from './functions'\nimport { createGraphqlClient } from './graphql'\nimport { createStorageClient } from './storage'\n\nexport const createNhostClient = (params: NhostClientConstructorParams) => new NhostClient(params)\n\nexport class NhostClient {\n auth: HasuraAuthClient\n storage: HasuraStorageClient\n functions: NhostFunctionsClient\n graphql: NhostGraphqlClient\n private _adminSecret?: string\n readonly devTools?: boolean\n\n /**\n * Nhost Client\n *\n * @example\n * ```ts\n * const nhost = new NhostClient({ subdomain, region });\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript\n */\n constructor({\n refreshIntervalTime,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n adminSecret,\n devTools,\n start = true,\n ...urlParams\n }: NhostClientConstructorParams) {\n // * Set clients for all services\n this.auth = createAuthClient({\n refreshIntervalTime,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n start,\n ...urlParams\n })\n this.storage = createStorageClient({ adminSecret, ...urlParams })\n this.functions = createFunctionsClient({ adminSecret, ...urlParams })\n this.graphql = createGraphqlClient({ adminSecret, ...urlParams })\n\n this.auth.onAuthStateChanged((_event, session) => {\n if (_event === 'SIGNED_OUT') {\n this.storage.setAccessToken(undefined)\n this.functions.setAccessToken(undefined)\n this.graphql.setAccessToken(undefined)\n }\n })\n\n // * Update access token for clients, including when signin in\n this.auth.onTokenChanged((session) => {\n const accessToken = session?.accessToken\n this.storage.setAccessToken(accessToken)\n this.functions.setAccessToken(accessToken)\n this.graphql.setAccessToken(accessToken)\n })\n\n this._adminSecret = adminSecret\n this.devTools = devTools\n }\n\n get adminSecret(): string | undefined {\n return this._adminSecret\n }\n\n set adminSecret(newValue: string | undefined) {\n this._adminSecret = newValue\n this.storage.setAdminSecret(newValue)\n // TODO inconsistent API: storage can change admin secret, but functions/graphql cannot\n // this.functions.setAdminSecret(newValue)\n // this.graphql.setAdminSecret(newValue)\n }\n}\n"],"names":["LOCALHOST_REGEX","urlFromSubdomain","backendOrSubdomain","service","backendUrl","subdomain","region","subdomainLocalhostFound","protocol","host","port","urlFromEnv","getValueFromEnv","isBrowser","environmentIsAvailable","buildUrl","baseUrl","path","urlPath","createAuthClient","params","authUrl","HasuraAuthClient","createFunctionsClient","functionsUrl","NhostFunctionsClient","url","adminSecret","body","config","headers","fullUrl","result","fetch","message","_a","data","_b","e","error","accessToken","createGraphqlClient","graphqlUrl","NhostGraphqlClient","createStorageClient","storageUrl","HasuraStorageClient","createNhostClient","NhostClient","refreshIntervalTime","clientStorage","clientStorageType","autoRefreshToken","autoSignIn","devTools","start","urlParams","_event","session","newValue"],"mappings":"8NAGaA,EACX,sFAUc,SAAAC,EACdC,EACAC,EACQ,CACR,KAAM,CAAE,WAAAC,EAAY,UAAAC,EAAW,OAAAC,CAAA,EAAWJ,EAE1C,GAAIE,EACF,MAAO,GAAGA,QAAiBD,IAG7B,GAAI,CAACE,EACG,MAAA,IAAI,MAAM,iDAAiD,EAI7D,MAAAE,EAA0BF,EAAU,MAAML,CAAe,EAC/D,GAAIO,GAAA,MAAAA,EAAyB,OAAQ,CACnC,KAAM,CAAE,SAAAC,EAAU,KAAAC,EAAM,KAAAC,CAAA,EAASH,EAAwB,OAEnDI,EAAaC,EAAgBT,CAAO,EAC1C,OAAIQ,IAIAF,IAAS,aACH,QAAA,KACN,0HAAA,EAGK,GAAGD,GAAY,sBAAsBE,GAAQ,WAAWP,KAG1DO,EACH,GAAGF,GAAY,mBAAmBL,eAAqBO,OACvD,GAAGF,GAAY,mBAAmBL,iBACxC,CAEA,GAAI,CAACG,EACG,MAAA,IAAI,MAAM,mEAAmE,EAG9E,MAAA,WAAWD,KAAaF,KAAWG,gBAC5C,CAMA,SAASO,GAAqB,CAC5B,OAAO,OAAO,OAAW,GAC3B,CAMA,SAASC,GAAyB,CACzB,OAAA,OAAO,QAAY,KAAe,QAAQ,GACnD,CAQA,SAASF,EAAgBT,EAAiB,CACxC,OAAIU,EAAU,GAAK,CAACC,IACX,KAGF,QAAQ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,CAAA;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAA;AACrC,cAAc,0BAA0B,CAAA;AACxC,cAAc,WAAW,CAAA;AACzB,cAAc,eAAe,CAAA"}
|
package/dist/index.esm.js
CHANGED
|
@@ -2,38 +2,38 @@ import { HasuraAuthClient as f } from "@nhost/hasura-auth-js";
|
|
|
2
2
|
export * from "@nhost/hasura-auth-js";
|
|
3
3
|
import { HasuraStorageClient as g } from "@nhost/hasura-storage-js";
|
|
4
4
|
export * from "@nhost/hasura-storage-js";
|
|
5
|
-
import
|
|
6
|
-
import { NhostGraphqlClient as
|
|
5
|
+
import p from "isomorphic-unfetch";
|
|
6
|
+
import { NhostGraphqlClient as w } from "@nhost/graphql-js";
|
|
7
7
|
const b = /^((?<protocol>http[s]?):\/\/)?(?<host>(localhost|local))(:(?<port>(\d+|__\w+__)))?$/;
|
|
8
8
|
function d(e, t) {
|
|
9
|
-
const { backendUrl: i, subdomain:
|
|
9
|
+
const { backendUrl: i, subdomain: o, region: a } = e;
|
|
10
10
|
if (i)
|
|
11
11
|
return `${i}/v1/${t}`;
|
|
12
|
-
if (!
|
|
12
|
+
if (!o)
|
|
13
13
|
throw new Error("Either `backendUrl` or `subdomain` must be set.");
|
|
14
|
-
const
|
|
15
|
-
if (
|
|
16
|
-
const { protocol: s, host:
|
|
17
|
-
return
|
|
14
|
+
const u = o.match(b);
|
|
15
|
+
if (u != null && u.groups) {
|
|
16
|
+
const { protocol: s, host: c, port: r } = u.groups, n = k(t);
|
|
17
|
+
return n || (c === "localhost" ? (console.warn(
|
|
18
18
|
'The `subdomain` is set to "localhost". Support for this will be removed in a future release. Please use "local" instead.'
|
|
19
|
-
), `${s || "http"}://localhost:${
|
|
19
|
+
), `${s || "http"}://localhost:${r || 1337}/v1/${t}`) : r ? `${s || "https"}://local.${t}.nhost.run:${r}/v1` : `${s || "https"}://local.${t}.nhost.run/v1`);
|
|
20
20
|
}
|
|
21
|
-
if (!
|
|
21
|
+
if (!a)
|
|
22
22
|
throw new Error('`region` must be set when using a `subdomain` other than "local".');
|
|
23
|
-
return `https://${
|
|
23
|
+
return `https://${o}.${t}.${a}.nhost.run/v1`;
|
|
24
24
|
}
|
|
25
25
|
function T() {
|
|
26
26
|
return typeof window < "u";
|
|
27
27
|
}
|
|
28
|
-
function
|
|
28
|
+
function m() {
|
|
29
29
|
return typeof process < "u" && process.env;
|
|
30
30
|
}
|
|
31
|
-
function
|
|
32
|
-
return T() || !
|
|
31
|
+
function k(e) {
|
|
32
|
+
return T() || !m() ? null : process.env[`NHOST_${e.toUpperCase()}_URL`];
|
|
33
33
|
}
|
|
34
34
|
function U(e, t) {
|
|
35
|
-
const
|
|
36
|
-
return e +
|
|
35
|
+
const o = t.startsWith("/") ? t : `/${t}`;
|
|
36
|
+
return e + o;
|
|
37
37
|
}
|
|
38
38
|
function S(e) {
|
|
39
39
|
const t = "subdomain" in e || "backendUrl" in e ? d(e, "auth") : e.authUrl;
|
|
@@ -49,37 +49,46 @@ function A(e) {
|
|
|
49
49
|
}
|
|
50
50
|
class $ {
|
|
51
51
|
constructor(t) {
|
|
52
|
-
const { url: i, adminSecret:
|
|
53
|
-
this.url = i, this.accessToken = null, this.adminSecret =
|
|
52
|
+
const { url: i, adminSecret: o } = t;
|
|
53
|
+
this.url = i, this.accessToken = null, this.adminSecret = o;
|
|
54
54
|
}
|
|
55
|
-
async call(t, i,
|
|
56
|
-
var s;
|
|
57
|
-
const
|
|
55
|
+
async call(t, i, o) {
|
|
56
|
+
var s, c;
|
|
57
|
+
const a = {
|
|
58
58
|
"Content-Type": "application/json",
|
|
59
59
|
...this.generateAccessTokenHeaders(),
|
|
60
|
-
...
|
|
61
|
-
},
|
|
60
|
+
...o == null ? void 0 : o.headers
|
|
61
|
+
}, u = U(this.url, t);
|
|
62
62
|
try {
|
|
63
|
-
const
|
|
63
|
+
const r = await p(u, {
|
|
64
64
|
body: i ? JSON.stringify(i) : null,
|
|
65
|
-
headers:
|
|
65
|
+
headers: a,
|
|
66
66
|
method: "POST"
|
|
67
67
|
});
|
|
68
|
-
if (!
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
68
|
+
if (!r.ok) {
|
|
69
|
+
let l;
|
|
70
|
+
return (s = r.headers.get("content-type")) != null && s.includes("application/json") ? l = await r.json() : l = await r.text(), {
|
|
71
|
+
res: null,
|
|
72
|
+
error: {
|
|
73
|
+
message: l,
|
|
74
|
+
error: r.statusText,
|
|
75
|
+
status: r.status
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
let n;
|
|
80
|
+
return (c = r.headers.get("content-type")) != null && c.includes("application/json") ? n = await r.json() : n = await r.text(), {
|
|
81
|
+
res: { data: n, status: r.status, statusText: r.statusText },
|
|
73
82
|
error: null
|
|
74
83
|
};
|
|
75
|
-
} catch (
|
|
76
|
-
const
|
|
84
|
+
} catch (r) {
|
|
85
|
+
const n = r;
|
|
77
86
|
return {
|
|
78
87
|
res: null,
|
|
79
88
|
error: {
|
|
80
|
-
message:
|
|
81
|
-
status:
|
|
82
|
-
error:
|
|
89
|
+
message: n.message,
|
|
90
|
+
status: n.name === "AbortError" ? 0 : 500,
|
|
91
|
+
error: n.name === "AbortError" ? "abort-error" : "unknown"
|
|
83
92
|
}
|
|
84
93
|
};
|
|
85
94
|
}
|
|
@@ -103,7 +112,7 @@ function v(e) {
|
|
|
103
112
|
const t = "subdomain" in e || "backendUrl" in e ? d(e, "graphql") : e.graphqlUrl;
|
|
104
113
|
if (!t)
|
|
105
114
|
throw new Error("Please provide `subdomain` or `graphqlUrl`.");
|
|
106
|
-
return new
|
|
115
|
+
return new w({ url: t, ...e });
|
|
107
116
|
}
|
|
108
117
|
function C(e) {
|
|
109
118
|
const t = "subdomain" in e || "backendUrl" in e ? d(e, "storage") : e.storageUrl;
|
|
@@ -116,28 +125,28 @@ class E {
|
|
|
116
125
|
constructor({
|
|
117
126
|
refreshIntervalTime: t,
|
|
118
127
|
clientStorage: i,
|
|
119
|
-
clientStorageType:
|
|
120
|
-
autoRefreshToken:
|
|
121
|
-
autoSignIn:
|
|
128
|
+
clientStorageType: o,
|
|
129
|
+
autoRefreshToken: a,
|
|
130
|
+
autoSignIn: u,
|
|
122
131
|
adminSecret: s,
|
|
123
|
-
devTools:
|
|
124
|
-
start:
|
|
125
|
-
...
|
|
132
|
+
devTools: c,
|
|
133
|
+
start: r = !0,
|
|
134
|
+
...n
|
|
126
135
|
}) {
|
|
127
136
|
this.auth = S({
|
|
128
137
|
refreshIntervalTime: t,
|
|
129
138
|
clientStorage: i,
|
|
130
|
-
clientStorageType:
|
|
131
|
-
autoRefreshToken:
|
|
132
|
-
autoSignIn:
|
|
133
|
-
start:
|
|
134
|
-
...
|
|
135
|
-
}), this.storage = C({ adminSecret: s, ...
|
|
136
|
-
|
|
137
|
-
}), this.auth.onTokenChanged((
|
|
138
|
-
const h =
|
|
139
|
+
clientStorageType: o,
|
|
140
|
+
autoRefreshToken: a,
|
|
141
|
+
autoSignIn: u,
|
|
142
|
+
start: r,
|
|
143
|
+
...n
|
|
144
|
+
}), this.storage = C({ adminSecret: s, ...n }), this.functions = A({ adminSecret: s, ...n }), this.graphql = v({ adminSecret: s, ...n }), this.auth.onAuthStateChanged((l, h) => {
|
|
145
|
+
l === "SIGNED_OUT" && (this.storage.setAccessToken(void 0), this.functions.setAccessToken(void 0), this.graphql.setAccessToken(void 0));
|
|
146
|
+
}), this.auth.onTokenChanged((l) => {
|
|
147
|
+
const h = l == null ? void 0 : l.accessToken;
|
|
139
148
|
this.storage.setAccessToken(h), this.functions.setAccessToken(h), this.graphql.setAccessToken(h);
|
|
140
|
-
}), this._adminSecret = s, this.devTools =
|
|
149
|
+
}), this._adminSecret = s, this.devTools = c;
|
|
141
150
|
}
|
|
142
151
|
get adminSecret() {
|
|
143
152
|
return this._adminSecret;
|
package/dist/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.js","sources":["../src/utils/helpers.ts","../src/clients/auth.ts","../src/clients/functions/index.ts","../src/clients/graphql.ts","../src/clients/storage.ts","../src/clients/nhost.ts"],"sourcesContent":["import { NhostClientConstructorParams } from './types'\n\n// a port can be a number or a placeholder string with leading and trailing double underscores, f.e. \"8080\" or \"__PLACEHOLDER_NAME__\"\nexport const LOCALHOST_REGEX =\n /^((?<protocol>http[s]?):\\/\\/)?(?<host>(localhost|local))(:(?<port>(\\d+|__\\w+__)))?$/\n\n/**\n * `backendUrl` should now be used only when self-hosting\n * `subdomain` and `region` should be used instead when using the Nhost platform\n * `\n * @param backendOrSubdomain\n * @param service\n * @returns\n */\nexport function urlFromSubdomain(\n backendOrSubdomain: Pick<NhostClientConstructorParams, 'region' | 'subdomain' | 'backendUrl'>,\n service: string\n): string {\n const { backendUrl, subdomain, region } = backendOrSubdomain\n\n if (backendUrl) {\n return `${backendUrl}/v1/${service}`\n }\n\n if (!subdomain) {\n throw new Error('Either `backendUrl` or `subdomain` must be set.')\n }\n\n // check if subdomain is [http[s]://]localhost[:port] or [http[s]://]local[:port]\n const subdomainLocalhostFound = subdomain.match(LOCALHOST_REGEX)\n if (subdomainLocalhostFound?.groups) {\n const { protocol, host, port } = subdomainLocalhostFound.groups\n\n const urlFromEnv = getValueFromEnv(service)\n if (urlFromEnv) {\n return urlFromEnv\n }\n\n if (host === 'localhost') {\n console.warn(\n 'The `subdomain` is set to \"localhost\". Support for this will be removed in a future release. Please use \"local\" instead.'\n )\n\n return `${protocol || 'http'}://localhost:${port || 1337}/v1/${service}`\n }\n\n return port\n ? `${protocol || 'https'}://local.${service}.nhost.run:${port}/v1`\n : `${protocol || 'https'}://local.${service}.nhost.run/v1`\n }\n\n if (!region) {\n throw new Error('`region` must be set when using a `subdomain` other than \"local\".')\n }\n\n return `https://${subdomain}.${service}.${region}.nhost.run/v1`\n}\n\n/**\n *\n * @returns whether the code is running in a browser\n */\nfunction isBrowser(): boolean {\n return typeof window !== 'undefined'\n}\n\n/**\n *\n * @returns whether the code is running in a Node.js environment\n */\nfunction environmentIsAvailable() {\n return typeof process !== 'undefined' && process.env\n}\n\n/**\n *\n * @param service auth | storage | graphql | functions\n * @returns the service's url if the corresponding env var is set\n * NHOST_${service}_URL\n */\nfunction getValueFromEnv(service: string) {\n if (isBrowser() || !environmentIsAvailable()) {\n return null\n }\n\n return process.env[`NHOST_${service.toUpperCase()}_URL`]\n}\n\n/**\n * Combines a base URL and a path into a single URL string.\n *\n * @param baseUrl - The base URL to use.\n * @param path - The path to append to the base URL.\n * @returns The combined URL string.\n */\nexport function buildUrl(baseUrl: string, path: string) {\n const hasLeadingSlash = path.startsWith('/')\n const urlPath = hasLeadingSlash ? path : `/${path}`\n return baseUrl + urlPath\n}\n","import { HasuraAuthClient } from '@nhost/hasura-auth-js'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for Auth from either a subdomain or a URL\n */\nexport function createAuthClient(params: NhostClientConstructorParams) {\n const authUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'auth')\n : params.authUrl\n\n if (!authUrl) {\n throw new Error('Please provide `subdomain` or `authUrl`.')\n }\n\n return new HasuraAuthClient({ url: authUrl, ...params })\n}\n","import fetch from 'isomorphic-unfetch'\nimport { buildUrl, urlFromSubdomain } from '../../utils/helpers'\nimport { NhostClientConstructorParams } from '../../utils/types'\nimport {\n NhostFunctionCallConfig,\n NhostFunctionCallResponse,\n NhostFunctionsConstructorParams\n} from './types'\n/**\n * Creates a client for Functions from either a subdomain or a URL\n */\nexport function createFunctionsClient(params: NhostClientConstructorParams) {\n const functionsUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'functions')\n : params.functionsUrl\n\n if (!functionsUrl) {\n throw new Error('Please provide `subdomain` or `functionsUrl`.')\n }\n\n return new NhostFunctionsClient({ url: functionsUrl, ...params })\n}\n\n/**\n * @alias Functions\n */\nexport class NhostFunctionsClient {\n readonly url: string\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostFunctionsConstructorParams) {\n const { url, adminSecret } = params\n\n this.url = url\n this.accessToken = null\n this.adminSecret = adminSecret\n }\n\n /**\n * Use `nhost.functions.call` to call (sending a POST request to) a serverless function.\n *\n * @example\n * ```ts\n * await nhost.functions.call('send-welcome-email', { email: 'joe@example.com', name: 'Joe Doe' })\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call\n */\n async call<T = unknown, D = any>(\n url: string,\n body: D | null,\n config?: NhostFunctionCallConfig\n ): Promise<NhostFunctionCallResponse<T>> {\n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n const fullUrl = buildUrl(this.url, url)\n\n try {\n const result = await fetch(fullUrl, {\n body: body ? JSON.stringify(body) : null,\n headers,\n method: 'POST'\n })\n\n if (!result.ok) {\n throw new Error(result.statusText)\n }\n\n let data: T\n\n if (result.headers.get('content-type')?.includes('application/json')) {\n data = await result.json()\n } else {\n data = (await result.text()) as unknown as T\n }\n\n return {\n res: { data, status: result.status, statusText: result.statusText },\n error: null\n }\n } catch (e) {\n const error = e as Error\n return {\n res: null,\n error: {\n message: error.message,\n status: error.name === 'AbortError' ? 0 : 500,\n error: error.name === 'AbortError' ? 'abort-error' : 'unknown'\n }\n }\n }\n }\n\n /**\n * Use `nhost.functions.setAccessToken` to a set an access token to be used in subsequent functions requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically.\n *\n * @example\n * ```ts\n * nhost.functions.setAccessToken('some-access-token')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/set-access-token\n */\n setAccessToken(accessToken: string | undefined) {\n if (!accessToken) {\n this.accessToken = null\n return\n }\n\n this.accessToken = accessToken\n }\n\n generateAccessTokenHeaders(): NhostFunctionCallConfig['headers'] {\n if (this.adminSecret) {\n return {\n 'x-hasura-admin-secret': this.adminSecret\n }\n }\n if (this.accessToken) {\n return {\n Authorization: `Bearer ${this.accessToken}`\n }\n }\n return {}\n }\n}\n","import { NhostGraphqlClient } from '@nhost/graphql-js'\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for GraphQL from either a subdomain or a URL\n */\nexport function createGraphqlClient(params: NhostClientConstructorParams) {\n const graphqlUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'graphql')\n : params.graphqlUrl\n\n if (!graphqlUrl) {\n throw new Error('Please provide `subdomain` or `graphqlUrl`.')\n }\n\n return new NhostGraphqlClient({ url: graphqlUrl, ...params })\n}\n","import { HasuraStorageClient } from '@nhost/hasura-storage-js'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for Storage from either a subdomain or a URL\n */\nexport function createStorageClient(params: NhostClientConstructorParams) {\n const storageUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'storage')\n : params.storageUrl\n\n if (!storageUrl) {\n throw new Error('Please provide `subdomain` or `storageUrl`.')\n }\n\n return new HasuraStorageClient({ url: storageUrl, ...params })\n}\n","import { NhostGraphqlClient } from '@nhost/graphql-js'\nimport { HasuraAuthClient } from '@nhost/hasura-auth-js'\nimport { HasuraStorageClient } from '@nhost/hasura-storage-js'\nimport { NhostClientConstructorParams } from '../utils/types'\nimport { createAuthClient } from './auth'\nimport { createFunctionsClient, NhostFunctionsClient } from './functions'\nimport { createGraphqlClient } from './graphql'\nimport { createStorageClient } from './storage'\n\nexport const createNhostClient = (params: NhostClientConstructorParams) => new NhostClient(params)\n\nexport class NhostClient {\n auth: HasuraAuthClient\n storage: HasuraStorageClient\n functions: NhostFunctionsClient\n graphql: NhostGraphqlClient\n private _adminSecret?: string\n readonly devTools?: boolean\n\n /**\n * Nhost Client\n *\n * @example\n * ```ts\n * const nhost = new NhostClient({ subdomain, region });\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript\n */\n constructor({\n refreshIntervalTime,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n adminSecret,\n devTools,\n start = true,\n ...urlParams\n }: NhostClientConstructorParams) {\n // * Set clients for all services\n this.auth = createAuthClient({\n refreshIntervalTime,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n start,\n ...urlParams\n })\n this.storage = createStorageClient({ adminSecret, ...urlParams })\n this.functions = createFunctionsClient({ adminSecret, ...urlParams })\n this.graphql = createGraphqlClient({ adminSecret, ...urlParams })\n\n this.auth.onAuthStateChanged((_event, session) => {\n if (_event === 'SIGNED_OUT') {\n this.storage.setAccessToken(undefined)\n this.functions.setAccessToken(undefined)\n this.graphql.setAccessToken(undefined)\n }\n })\n\n // * Update access token for clients, including when signin in\n this.auth.onTokenChanged((session) => {\n const accessToken = session?.accessToken\n this.storage.setAccessToken(accessToken)\n this.functions.setAccessToken(accessToken)\n this.graphql.setAccessToken(accessToken)\n })\n\n this._adminSecret = adminSecret\n this.devTools = devTools\n }\n\n get adminSecret(): string | undefined {\n return this._adminSecret\n }\n\n set adminSecret(newValue: string | undefined) {\n this._adminSecret = newValue\n this.storage.setAdminSecret(newValue)\n // TODO inconsistent API: storage can change admin secret, but functions/graphql cannot\n // this.functions.setAdminSecret(newValue)\n // this.graphql.setAdminSecret(newValue)\n }\n}\n"],"names":["LOCALHOST_REGEX","urlFromSubdomain","backendOrSubdomain","service","backendUrl","subdomain","region","subdomainLocalhostFound","protocol","host","port","urlFromEnv","getValueFromEnv","isBrowser","environmentIsAvailable","buildUrl","baseUrl","path","urlPath","createAuthClient","params","authUrl","HasuraAuthClient","createFunctionsClient","functionsUrl","NhostFunctionsClient","url","adminSecret","body","config","headers","fullUrl","result","fetch","data","_a","e","error","accessToken","createGraphqlClient","graphqlUrl","NhostGraphqlClient","createStorageClient","storageUrl","HasuraStorageClient","createNhostClient","NhostClient","refreshIntervalTime","clientStorage","clientStorageType","autoRefreshToken","autoSignIn","devTools","start","urlParams","_event","session","newValue"],"mappings":";;;;;;AAGO,MAAMA,IACX;AAUc,SAAAC,EACdC,GACAC,GACQ;AACR,QAAM,EAAE,YAAAC,GAAY,WAAAC,GAAW,QAAAC,EAAA,IAAWJ;AAE1C,MAAIE;AACF,WAAO,GAAGA,QAAiBD;AAG7B,MAAI,CAACE;AACG,UAAA,IAAI,MAAM,iDAAiD;AAI7D,QAAAE,IAA0BF,EAAU,MAAML,CAAe;AAC/D,MAAIO,KAAA,QAAAA,EAAyB,QAAQ;AACnC,UAAM,EAAE,UAAAC,GAAU,MAAAC,GAAM,MAAAC,EAAA,IAASH,EAAwB,QAEnDI,IAAaC,EAAgBT,CAAO;AAC1C,WAAIQ,MAIAF,MAAS,eACH,QAAA;AAAA,MACN;AAAA,IAAA,GAGK,GAAGD,KAAY,sBAAsBE,KAAQ,WAAWP,OAG1DO,IACH,GAAGF,KAAY,mBAAmBL,eAAqBO,SACvD,GAAGF,KAAY,mBAAmBL;AAAA,EACxC;AAEA,MAAI,CAACG;AACG,UAAA,IAAI,MAAM,mEAAmE;AAG9E,SAAA,WAAWD,KAAaF,KAAWG;AAC5C;AAMA,SAASO,IAAqB;AAC5B,SAAO,OAAO,SAAW;AAC3B;AAMA,SAASC,IAAyB;AACzB,SAAA,OAAO,UAAY,OAAe,QAAQ;AACnD;AAQA,SAASF,EAAgBT,GAAiB;AACxC,SAAIU,EAAU,KAAK,CAACC,MACX,OAGF,QAAQ,IAAI,SAASX,EAAQ,YAAY;AAClD;AASgB,SAAAY,EAASC,GAAiBC,GAAc;AAEhD,QAAAC,IADkBD,EAAK,WAAW,GAAG,IACTA,IAAO,IAAIA;AAC7C,SAAOD,IAAUE;AACnB;AC3FO,SAASC,EAAiBC,GAAsC;AAC/D,QAAAC,IACJ,eAAeD,KAAU,gBAAgBA,IACrCnB,EAAiBmB,GAAQ,MA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IAAQ;AAAA,OACLC;AAAA,EAAA,GAC4B;AAE/B,SAAK,OAAOnC,EAAiB;AAAA,MAC3B,qBAAA4B;AAAA,MACA,eAAAC;AAAA,MACA,mBAAAC;AAAA,MACA,kBAAAC;AAAA,MACA,YAAAC;AAAA,MACA,OAAAE;AAAA,MACA,GAAGC;AAAA,IAAA,CACJ,GACD,KAAK,UAAUZ,EAAoB,EAAE,aAAAf,GAAa,GAAG2B,GAAW,GAChE,KAAK,YAAY/B,EAAsB,EAAE,aAAAI,GAAa,GAAG2B,GAAW,GACpE,KAAK,UAAUf,EAAoB,EAAE,aAAAZ,GAAa,GAAG2B,GAAW,GAEhE,KAAK,KAAK,mBAAmB,CAACC,GAAQC,MAAY;AAChD,MAAID,MAAW,iBACR,KAAA,QAAQ,eAAe,MAAS,GAChC,KAAA,UAAU,eAAe,MAAS,GAClC,KAAA,QAAQ,eAAe,MAAS;AAAA,IACvC,CACD,GAGI,KAAA,KAAK,eAAe,CAACC,MAAY;AACpC,YAAMlB,IAAckB,KAAA,gBAAAA,EAAS;AACxB,WAAA,QAAQ,eAAelB,CAAW,GAClC,KAAA,UAAU,eAAeA,CAAW,GACpC,KAAA,QAAQ,eAAeA,CAAW;AAAA,IAAA,CACxC,GAED,KAAK,eAAeX,GACpB,KAAK,WAAWyB;AAAA,EAClB;AAAA,EAEA,IAAI,cAAkC;AACpC,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,YAAYK,GAA8B;AAC5C,SAAK,eAAeA,GACf,KAAA,QAAQ,eAAeA,CAAQ;AAAA,EAItC;AACF;"}
|
|
1
|
+
{"version":3,"file":"index.esm.js","sources":["../src/utils/helpers.ts","../src/clients/auth.ts","../src/clients/functions/index.ts","../src/clients/graphql.ts","../src/clients/storage.ts","../src/clients/nhost.ts"],"sourcesContent":["import { NhostClientConstructorParams } from './types'\n\n// a port can be a number or a placeholder string with leading and trailing double underscores, f.e. \"8080\" or \"__PLACEHOLDER_NAME__\"\nexport const LOCALHOST_REGEX =\n /^((?<protocol>http[s]?):\\/\\/)?(?<host>(localhost|local))(:(?<port>(\\d+|__\\w+__)))?$/\n\n/**\n * `backendUrl` should now be used only when self-hosting\n * `subdomain` and `region` should be used instead when using the Nhost platform\n * `\n * @param backendOrSubdomain\n * @param service\n * @returns\n */\nexport function urlFromSubdomain(\n backendOrSubdomain: Pick<NhostClientConstructorParams, 'region' | 'subdomain' | 'backendUrl'>,\n service: string\n): string {\n const { backendUrl, subdomain, region } = backendOrSubdomain\n\n if (backendUrl) {\n return `${backendUrl}/v1/${service}`\n }\n\n if (!subdomain) {\n throw new Error('Either `backendUrl` or `subdomain` must be set.')\n }\n\n // check if subdomain is [http[s]://]localhost[:port] or [http[s]://]local[:port]\n const subdomainLocalhostFound = subdomain.match(LOCALHOST_REGEX)\n if (subdomainLocalhostFound?.groups) {\n const { protocol, host, port } = subdomainLocalhostFound.groups\n\n const urlFromEnv = getValueFromEnv(service)\n if (urlFromEnv) {\n return urlFromEnv\n }\n\n if (host === 'localhost') {\n console.warn(\n 'The `subdomain` is set to \"localhost\". Support for this will be removed in a future release. Please use \"local\" instead.'\n )\n\n return `${protocol || 'http'}://localhost:${port || 1337}/v1/${service}`\n }\n\n return port\n ? `${protocol || 'https'}://local.${service}.nhost.run:${port}/v1`\n : `${protocol || 'https'}://local.${service}.nhost.run/v1`\n }\n\n if (!region) {\n throw new Error('`region` must be set when using a `subdomain` other than \"local\".')\n }\n\n return `https://${subdomain}.${service}.${region}.nhost.run/v1`\n}\n\n/**\n *\n * @returns whether the code is running in a browser\n */\nfunction isBrowser(): boolean {\n return typeof window !== 'undefined'\n}\n\n/**\n *\n * @returns whether the code is running in a Node.js environment\n */\nfunction environmentIsAvailable() {\n return typeof process !== 'undefined' && process.env\n}\n\n/**\n *\n * @param service auth | storage | graphql | functions\n * @returns the service's url if the corresponding env var is set\n * NHOST_${service}_URL\n */\nfunction getValueFromEnv(service: string) {\n if (isBrowser() || !environmentIsAvailable()) {\n return null\n }\n\n return process.env[`NHOST_${service.toUpperCase()}_URL`]\n}\n\n/**\n * Combines a base URL and a path into a single URL string.\n *\n * @param baseUrl - The base URL to use.\n * @param path - The path to append to the base URL.\n * @returns The combined URL string.\n */\nexport function buildUrl(baseUrl: string, path: string) {\n const hasLeadingSlash = path.startsWith('/')\n const urlPath = hasLeadingSlash ? path : `/${path}`\n return baseUrl + urlPath\n}\n","import { HasuraAuthClient } from '@nhost/hasura-auth-js'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for Auth from either a subdomain or a URL\n */\nexport function createAuthClient(params: NhostClientConstructorParams) {\n const authUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'auth')\n : params.authUrl\n\n if (!authUrl) {\n throw new Error('Please provide `subdomain` or `authUrl`.')\n }\n\n return new HasuraAuthClient({ url: authUrl, ...params })\n}\n","import fetch from 'isomorphic-unfetch'\nimport { buildUrl, urlFromSubdomain } from '../../utils/helpers'\nimport { NhostClientConstructorParams } from '../../utils/types'\nimport {\n NhostFunctionCallConfig,\n NhostFunctionCallResponse,\n NhostFunctionsConstructorParams\n} from './types'\n/**\n * Creates a client for Functions from either a subdomain or a URL\n */\nexport function createFunctionsClient(params: NhostClientConstructorParams) {\n const functionsUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'functions')\n : params.functionsUrl\n\n if (!functionsUrl) {\n throw new Error('Please provide `subdomain` or `functionsUrl`.')\n }\n\n return new NhostFunctionsClient({ url: functionsUrl, ...params })\n}\n\n/**\n * @alias Functions\n */\nexport class NhostFunctionsClient {\n readonly url: string\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostFunctionsConstructorParams) {\n const { url, adminSecret } = params\n\n this.url = url\n this.accessToken = null\n this.adminSecret = adminSecret\n }\n\n /**\n * Use `nhost.functions.call` to call (sending a POST request to) a serverless function. Use generic\n * types to specify the expected response data, request body and error message.\n *\n * @example\n * ### Without generic types\n * ```ts\n * await nhost.functions.call('send-welcome-email', { email: 'joe@example.com', name: 'Joe Doe' })\n * ```\n *\n * @example\n * ### Using generic types\n * ```ts\n * type Data = {\n * message: string\n * }\n *\n * type Body = {\n * email: string\n * name: string\n * }\n *\n * type ErrorMessage = {\n * details: string\n * }\n *\n * // The function will only accept a body of type `Body`\n * const { res, error } = await nhost.functions.call<Data, Body, ErrorMessage>(\n * 'send-welcome-email',\n * { email: 'joe@example.com', name: 'Joe Doe' }\n * )\n *\n * // Now the response data is typed as `Data`\n * console.log(res?.data.message)\n *\n * // Now the error message is typed as `ErrorMessage`\n * console.log(error?.message.details)\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call\n */\n async call<TData = unknown, TBody = any, TErrorMessage = any>(\n url: string,\n body?: TBody | null,\n config?: NhostFunctionCallConfig\n ): Promise<NhostFunctionCallResponse<TData, TErrorMessage>> {\n const headers: HeadersInit = {\n 'Content-Type': 'application/json',\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n const fullUrl = buildUrl(this.url, url)\n\n try {\n const result = await fetch(fullUrl, {\n body: body ? JSON.stringify(body) : null,\n headers,\n method: 'POST'\n })\n\n if (!result.ok) {\n let message: TErrorMessage\n\n if (result.headers.get('content-type')?.includes('application/json')) {\n message = await result.json()\n } else {\n message = (await result.text()) as unknown as TErrorMessage\n }\n\n return {\n res: null,\n error: {\n message,\n error: result.statusText,\n status: result.status\n }\n }\n }\n\n let data: TData\n\n if (result.headers.get('content-type')?.includes('application/json')) {\n data = await result.json()\n } else {\n data = (await result.text()) as unknown as TData\n }\n\n return {\n res: { data, status: result.status, statusText: result.statusText },\n error: null\n }\n } catch (e) {\n const error = e as Error\n return {\n res: null,\n error: {\n message: error.message as unknown as TErrorMessage,\n status: error.name === 'AbortError' ? 0 : 500,\n error: error.name === 'AbortError' ? 'abort-error' : 'unknown'\n }\n }\n }\n }\n\n /**\n * Use `nhost.functions.setAccessToken` to a set an access token to be used in subsequent functions requests. Note that if you're signin in users with `nhost.auth.signIn()` the access token will be set automatically.\n *\n * @example\n * ```ts\n * nhost.functions.setAccessToken('some-access-token')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/set-access-token\n */\n setAccessToken(accessToken: string | undefined) {\n if (!accessToken) {\n this.accessToken = null\n return\n }\n\n this.accessToken = accessToken\n }\n\n generateAccessTokenHeaders(): NhostFunctionCallConfig['headers'] {\n if (this.adminSecret) {\n return {\n 'x-hasura-admin-secret': this.adminSecret\n }\n }\n if (this.accessToken) {\n return {\n Authorization: `Bearer ${this.accessToken}`\n }\n }\n return {}\n }\n}\n","import { NhostGraphqlClient } from '@nhost/graphql-js'\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for GraphQL from either a subdomain or a URL\n */\nexport function createGraphqlClient(params: NhostClientConstructorParams) {\n const graphqlUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'graphql')\n : params.graphqlUrl\n\n if (!graphqlUrl) {\n throw new Error('Please provide `subdomain` or `graphqlUrl`.')\n }\n\n return new NhostGraphqlClient({ url: graphqlUrl, ...params })\n}\n","import { HasuraStorageClient } from '@nhost/hasura-storage-js'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { NhostClientConstructorParams } from '../utils/types'\n\n/**\n * Creates a client for Storage from either a subdomain or a URL\n */\nexport function createStorageClient(params: NhostClientConstructorParams) {\n const storageUrl =\n 'subdomain' in params || 'backendUrl' in params\n ? urlFromSubdomain(params, 'storage')\n : params.storageUrl\n\n if (!storageUrl) {\n throw new Error('Please provide `subdomain` or `storageUrl`.')\n }\n\n return new HasuraStorageClient({ url: storageUrl, ...params })\n}\n","import { NhostGraphqlClient } from '@nhost/graphql-js'\nimport { HasuraAuthClient } from '@nhost/hasura-auth-js'\nimport { HasuraStorageClient } from '@nhost/hasura-storage-js'\nimport { NhostClientConstructorParams } from '../utils/types'\nimport { createAuthClient } from './auth'\nimport { createFunctionsClient, NhostFunctionsClient } from './functions'\nimport { createGraphqlClient } from './graphql'\nimport { createStorageClient } from './storage'\n\nexport const createNhostClient = (params: NhostClientConstructorParams) => new NhostClient(params)\n\nexport class NhostClient {\n auth: HasuraAuthClient\n storage: HasuraStorageClient\n functions: NhostFunctionsClient\n graphql: NhostGraphqlClient\n private _adminSecret?: string\n readonly devTools?: boolean\n\n /**\n * Nhost Client\n *\n * @example\n * ```ts\n * const nhost = new NhostClient({ subdomain, region });\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript\n */\n constructor({\n refreshIntervalTime,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n adminSecret,\n devTools,\n start = true,\n ...urlParams\n }: NhostClientConstructorParams) {\n // * Set clients for all services\n this.auth = createAuthClient({\n refreshIntervalTime,\n clientStorage,\n clientStorageType,\n autoRefreshToken,\n autoSignIn,\n start,\n ...urlParams\n })\n this.storage = createStorageClient({ adminSecret, ...urlParams })\n this.functions = createFunctionsClient({ adminSecret, ...urlParams })\n this.graphql = createGraphqlClient({ adminSecret, ...urlParams })\n\n this.auth.onAuthStateChanged((_event, session) => {\n if (_event === 'SIGNED_OUT') {\n this.storage.setAccessToken(undefined)\n this.functions.setAccessToken(undefined)\n this.graphql.setAccessToken(undefined)\n }\n })\n\n // * Update access token for clients, including when signin in\n this.auth.onTokenChanged((session) => {\n const accessToken = session?.accessToken\n this.storage.setAccessToken(accessToken)\n this.functions.setAccessToken(accessToken)\n this.graphql.setAccessToken(accessToken)\n })\n\n this._adminSecret = adminSecret\n this.devTools = devTools\n }\n\n get adminSecret(): string | undefined {\n return this._adminSecret\n }\n\n set adminSecret(newValue: string | undefined) {\n this._adminSecret = newValue\n this.storage.setAdminSecret(newValue)\n // TODO inconsistent API: storage can change admin secret, but functions/graphql cannot\n // this.functions.setAdminSecret(newValue)\n // this.graphql.setAdminSecret(newValue)\n }\n}\n"],"names":["LOCALHOST_REGEX","urlFromSubdomain","backendOrSubdomain","service","backendUrl","subdomain","region","subdomainLocalhostFound","protocol","host","port","urlFromEnv","getValueFromEnv","isBrowser","environmentIsAvailable","buildUrl","baseUrl","path","urlPath","createAuthClient","params","authUrl","HasuraAuthClient","createFunctionsClient","functionsUrl","NhostFunctionsClient","url","adminSecret","body","config","headers","fullUrl","result","fetch","message","_a","data","_b","e","error","accessToken","createGraphqlClient","graphqlUrl","NhostGraphqlClient","createStorageClient","storageUrl","HasuraStorageClient","createNhostClient","NhostClient","refreshIntervalTime","clientStorage","clientStorageType","autoRefreshToken","autoSignIn","devTools","start","urlParams","_event","session","newValue"],"mappings":";;;;;;AAGO,MAAMA,IACX;AAUc,SAAAC,EACdC,GACAC,GACQ;AACR,QAAM,EAAE,YAAAC,GAAY,WAAAC,GAAW,QAAAC,EAAA,IAAWJ;AAE1C,MAAIE;AACF,WAAO,GAAGA,QAAiBD;AAG7B,MAAI,CAACE;AACG,UAAA,IAAI,MAAM,iDAAiD;AAI7D,QAAAE,IAA0BF,EAAU,MAAML,CAAe;AAC/D,MAAIO,KAAA,QAAAA,EAAyB,QAAQ;AACnC,UAAM,EAAE,UAAAC,GAAU,MAAAC,GAAM,MAAAC,EAAA,IAASH,EAAwB,QAEnDI,IAAaC,EAAgBT,CAAO;AAC1C,WAAIQ,MAIAF,MAAS,eACH,QAAA;AAAA,MACN;AAAA,IAAA,GAGK,GAAGD,KAAY,sBAAsBE,KAAQ,WAAWP,OAG1DO,IACH,GAAGF,KAAY,mBAAmBL,eAAqBO,SACvD,GAAGF,KAAY,mBAAmBL;AAAA,EACxC;AAEA,MAAI,CAACG;AACG,UAAA,IAAI,MAAM,mEAAmE;AAG9E,SAAA,WAAWD,KAAaF,KAAWG;AAC5C;AAMA,SAASO,IAAqB;AAC5B,SAAO,OAAO,SAAW;AAC3B;AAMA,SAASC,IAAyB;AACzB,SAAA,OAAO,UAAY,OAAe,QAAQ;AACnD;AAQA,SAASF,EAAgBT,GAAiB;AACxC,SAAI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,CAAW,GAClC,KAAA,UAAU,eAAeA,CAAW,GACpC,KAAA,QAAQ,eAAeA,CAAW;AAAA,IAAA,CACxC,GAED,KAAK,eAAeb,GACpB,KAAK,WAAW2B;AAAA,EAClB;AAAA,EAEA,IAAI,cAAkC;AACpC,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,YAAYK,GAA8B;AAC5C,SAAK,eAAeA,GACf,KAAA,QAAQ,eAAeA,CAAQ;AAAA,EAItC;AACF;"}
|
package/dist/utils/types.d.ts
CHANGED
|
@@ -1,9 +1,28 @@
|
|
|
1
1
|
import { NhostAuthConstructorParams } from '@nhost/hasura-auth-js';
|
|
2
|
-
export
|
|
2
|
+
export interface ErrorPayload<TMessage = any> {
|
|
3
3
|
error: string;
|
|
4
4
|
status: number;
|
|
5
|
-
message:
|
|
6
|
-
}
|
|
5
|
+
message: TMessage;
|
|
6
|
+
}
|
|
7
|
+
export interface ActionErrorState {
|
|
8
|
+
/**
|
|
9
|
+
* @return `true` if an error occurred
|
|
10
|
+
* @depreacted use `!isSuccess` or `!!error` instead
|
|
11
|
+
* */
|
|
12
|
+
isError: boolean;
|
|
13
|
+
/** Provides details about the error */
|
|
14
|
+
error: ErrorPayload | null;
|
|
15
|
+
}
|
|
16
|
+
export interface ActionLoadingState {
|
|
17
|
+
/**
|
|
18
|
+
* @return `true` when the action is executing, `false` when it finished its execution.
|
|
19
|
+
*/
|
|
20
|
+
isLoading: boolean;
|
|
21
|
+
}
|
|
22
|
+
export interface ActionSuccessState {
|
|
23
|
+
/** Returns `true` if the action is successful. */
|
|
24
|
+
isSuccess: boolean;
|
|
25
|
+
}
|
|
7
26
|
export type BackendUrl = {
|
|
8
27
|
/**
|
|
9
28
|
* Nhost backend URL
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/utils/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAA;
|
|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zC;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nhost/nhost-js",
|
|
3
|
-
"version": "2.1
|
|
3
|
+
"version": "2.2.1",
|
|
4
4
|
"description": "Nhost JavaScript SDK",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"keywords": [
|
|
@@ -45,19 +45,20 @@
|
|
|
45
45
|
"dependencies": {
|
|
46
46
|
"isomorphic-unfetch": "^3.1.0",
|
|
47
47
|
"@nhost/graphql-js": "0.1.0",
|
|
48
|
-
"@nhost/hasura-auth-js": "2.0
|
|
49
|
-
"@nhost/hasura-storage-js": "2.0
|
|
48
|
+
"@nhost/hasura-auth-js": "2.1.0",
|
|
49
|
+
"@nhost/hasura-storage-js": "2.1.0"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"graphql": "16.6.0",
|
|
53
|
-
"@nhost/docgen": "0.1.
|
|
53
|
+
"@nhost/docgen": "0.1.9"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
56
|
"graphql": "^14.0.0 || ^15.0.0 || ^16.0.0"
|
|
57
57
|
},
|
|
58
58
|
"scripts": {
|
|
59
59
|
"dev": "vite build --config ../../config/vite.lib.dev.config.js",
|
|
60
|
-
"build": "run-p build:lib build:umd",
|
|
60
|
+
"build": "run-p typecheck build:lib build:umd",
|
|
61
|
+
"typecheck": "tsc --noEmit",
|
|
61
62
|
"build:lib": "vite build",
|
|
62
63
|
"build:umd": "vite build --config ../../config/vite.lib.umd.config.js",
|
|
63
64
|
"test": "vitest run",
|