@nhost/nhost-js 1.7.0 → 1.12.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.
@@ -1,15 +1,7 @@
1
1
  import { AxiosRequestConfig } from 'axios';
2
- import { FunctionCallResponse, NhostClientConstructorParams } from '../utils/types';
3
- export interface NhostFunctionsConstructorParams {
4
- /**
5
- * Serverless Functions endpoint.
6
- */
7
- url: string;
8
- /**
9
- * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all requests.
10
- */
11
- adminSecret?: string;
12
- }
2
+ import { NhostClientConstructorParams } from '../../utils/types';
3
+ import { DeprecatedNhostFunctionCallResponse, NhostFunctionCallConfig, NhostFunctionCallResponse, NhostFunctionsConstructorParams } from './types';
4
+ export * from './types';
13
5
  /**
14
6
  * Creates a client for Functions from either a subdomain or a URL
15
7
  */
@@ -23,17 +15,13 @@ export declare class NhostFunctionsClient {
23
15
  private accessToken;
24
16
  private adminSecret?;
25
17
  constructor(params: NhostFunctionsConstructorParams);
26
- /**
27
- * Use `nhost.functions.call` to call (sending a POST request to) a serverless function.
28
- *
29
- * @example
30
- * ```ts
31
- * await nhost.functions.call('send-welcome-email', { email: 'joe@example.com', name: 'Joe Doe' })
32
- * ```
33
- *
34
- * @docs https://docs.nhost.io/reference/javascript/nhost-js/functions/call
35
- */
36
- call<T = unknown, D = any>(url: string, data: D, config?: AxiosRequestConfig): Promise<FunctionCallResponse<T>>;
18
+ /** @deprecated Axios will be replaced by cross-fetch in the near future. Only the headers configuration will be kept. */
19
+ call<T = unknown, D = any>(url: string, data?: D, config?: (NhostFunctionCallConfig | AxiosRequestConfig) & {
20
+ useAxios?: true;
21
+ }): Promise<DeprecatedNhostFunctionCallResponse<T>>;
22
+ call<T = unknown, D = any>(url: string, data: D, config?: NhostFunctionCallConfig & {
23
+ useAxios: false;
24
+ }): Promise<NhostFunctionCallResponse<T>>;
37
25
  /**
38
26
  * 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.
39
27
  *
@@ -47,4 +35,4 @@ export declare class NhostFunctionsClient {
47
35
  setAccessToken(accessToken: string | undefined): void;
48
36
  private generateAccessTokenHeaders;
49
37
  }
50
- //# sourceMappingURL=functions.d.ts.map
38
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAc,EAGZ,kBAAkB,EAGnB,MAAM,OAAO,CAAA;AAEd,OAAO,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAA;AAChE,OAAO,EACL,mCAAmC,EACnC,uBAAuB,EACvB,yBAAyB,EACzB,+BAA+B,EAChC,MAAM,SAAS,CAAA;AAEhB,cAAc,SAAS,CAAA;AACvB;;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,QAAQ,CAAe;IAC/B,OAAO,CAAC,WAAW,CAAe;IAClC,OAAO,CAAC,WAAW,CAAC,CAAQ;gBAEhB,MAAM,EAAE,+BAA+B;IAWnD,yHAAyH;IACnH,IAAI,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,GAAG,EAC7B,GAAG,EAAE,MAAM,EACX,IAAI,CAAC,EAAE,CAAC,EACR,MAAM,CAAC,EAAE,CAAC,uBAAuB,GAAG,kBAAkB,CAAC,GAAG;QAAE,QAAQ,CAAC,EAAE,IAAI,CAAA;KAAE,GAC5E,OAAO,CAAC,mCAAmC,CAAC,CAAC,CAAC,CAAC;IAE5C,IAAI,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,GAAG,EAC7B,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,CAAC,EACP,MAAM,CAAC,EAAE,uBAAuB,GAAG;QAAE,QAAQ,EAAE,KAAK,CAAA;KAAE,GACrD,OAAO,CAAC,yBAAyB,CAAC,CAAC,CAAC,CAAC;IAgFxC;;;;;;;;;OASG;IACH,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS;IAS9C,OAAO,CAAC,0BAA0B;CAanC"}
@@ -0,0 +1,36 @@
1
+ import type { AxiosResponse } from 'axios';
2
+ import { ErrorPayload } from '../../utils/types';
3
+ export interface NhostFunctionsConstructorParams {
4
+ /**
5
+ * Serverless Functions endpoint.
6
+ */
7
+ url: string;
8
+ /**
9
+ * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all requests.
10
+ */
11
+ adminSecret?: string;
12
+ }
13
+ export declare type NhostFunctionCallResponse<T = unknown> = {
14
+ res: {
15
+ data: T;
16
+ status: number;
17
+ statusText: string;
18
+ };
19
+ error: null;
20
+ } | {
21
+ res: null;
22
+ error: ErrorPayload;
23
+ };
24
+ /**@deprecated */
25
+ export declare type DeprecatedNhostFunctionCallResponse<T = unknown> = {
26
+ res: AxiosResponse<T>;
27
+ error: null;
28
+ } | {
29
+ res: null;
30
+ error: Error;
31
+ };
32
+ /** Subset of RequestInit parameters that are supported by the functions client */
33
+ export interface NhostFunctionCallConfig {
34
+ headers?: Record<string, string>;
35
+ }
36
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAA;AAC1C,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,oBAAY,yBAAyB,CAAC,CAAC,GAAG,OAAO,IAC7C;IACE,GAAG,EAAE;QACH,IAAI,EAAE,CAAC,CAAA;QACP,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,CAAA;CACpB,CAAA;AAEL,iBAAiB;AACjB,oBAAY,mCAAmC,CAAC,CAAC,GAAG,OAAO,IACvD;IACE,GAAG,EAAE,aAAa,CAAC,CAAC,CAAC,CAAA;IACrB,KAAK,EAAE,IAAI,CAAA;CACZ,GACD;IACE,GAAG,EAAE,IAAI,CAAA;IACT,KAAK,EAAE,KAAK,CAAA;CACb,CAAA;AAEL,kFAAkF;AAClF,MAAM,WAAW,uBAAuB;IACtC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CACjC"}
@@ -1,16 +1,7 @@
1
1
  import { AxiosRequestConfig } from 'axios';
2
2
  import { DocumentNode } from 'graphql';
3
- import { GraphqlRequestResponse, NhostClientConstructorParams } from '../utils/types';
4
- export interface NhostGraphqlConstructorParams {
5
- /**
6
- * GraphQL endpoint.
7
- */
8
- url: string;
9
- /**
10
- * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all requests.
11
- */
12
- adminSecret?: string;
13
- }
3
+ import { NhostClientConstructorParams } from '../../utils/types';
4
+ import { DeprecatedNhostGraphqlRequestResponse, NhostGraphqlConstructorParams, NhostGraphqlRequestConfig, NhostGraphqlRequestResponse } from './types';
14
5
  /**
15
6
  * Creates a client for GraphQL from either a subdomain or a URL
16
7
  */
@@ -24,25 +15,13 @@ export declare class NhostGraphqlClient {
24
15
  private accessToken;
25
16
  private adminSecret?;
26
17
  constructor(params: NhostGraphqlConstructorParams);
27
- /**
28
- * Use `nhost.graphql.request` to send a GraphQL request. For more serious GraphQL usage we recommend using a GraphQL client such as Apollo Client (https://www.apollographql.com/docs/react).
29
- *
30
- * @example
31
- * ```ts
32
- * const CUSTOMERS = gql`
33
- * query {
34
- * customers {
35
- * id
36
- * name
37
- * }
38
- * }
39
- * `
40
- * const { data, error } = await nhost.graphql.request(CUSTOMERS)
41
- * ```
42
- *
43
- * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/request
44
- */
45
- request<T = any, V = any>(document: string | DocumentNode, variables?: V, config?: AxiosRequestConfig): Promise<GraphqlRequestResponse<T>>;
18
+ /** @deprecated Axios will be replaced by cross-fetch in the near future. Only the headers configuration will be kept. */
19
+ request<T = any, V = any>(document: string | DocumentNode, variables?: V, config?: (AxiosRequestConfig | NhostGraphqlRequestConfig) & {
20
+ useAxios?: true;
21
+ }): Promise<DeprecatedNhostGraphqlRequestResponse<T>>;
22
+ request<T = any, V = any>(document: string | DocumentNode, variables?: V, config?: NhostGraphqlRequestConfig & {
23
+ useAxios: false;
24
+ }): Promise<NhostGraphqlRequestResponse<T>>;
46
25
  /**
47
26
  * Use `nhost.graphql.getUrl` to get the GraphQL URL.
48
27
  *
@@ -67,4 +46,4 @@ export declare class NhostGraphqlClient {
67
46
  setAccessToken(accessToken: string | undefined): void;
68
47
  private generateAccessTokenHeaders;
69
48
  }
70
- //# sourceMappingURL=graphql.d.ts.map
49
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAc,EAA6B,kBAAkB,EAAE,MAAM,OAAO,CAAA;AAC5E,OAAO,EAAE,YAAY,EAAuB,MAAM,SAAS,CAAA;AAE3D,OAAO,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAA;AAChE,OAAO,EACL,qCAAqC,EACrC,6BAA6B,EAC7B,yBAAyB,EACzB,2BAA2B,EAC5B,MAAM,SAAS,CAAA;AAEhB;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,4BAA4B,sBAWvE;AAED;;GAEG;AACH,qBAAa,kBAAkB;IAC7B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,OAAO,CAAC,QAAQ,CAAe;IAC/B,OAAO,CAAC,WAAW,CAAe;IAClC,OAAO,CAAC,WAAW,CAAC,CAAQ;gBAEhB,MAAM,EAAE,6BAA6B;IAWjD,yHAAyH;IACnH,OAAO,CAAC,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,GAAG,EAC5B,QAAQ,EAAE,MAAM,GAAG,YAAY,EAC/B,SAAS,CAAC,EAAE,CAAC,EACb,MAAM,CAAC,EAAE,CAAC,kBAAkB,GAAG,yBAAyB,CAAC,GAAG;QAAE,QAAQ,CAAC,EAAE,IAAI,CAAA;KAAE,GAC9E,OAAO,CAAC,qCAAqC,CAAC,CAAC,CAAC,CAAC;IAE9C,OAAO,CAAC,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,GAAG,EAC5B,QAAQ,EAAE,MAAM,GAAG,YAAY,EAC/B,SAAS,CAAC,EAAE,CAAC,EACb,MAAM,CAAC,EAAE,yBAAyB,GAAG;QAAE,QAAQ,EAAE,KAAK,CAAA;KAAE,GACvD,OAAO,CAAC,2BAA2B,CAAC,CAAC,CAAC,CAAC;IAsG1C;;;;;;;;;OASG;IACH,MAAM,IAAI,MAAM;IAIhB;;;;;;;;;OASG;IACH,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS;IAS9C,OAAO,CAAC,0BAA0B;CAanC"}
@@ -0,0 +1,32 @@
1
+ import { GraphQLError } from 'graphql';
2
+ import { ErrorPayload } from '../../utils/types';
3
+ export interface NhostGraphqlConstructorParams {
4
+ /**
5
+ * GraphQL endpoint.
6
+ */
7
+ url: string;
8
+ /**
9
+ * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all requests.
10
+ */
11
+ adminSecret?: string;
12
+ }
13
+ export declare type NhostGraphqlRequestResponse<T = unknown> = {
14
+ data: null;
15
+ error: GraphQLError[] | ErrorPayload;
16
+ } | {
17
+ data: T;
18
+ error: null;
19
+ };
20
+ /**@deprecated */
21
+ export declare type DeprecatedNhostGraphqlRequestResponse<T = unknown> = {
22
+ data: null;
23
+ error: Error | object | object[];
24
+ } | {
25
+ data: T;
26
+ error: null;
27
+ };
28
+ /** Subset of RequestInit parameters that are supported by the graphql client */
29
+ export interface NhostGraphqlRequestConfig {
30
+ headers?: Record<string, string>;
31
+ }
32
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAEhD,MAAM,WAAW,6BAA6B;IAC5C;;OAEG;IACH,GAAG,EAAE,MAAM,CAAA;IACX;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,oBAAY,2BAA2B,CAAC,CAAC,GAAG,OAAO,IAC/C;IACE,IAAI,EAAE,IAAI,CAAA;IACV,KAAK,EAAE,YAAY,EAAE,GAAG,YAAY,CAAA;CACrC,GACD;IACE,IAAI,EAAE,CAAC,CAAA;IACP,KAAK,EAAE,IAAI,CAAA;CACZ,CAAA;AAEL,iBAAiB;AACjB,oBAAY,qCAAqC,CAAC,CAAC,GAAG,OAAO,IACzD;IACE,IAAI,EAAE,IAAI,CAAA;IACV,KAAK,EAAE,KAAK,GAAG,MAAM,GAAG,MAAM,EAAE,CAAA;CACjC,GACD;IACE,IAAI,EAAE,CAAC,CAAA;IACP,KAAK,EAAE,IAAI,CAAA;CACZ,CAAA;AAEL,gFAAgF;AAChF,MAAM,WAAW,yBAAyB;IACxC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CACjC"}
@@ -1 +1 @@
1
- {"version":3,"file":"nhost.d.ts","sourceRoot":"","sources":["nhost.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,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AO,EAAE,mBAAmB,CAAA;IAC5B,SAAS,EAAE,oBAAoB,CAAA;IAC/B,OAAO,EAAE,kBAAkB,CAAA;IAC3B,OAAO,CAAC,YAAY,CAAC,CAAQ;IAC7B,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;IAE3B;;;;;;;;;OASG;gBACS,EACV,mBAAmB,EACnB,mBAAmB,EACnB,mBAAmB,EACnB,aAAa,EACb,iBAAiB,EACjB,gBAAgB,EAChB,UAAU,EACV,WAAW,EACX,QAAQ,EACR,KAAY,EACZ,GAAG,SAAS,EACb,EAAE,4BAA4B;IAqC/B,IAAI,WAAW,IAAI,MAAM,GAAG,SAAS,CAEpC;IAED,IAAI,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAM3C;CACF"}
package/dist/index.cjs.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var v=Object.defineProperty;var m=(t,e,r)=>e in t?v(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var o=(t,e,r)=>(m(t,typeof e!="symbol"?e+"":e,r),r);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const E=require("@nhost/hasura-auth-js"),_=require("axios"),y=require("graphql"),$=require("@nhost/hasura-storage-js"),N=t=>t&&typeof t=="object"&&"default"in t?t:{default:t},T=N(_),G=/^((?<protocol>http[s]?):\/\/)?(?<host>localhost)(:(?<port>(\d+|__\w+__)))?$/;function g(t,e){const{backendUrl:r,subdomain:n,region:a}=t;if(r)return`${r}/v1/${e}`;if(!n)throw new Error("Either `backendUrl` or `subdomain` must be set.");const s=n.match(G);if(s!=null&&s.groups){const{protocol:c="http",host:u,port:i=1337}=s.groups,l=F(e);return l||`${c}://${u}:${i}/v1/${e}`}if(!a)throw new Error('`region` must be set when using a `subdomain` other than "localhost".');return`https://${n}.${e}.${a}.nhost.run/v1`}function H(){return typeof window<"u"}function L(){return typeof process<"u"&&process.env}function F(t){return H()||!L()?null:process.env[`NHOST_${t.toUpperCase()}_URL`]}function p(t){const e="subdomain"in t||"backendUrl"in t?g(t,"auth"):t.authUrl;if(!e)throw new Error("Please provide `subdomain` or `authUrl`.");return new E.HasuraAuthClient({url:e,...t})}function A(t){const e="subdomain"in t||"backendUrl"in t?g(t,"functions"):t.functionsUrl;if(!e)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new b({url:e,...t})}class b{constructor(e){o(this,"url");o(this,"instance");o(this,"accessToken");o(this,"adminSecret");const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n,this.instance=T.default.create({baseURL:r})}async call(e,r,n){const a={...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers};let s;try{s=await this.instance.post(e,r,{...n,headers:a})}catch(c){if(c instanceof Error)return{res:null,error:c}}return s?{res:s,error:null}:{res:null,error:new Error("Unable to make post request to funtion")}}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 w(t){const e="subdomain"in t||"backendUrl"in t?g(t,"graphql"):t.graphqlUrl;if(!e)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new S({url:e,...t})}class S{constructor(e){o(this,"url");o(this,"instance");o(this,"accessToken");o(this,"adminSecret");const{url:r,adminSecret:n}=e;this.url=r,this.accessToken=null,this.adminSecret=n,this.instance=T.default.create({baseURL:r})}async request(e,r,n){const a={...this.generateAccessTokenHeaders(),...n==null?void 0:n.headers,"Accept-Encoding":"*"};try{const s="",u=(await this.instance.post("",{operationName:s||void 0,query:typeof e=="string"?e:y.print(e),variables:r},{...n,headers:a})).data,{data:i}=u;return u.errors?{data:null,error:u.errors}:typeof i!="object"||Array.isArray(i)||i===null?{data:null,error:new Error("incorrect response data from GraphQL server")}:{data:i,error:null}}catch(s){return s instanceof Error?{data:null,error:s}:(console.error(s),{data:null,error:new Error("Unable to get do GraphQL request")})}}getUrl(){return this.url}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 U(t){const e="subdomain"in t||"backendUrl"in t?g(t,"storage"):t.storageUrl;if(!e)throw new Error("Please provide `subdomain` or `storageUrl`.");return new $.HasuraStorageClient({url:e,...t})}const j=t=>new q(t);class q{constructor({refreshIntervalTime:e,clientStorageGetter:r,clientStorageSetter:n,clientStorage:a,clientStorageType:s,autoRefreshToken:c,autoSignIn:u,adminSecret:i,devTools:l,start:C=!0,...d}){o(this,"auth");o(this,"storage");o(this,"functions");o(this,"graphql");o(this,"_adminSecret");o(this,"devTools");this.auth=p({refreshIntervalTime:e,clientStorageGetter:r,clientStorageSetter:n,clientStorage:a,clientStorageType:s,autoRefreshToken:c,autoSignIn:u,start:C,...d}),this.storage=U({adminSecret:i,...d}),this.functions=A({adminSecret:i,...d}),this.graphql=w({adminSecret:i,...d}),this.auth.client.onStart(()=>{const k=this.auth.getAccessToken();this.storage.setAccessToken(k),this.functions.setAccessToken(k),this.graphql.setAccessToken(k),this.auth.onAuthStateChanged((h,f)=>{h==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(h=>{const f=h==null?void 0:h.accessToken;this.storage.setAccessToken(f),this.functions.setAccessToken(f),this.graphql.setAccessToken(f)})}),this._adminSecret=i,this.devTools=l}get adminSecret(){return this._adminSecret}set adminSecret(e){this._adminSecret=e,this.storage.setAdminSecret(e)}}exports.NhostClient=q;exports.NhostFunctionsClient=b;exports.NhostGraphqlClient=S;exports.createAuthClient=p;exports.createFunctionsClient=A;exports.createGraphqlClient=w;exports.createNhostClient=j;exports.createStorageClient=U;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@nhost/hasura-auth-js"),g=require("@nhost/hasura-storage-js"),k=require("axios"),q=require("graphql"),v=/^((?<protocol>http[s]?):\/\/)?(?<host>localhost)(:(?<port>(\d+|__\w+__)))?$/;function f(e,t){const{backendUrl:s,subdomain:r,region:o}=e;if(s)return`${s}/v1/${t}`;if(!r)throw new Error("Either `backendUrl` or `subdomain` must be set.");const c=r.match(v);if(c!=null&&c.groups){const{protocol:n="http",host:a,port:i=1337}=c.groups,u=$(t);return u||`${n}://${a}:${i}/v1/${t}`}if(!o)throw new Error('`region` must be set when using a `subdomain` other than "localhost".');return`https://${r}.${t}.${o}.nhost.run/v1`}function E(){return typeof window<"u"}function y(){return typeof process<"u"&&process.env}function $(e){return E()||!y()?null:process.env[`NHOST_${e.toUpperCase()}_URL`]}function b(e){const t="subdomain"in e||"backendUrl"in e?f(e,"auth"):e.authUrl;if(!t)throw new Error("Please provide `subdomain` or `authUrl`.");return new p.HasuraAuthClient({url:t,...e})}function w(e){const t="subdomain"in e||"backendUrl"in e?f(e,"functions"):e.functionsUrl;if(!t)throw new Error("Please provide `subdomain` or `functionsUrl`.");return new T({url:t,...e})}class T{constructor(t){const{url:s,adminSecret:r}=t;this.url=s,this.accessToken=null,this.adminSecret=r,this.instance=k.create({baseURL:s})}async call(t,s,{useAxios:r=!0,...o}={}){r&&console.warn("nhost.functions.call() will no longer use Axios in the near future. Please add `useAxios: false` in the config argument to use the new implementation.");const c={...this.generateAccessTokenHeaders(),...o==null?void 0:o.headers};let n;try{n=await this.instance.post(t,s,{...o,headers:c})}catch(a){if(a instanceof Error){if(r)return{res:null,error:a};const i=a;return{res:null,error:{error:i.code||"unknown",status:i.status||0,message:i.message}}}}return n?r?{res:n,error:null}:{res:{status:n.status,statusText:n.statusText,data:n.data},error:null}:r?{res:null,error:new Error("Unable to make post request to function")}:{res:null,error:{error:"invalid-response",status:0,message:"Unable to make post request to function"}}}setAccessToken(t){if(!t){this.accessToken=null;return}this.accessToken=t}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function m(e){const t="subdomain"in e||"backendUrl"in e?f(e,"graphql"):e.graphqlUrl;if(!t)throw new Error("Please provide `subdomain` or `graphqlUrl`.");return new U({url:t,...e})}class U{constructor(t){const{url:s,adminSecret:r}=t;this.url=s,this.accessToken=null,this.adminSecret=r,this.instance=k.create({baseURL:s})}async request(t,s,{useAxios:r=!0,...o}={}){const c={"Accept-Encoding":"*",...this.generateAccessTokenHeaders(),...o==null?void 0:o.headers};try{const n="",i=(await this.instance.post("",{operationName:n||void 0,query:typeof t=="string"?t:q.print(t),variables:s},{...o,headers:c})).data,{data:u}=i;return i.errors?{data:null,error:i.errors}:typeof u!="object"||Array.isArray(u)||u===null?r?{data:null,error:new Error("incorrect response data from GraphQL server")}:{data:null,error:{error:"invalid-response",status:0,message:"incorrect response data from GraphQL server"}}:{data:u,error:null}}catch(n){if(console.error(n),r)return n instanceof Error?{data:null,error:n}:{data:null,error:new Error("Unable to get do GraphQL request")};const a=n;return{data:null,error:{error:a.code||"unknown",status:a.status||0,message:a.message}}}}getUrl(){return this.url}setAccessToken(t){if(!t){this.accessToken=null;return}this.accessToken=t}generateAccessTokenHeaders(){return this.adminSecret?{"x-hasura-admin-secret":this.adminSecret}:this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}}function A(e){const t="subdomain"in e||"backendUrl"in e?f(e,"storage"):e.storageUrl;if(!t)throw new Error("Please provide `subdomain` or `storageUrl`.");return new g.HasuraStorageClient({url:t,...e})}const N=e=>new C(e);class C{constructor({refreshIntervalTime:t,clientStorageGetter:s,clientStorageSetter:r,clientStorage:o,clientStorageType:c,autoRefreshToken:n,autoSignIn:a,adminSecret:i,devTools:u,start:S=!0,...h}){this.auth=b({refreshIntervalTime:t,clientStorageGetter:s,clientStorageSetter:r,clientStorage:o,clientStorageType:c,autoRefreshToken:n,autoSignIn:a,start:S,...h}),this.storage=A({adminSecret:i,...h}),this.functions=w({adminSecret:i,...h}),this.graphql=m({adminSecret:i,...h}),this.auth.onAuthStateChanged((l,d)=>{l==="SIGNED_OUT"&&(this.storage.setAccessToken(void 0),this.functions.setAccessToken(void 0),this.graphql.setAccessToken(void 0))}),this.auth.onTokenChanged(l=>{const d=l==null?void 0:l.accessToken;this.storage.setAccessToken(d),this.functions.setAccessToken(d),this.graphql.setAccessToken(d)}),this._adminSecret=i,this.devTools=u}get adminSecret(){return this._adminSecret}set adminSecret(t){this._adminSecret=t,this.storage.setAdminSecret(t)}}exports.NhostClient=C;exports.NhostFunctionsClient=T;exports.NhostGraphqlClient=U;exports.createAuthClient=b;exports.createFunctionsClient=w;exports.createGraphqlClient=m;exports.createNhostClient=N;exports.createStorageClient=A;for(const e in p)e!=="default"&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:()=>p[e]});for(const e in g)e!=="default"&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:()=>g[e]});
2
2
  //# sourceMappingURL=index.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../src/utils/helpers.ts","../src/clients/auth.ts","../src/clients/functions.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__\"\nconst LOCALHOST_REGEX = /^((?<protocol>http[s]?):\\/\\/)?(?<host>localhost)(:(?<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]\n const subdomainLocalhostFound = subdomain.match(LOCALHOST_REGEX)\n if (subdomainLocalhostFound?.groups) {\n const { protocol = 'http', host, port = 1337 } = subdomainLocalhostFound.groups\n\n const urlFromEnv = getValueFromEnv(service)\n if (urlFromEnv) {\n return urlFromEnv\n }\n return `${protocol}://${host}:${port}/v1/${service}`\n }\n\n if (!region) {\n throw new Error('`region` must be set when using a `subdomain` other than \"localhost\".')\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","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 axios, {\n AxiosInstance,\n AxiosRequestConfig,\n AxiosResponse,\n RawAxiosRequestHeaders\n} from 'axios'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport { FunctionCallResponse, NhostClientConstructorParams } from '../utils/types'\nexport interface NhostFunctionsConstructorParams {\n /**\n * Serverless Functions endpoint.\n */\n url: string\n /**\n * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all requests.\n */\n adminSecret?: string\n}\n\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 instance: AxiosInstance\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 this.instance = axios.create({\n baseURL: url\n })\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 data: D,\n config?: AxiosRequestConfig\n ): Promise<FunctionCallResponse<T>> {\n const headers = {\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n let res\n try {\n res = await this.instance.post<T, AxiosResponse<T>, D>(url, data, { ...config, headers })\n } catch (error) {\n if (error instanceof Error) {\n return { res: null, error }\n }\n }\n\n if (!res) {\n return {\n res: null,\n error: new Error('Unable to make post request to funtion')\n }\n }\n\n return { res, error: null }\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 private generateAccessTokenHeaders(): RawAxiosRequestHeaders {\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 axios, { AxiosInstance, AxiosRequestConfig } from 'axios'\nimport { DocumentNode, print } from 'graphql'\n\nimport { urlFromSubdomain } from '../utils/helpers'\nimport {\n GraphqlRequestResponse,\n GraphqlResponse,\n NhostClientConstructorParams\n} from '../utils/types'\n\nexport interface NhostGraphqlConstructorParams {\n /**\n * GraphQL endpoint.\n */\n url: string\n /**\n * Admin secret. When set, it is sent as an `x-hasura-admin-secret` header for all requests.\n */\n adminSecret?: string\n}\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\n/**\n * @alias GraphQL\n */\nexport class NhostGraphqlClient {\n readonly url: string\n private instance: AxiosInstance\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostGraphqlConstructorParams) {\n const { url, adminSecret } = params\n\n this.url = url\n this.accessToken = null\n this.adminSecret = adminSecret\n this.instance = axios.create({\n baseURL: url\n })\n }\n\n /**\n * Use `nhost.graphql.request` to send a GraphQL request. For more serious GraphQL usage we recommend using a GraphQL client such as Apollo Client (https://www.apollographql.com/docs/react).\n *\n * @example\n * ```ts\n * const CUSTOMERS = gql`\n * query {\n * customers {\n * id\n * name\n * }\n * }\n * `\n * const { data, error } = await nhost.graphql.request(CUSTOMERS)\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/request\n */\n async request<T = any, V = any>(\n document: string | DocumentNode,\n variables?: V,\n config?: AxiosRequestConfig\n ): Promise<GraphqlRequestResponse<T>> {\n // add auth headers if any\n const headers = {\n ...this.generateAccessTokenHeaders(),\n ...config?.headers,\n 'Accept-Encoding': '*'\n }\n\n try {\n const operationName = ''\n const res = await this.instance.post<GraphqlResponse<T>>(\n '',\n {\n operationName: operationName || undefined,\n query: typeof document === 'string' ? document : print(document),\n variables\n },\n { ...config, headers }\n )\n\n const responseData = res.data\n const { data } = responseData\n\n if (responseData.errors) {\n return {\n data: null,\n error: responseData.errors\n }\n }\n\n if (typeof data !== 'object' || Array.isArray(data) || data === null) {\n return {\n data: null,\n error: new Error('incorrect response data from GraphQL server')\n }\n }\n\n return { data, error: null }\n } catch (error) {\n if (error instanceof Error) {\n return { data: null, error }\n }\n console.error(error)\n return {\n data: null,\n error: new Error('Unable to get do GraphQL request')\n }\n }\n }\n\n /**\n * Use `nhost.graphql.getUrl` to get the GraphQL URL.\n *\n * @example\n * ```ts\n * const url = nhost.graphql.getUrl();\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/get-url\n */\n getUrl(): string {\n return this.url\n }\n\n /**\n * Use `nhost.graphql.setAccessToken` to a set an access token to be used in subsequent graphql 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.graphql.setAccessToken('some-access-token')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/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 private generateAccessTokenHeaders(): Record<string, string> {\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 { 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 { HasuraAuthClient } from '@nhost/hasura-auth-js'\nimport { HasuraStorageClient } from '@nhost/hasura-storage-js'\n\nimport { NhostClientConstructorParams } from '../utils/types'\n\nimport { createAuthClient } from './auth'\nimport { createFunctionsClient, NhostFunctionsClient } from './functions'\nimport { createGraphqlClient, NhostGraphqlClient } from './graphql'\nimport { createStorageClient } from './storage'\n\nexport const createNhostClient = (params: NhostClientConstructorParams) => new NhostClient(params)\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 clientStorageGetter,\n clientStorageSetter,\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 clientStorageGetter,\n clientStorageSetter,\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.client.onStart(() => {\n // * Set current token if token is already accessable\n const accessToken = this.auth.getAccessToken()\n this.storage.setAccessToken(accessToken)\n this.functions.setAccessToken(accessToken)\n this.graphql.setAccessToken(accessToken)\n // * Set access token when signing out\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","createAuthClient","params","authUrl","HasuraAuthClient","createFunctionsClient","functionsUrl","NhostFunctionsClient","__publicField","url","adminSecret","axios","data","config","headers","res","error","accessToken","createGraphqlClient","graphqlUrl","NhostGraphqlClient","document","variables","operationName","responseData","print","createStorageClient","storageUrl","HasuraStorageClient","createNhostClient","NhostClient","refreshIntervalTime","clientStorageGetter","clientStorageSetter","clientStorage","clientStorageType","autoRefreshToken","autoSignIn","devTools","start","urlParams","_event","session","newValue"],"mappings":"0cAGMA,EAAkB,8EAUR,SAAAC,EACdC,EACAC,EACQ,CACR,KAAM,CAAE,WAAAC,EAAY,UAAAC,EAAW,OAAAC,CAAA,EAAWJ,EAE1C,GAAIE,EACF,MAAO,GAAGA,QAAiBD,IAG7B,GAAI,CAACE,EACG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ACD,KAAK,aAAeP,EACpB,KAAK,SAAW4B,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/index.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__\"\nconst LOCALHOST_REGEX = /^((?<protocol>http[s]?):\\/\\/)?(?<host>localhost)(:(?<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]\n const subdomainLocalhostFound = subdomain.match(LOCALHOST_REGEX)\n if (subdomainLocalhostFound?.groups) {\n const { protocol = 'http', host, port = 1337 } = subdomainLocalhostFound.groups\n\n const urlFromEnv = getValueFromEnv(service)\n if (urlFromEnv) {\n return urlFromEnv\n }\n return `${protocol}://${host}:${port}/v1/${service}`\n }\n\n if (!region) {\n throw new Error('`region` must be set when using a `subdomain` other than \"localhost\".')\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","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 axios, {\n AxiosError,\n AxiosInstance,\n AxiosRequestConfig,\n AxiosResponse,\n RawAxiosRequestHeaders\n} from 'axios'\nimport { urlFromSubdomain } from '../../utils/helpers'\nimport { NhostClientConstructorParams } from '../../utils/types'\nimport {\n DeprecatedNhostFunctionCallResponse,\n NhostFunctionCallConfig,\n NhostFunctionCallResponse,\n NhostFunctionsConstructorParams\n} from './types'\n\nexport * 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 instance: AxiosInstance\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 this.instance = axios.create({\n baseURL: url\n })\n }\n\n /** @deprecated Axios will be replaced by cross-fetch in the near future. Only the headers configuration will be kept. */\n async call<T = unknown, D = any>(\n url: string,\n data?: D,\n config?: (NhostFunctionCallConfig | AxiosRequestConfig) & { useAxios?: true }\n ): Promise<DeprecatedNhostFunctionCallResponse<T>>\n\n async call<T = unknown, D = any>(\n url: string,\n data: D,\n config?: NhostFunctionCallConfig & { useAxios: false }\n ): Promise<NhostFunctionCallResponse<T>>\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 data: D,\n {\n useAxios = true,\n ...config\n }: (AxiosRequestConfig | NhostFunctionCallConfig) & { useAxios?: boolean } = {}\n ): Promise<DeprecatedNhostFunctionCallResponse<T> | NhostFunctionCallResponse> {\n if (useAxios) {\n console.warn(\n 'nhost.functions.call() will no longer use Axios in the near future. Please add `useAxios: false` in the config argument to use the new implementation.'\n )\n }\n const headers = {\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n let res\n try {\n res = await this.instance.post<T, AxiosResponse<T>, D>(url, data, { ...config, headers })\n } catch (error) {\n if (error instanceof Error) {\n if (useAxios) {\n return { res: null, error }\n }\n const axiosError = error as AxiosError\n return {\n res: null,\n error: {\n error: axiosError.code || 'unknown',\n status: axiosError.status || 0,\n message: axiosError.message\n }\n }\n }\n }\n\n if (!res) {\n if (useAxios) {\n return {\n res: null,\n error: new Error('Unable to make post request to function')\n }\n }\n return {\n res: null,\n error: {\n error: 'invalid-response',\n status: 0,\n message: 'Unable to make post request to function'\n }\n }\n }\n\n if (useAxios) {\n return { res, error: null }\n }\n return {\n res: {\n status: res.status,\n statusText: res.statusText,\n data: res.data\n },\n error: null\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 private generateAccessTokenHeaders(): RawAxiosRequestHeaders {\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 axios, { AxiosError, AxiosInstance, AxiosRequestConfig } from 'axios'\nimport { DocumentNode, GraphQLError, print } from 'graphql'\nimport { urlFromSubdomain } from '../../utils/helpers'\nimport { NhostClientConstructorParams } from '../../utils/types'\nimport {\n DeprecatedNhostGraphqlRequestResponse,\n NhostGraphqlConstructorParams,\n NhostGraphqlRequestConfig,\n NhostGraphqlRequestResponse\n} from './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\n/**\n * @alias GraphQL\n */\nexport class NhostGraphqlClient {\n readonly url: string\n private instance: AxiosInstance\n private accessToken: string | null\n private adminSecret?: string\n\n constructor(params: NhostGraphqlConstructorParams) {\n const { url, adminSecret } = params\n\n this.url = url\n this.accessToken = null\n this.adminSecret = adminSecret\n this.instance = axios.create({\n baseURL: url\n })\n }\n\n /** @deprecated Axios will be replaced by cross-fetch in the near future. Only the headers configuration will be kept. */\n async request<T = any, V = any>(\n document: string | DocumentNode,\n variables?: V,\n config?: (AxiosRequestConfig | NhostGraphqlRequestConfig) & { useAxios?: true }\n ): Promise<DeprecatedNhostGraphqlRequestResponse<T>>\n\n async request<T = any, V = any>(\n document: string | DocumentNode,\n variables?: V,\n config?: NhostGraphqlRequestConfig & { useAxios: false }\n ): Promise<NhostGraphqlRequestResponse<T>>\n\n /**\n * Use `nhost.graphql.request` to send a GraphQL request. For more serious GraphQL usage we recommend using a GraphQL client such as Apollo Client (https://www.apollographql.com/docs/react).\n *\n * @example\n * ```ts\n * const CUSTOMERS = gql`\n * query {\n * customers {\n * id\n * name\n * }\n * }\n * `\n * const { data, error } = await nhost.graphql.request(CUSTOMERS)\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/request\n */\n async request<T = any, V = any>(\n document: string | DocumentNode,\n variables?: V,\n {\n useAxios = true,\n ...config\n }: (AxiosRequestConfig | NhostGraphqlRequestConfig) & { useAxios?: boolean } = {}\n ): Promise<DeprecatedNhostGraphqlRequestResponse<T> | NhostGraphqlRequestResponse<T>> {\n // add auth headers if any\n const headers = {\n 'Accept-Encoding': '*',\n ...this.generateAccessTokenHeaders(),\n ...config?.headers\n }\n\n try {\n const operationName = ''\n const res = await this.instance.post<{\n errors?: GraphQLError[]\n data?: T\n }>(\n '',\n {\n operationName: operationName || undefined,\n query: typeof document === 'string' ? document : print(document),\n variables\n },\n { ...config, headers }\n )\n\n const responseData = res.data\n const { data } = responseData\n\n if (responseData.errors) {\n return {\n data: null,\n error: responseData.errors\n }\n }\n\n if (typeof data !== 'object' || Array.isArray(data) || data === null) {\n if (useAxios) {\n return {\n data: null,\n error: new Error('incorrect response data from GraphQL server')\n }\n }\n return {\n data: null,\n error: {\n error: 'invalid-response',\n status: 0,\n message: 'incorrect response data from GraphQL server'\n }\n }\n }\n\n return { data, error: null }\n } catch (error) {\n console.error(error)\n if (useAxios) {\n if (error instanceof Error) {\n return { data: null, error }\n }\n return {\n data: null,\n error: new Error('Unable to get do GraphQL request')\n }\n }\n\n const axiosError = error as AxiosError\n return {\n data: null,\n error: {\n error: axiosError.code || 'unknown',\n status: axiosError.status || 0,\n message: axiosError.message\n }\n }\n }\n }\n\n /**\n * Use `nhost.graphql.getUrl` to get the GraphQL URL.\n *\n * @example\n * ```ts\n * const url = nhost.graphql.getUrl();\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/get-url\n */\n getUrl(): string {\n return this.url\n }\n\n /**\n * Use `nhost.graphql.setAccessToken` to a set an access token to be used in subsequent graphql 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.graphql.setAccessToken('some-access-token')\n * ```\n *\n * @docs https://docs.nhost.io/reference/javascript/nhost-js/graphql/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 private generateAccessTokenHeaders(): Record<string, string> {\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 { 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 { 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, NhostGraphqlClient } from './graphql'\nimport { createStorageClient } from './storage'\n\nexport const createNhostClient = (params: NhostClientConstructorParams) => new NhostClient(params)\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 clientStorageGetter,\n clientStorageSetter,\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 clientStorageGetter,\n clientStorageSetter,\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","createAuthClient","params","authUrl","HasuraAuthClient","createFunctionsClient","functionsUrl","NhostFunctionsClient","url","adminSecret","axios","data","useAxios","config","headers","res","error","axiosError","accessToken","createGraphqlClient","graphqlUrl","NhostGraphqlClient","document","variables","operationName","responseData","print","createStorageClient","storageUrl","HasuraStorageClient","createNhostClient","NhostClient","refreshIntervalTime","clientStorageGetter","clientStorageSetter","clientStorage","clientStorageType","autoRefreshToken","autoSignIn","devTools","start","urlParams","_event","session","newValue"],"mappings":"uMAGMA,EAAkB,8EAUR,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,EAAW,OAAQ,KAAAC,EAAM,KAAAC,EAAO,MAASH,EAAwB,OAEnEI,EAAaC,EAAgBT,CAAO,EAC1C,OAAIQ,GAGG,GAAGH,OAAcC,KAAQC,QAAWP,GAC7C,CAEA,GAAI,CAACG,EACG,MAAA,IAAI,MAAM,uEAAuE,EAGlF,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,IAAI,SAASX,EAAQ,YAAY,QAClD,CClEO,SAASY,EAAiBC,EAAsC,CAC/D,M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AAyC,IAAI6B,EAAY7B,CAAM,EAC1F,MAAM6B,CAAY,CAkBvB,YAAY,CACV,oBAAAC,EACA,oBAAAC,EACA,oBAAAC,EACA,cAAAC,EACA,kBAAAC,EACA,iBAAAC,EACA,WAAAC,EACA,YAAA7B,EACA,SAAA8B,EACA,MAAAC,EAAQ,MACLC,CAAA,EAC4B,CAE/B,KAAK,KAAOxC,EAAiB,CAC3B,oBAAA+B,EACA,oBAAAC,EACA,oBAAAC,EACA,cAAAC,EACA,kBAAAC,EACA,iBAAAC,EACA,WAAAC,EACA,MAAAE,EACA,GAAGC,CAAA,CACJ,EACD,KAAK,QAAUd,EAAoB,CAAE,YAAAlB,EAAa,GAAGgC,EAAW,EAChE,KAAK,UAAYpC,EAAsB,CAAE,YAAAI,EAAa,GAAGgC,EAAW,EACpE,KAAK,QAAUtB,EAAoB,CAAE,YAAAV,EAAa,GAAGgC,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,MAAMzB,EAAcyB,GAAA,YAAAA,EAAS,YACxB,KAAA,QAAQ,eAAezB,CAAW,EAClC,KAAA,UAAU,eAAeA,CAAW,EACpC,KAAA,QAAQ,eAAeA,CAAW,CAAA,CACxC,EAED,KAAK,aAAeT,EACpB,KAAK,SAAW8B,CAClB,CAEA,IAAI,aAAkC,CACpC,OAAO,KAAK,YACd,CAEA,IAAI,YAAYK,EAA8B,CAC5C,KAAK,aAAeA,EACf,KAAA,QAAQ,eAAeA,CAAQ,CAItC,CACF"}
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export * from '@nhost/hasura-auth-js';
2
+ export * from '@nhost/hasura-storage-js';
1
3
  export * from './clients';
2
4
  export * from './utils/types';
3
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAA;AACzB,cAAc,eAAe,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAA;AAIrC,cAAc,0BAA0B,CAAA;AACxC,cAAc,WAAW,CAAA;AAIzB,cAAc,eAAe,CAAA"}