@nestbridge/runtime 0.1.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,10 +3,12 @@
3
3
  [![CI](https://github.com/MDReal32/nestbridge/actions/workflows/ci.yml/badge.svg)](https://github.com/MDReal32/nestbridge/actions/workflows/ci.yml)
4
4
  [![npm](https://img.shields.io/npm/v/@nestbridge/runtime.svg)](https://www.npmjs.com/package/@nestbridge/runtime)
5
5
 
6
- The browser-side `fetch()` client that NestBridge's generated controller
7
- modules call into. Zero dependencies, and no knowledge of NestJS or Vite —
8
- see the [repository README](../../README.md) for how this fits into the rest
9
- of NestBridge.
6
+ The browser-side client that NestBridge's generated controller and resolver
7
+ modules call into: a dependency-free `fetch()` wrapper for REST, and a
8
+ [`graphql-request`](https://github.com/jasonkuhrt/graphql-request)-based
9
+ client for GraphQL. No knowledge of NestJS or Vite either way — see the
10
+ [repository README](../../README.md) for how this fits into the rest of
11
+ NestBridge.
10
12
 
11
13
  ## Install
12
14
 
@@ -34,6 +36,7 @@ than merging, so pass everything you need in one call.
34
36
  ```ts
35
37
  interface NestBridgeConfig {
36
38
  baseURL?: string;
39
+ graphqlEndpoint?: string; // defaults to `${baseURL}/graphql`
37
40
  headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
38
41
  fetch?: typeof globalThis.fetch;
39
42
  }
@@ -52,14 +55,32 @@ class NestBridgeError<T = unknown> extends Error {
52
55
  }
53
56
  ```
54
57
 
58
+ ## `graphqlRequest()`
59
+
60
+ Generated resolver modules call `graphqlRequest()` directly; you won't
61
+ normally call it yourself either. It sends the given document/variables to
62
+ `graphqlEndpoint` via `graphql-request`'s `GraphQLClient`. Failed requests
63
+ reject with a `NestBridgeGraphqlError`:
64
+
65
+ ```ts
66
+ class NestBridgeGraphqlError extends Error {
67
+ readonly status: number;
68
+ readonly errors: GraphQLError[] | undefined;
69
+ readonly data: Record<string, unknown> | undefined;
70
+ readonly request: unknown;
71
+ }
72
+ ```
73
+
55
74
  ## Types
56
75
 
57
76
  - `NestBridgeConfig` — the shape passed to `configureNestBridge`.
58
- - `NestBridgeRequest` — the shape of a single generated request.
77
+ - `NestBridgeRequest` — the shape of a single generated REST request.
78
+ - `NestBridgeGraphqlRequest` — the shape of a single generated GraphQL
79
+ request (`document` + optional `variables`).
59
80
  - `RemoteMethod<T>` / `RemoteResult<T>` — the type-level helpers that project
60
- a real controller method's parameters and return type onto its generated
61
- client method. Useful outside code generation too — a manual SDK wrapper, a
62
- mock, a test double.
81
+ a real controller or resolver method's parameters and return type onto its
82
+ generated client method. Useful outside code generation too — a manual SDK
83
+ wrapper, a mock, a test double.
63
84
 
64
85
  ## License
65
86
 
@@ -1,7 +1,13 @@
1
+ import { ClientError } from 'graphql-request';
2
+ import { Observable } from 'rxjs';
3
+
1
4
  export declare const configureNestBridge: (config: NestBridgeConfig) => void;
2
5
 
6
+ export declare const graphqlRequest: <T>(nestBridgeGraphqlRequest: NestBridgeGraphqlRequest) => Promise<T>;
7
+
3
8
  export declare interface NestBridgeConfig {
4
9
  baseURL?: string;
10
+ graphqlEndpoint?: string;
5
11
  headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
6
12
  fetch?: typeof globalThis.fetch;
7
13
  }
@@ -13,20 +19,40 @@ export declare class NestBridgeError<T = unknown> extends Error {
13
19
  constructor(message: string, status: number, body: T, response: Response);
14
20
  }
15
21
 
22
+ export declare class NestBridgeGraphqlError extends Error {
23
+ readonly status: number;
24
+ readonly errors: ClientError['response']['errors'];
25
+ readonly data: ClientError['response']['data'];
26
+ readonly request: ClientError['request'];
27
+ constructor(clientError: ClientError, endpoint: string);
28
+ }
29
+
30
+ export declare interface NestBridgeGraphqlRequest {
31
+ document: string;
32
+ variables?: Record<string, unknown>;
33
+ }
34
+
16
35
  export declare interface NestBridgeRequest {
17
36
  method: string;
18
37
  path: string;
19
38
  query?: Record<string, unknown>;
20
39
  body?: unknown;
21
40
  headers?: Record<string, string | undefined>;
41
+ responseType?: 'json' | 'blob';
22
42
  }
23
43
 
24
44
  export declare type RemoteMethod<T> = T extends (...args: infer Args) => unknown ? (...args: Args) => RemoteResult<T> : never;
25
45
 
46
+ export declare type RemoteObservableResult<T> = T extends (...args: never[]) => infer Result ? Promise<UnwrapObservableResult<Result>> : never;
47
+
26
48
  export declare type RemoteResult<T> = T extends (...args: never[]) => infer Result ? Promise<Awaited<Result>> : never;
27
49
 
50
+ export declare type RemoteStreamResult<T> = T extends (...args: never[]) => unknown ? Promise<Blob> : never;
51
+
28
52
  export declare const request: <T>(nestBridgeRequest: NestBridgeRequest) => Promise<T>;
29
53
 
54
+ declare type UnwrapObservableResult<Result> = Result extends Observable<infer Value> ? Value : Result extends Promise<Observable<infer Value>> ? Value : never;
55
+
30
56
  export declare const VERSION: string;
31
57
 
32
58
  export { }
@@ -1,9 +1,79 @@
1
+ import { GraphQLClient, ClientError } from 'graphql-request';
2
+
1
3
  let currentConfig = {};
2
4
  const configureNestBridge = (config) => {
3
5
  currentConfig = config;
4
6
  };
5
7
  const getNestBridgeConfig = () => currentConfig;
6
8
 
9
+ const resolveRequestHeaders = async (config, requestHeaders, hasBody) => {
10
+ const globalHeaders = typeof config.headers === "function" ? await config.headers() : config.headers ?? {};
11
+ const merged = { ...globalHeaders };
12
+ if (hasBody) {
13
+ merged["content-type"] = "application/json";
14
+ }
15
+ for (const [key, value] of Object.entries(requestHeaders ?? {})) {
16
+ if (value !== void 0) {
17
+ merged[key] = value;
18
+ }
19
+ }
20
+ return merged;
21
+ };
22
+
23
+ const extractGraphqlErrorMessage = (response) => {
24
+ if (response.errors !== void 0 && response.errors.length > 0) {
25
+ return response.errors.map((error) => error.message).join(", ");
26
+ }
27
+ if (typeof response.body === "string" && response.body.length > 0) {
28
+ return response.body;
29
+ }
30
+ return void 0;
31
+ };
32
+
33
+ class NestBridgeGraphqlError extends Error {
34
+ status;
35
+ errors;
36
+ data;
37
+ request;
38
+ constructor(clientError, endpoint) {
39
+ const backendMessage = extractGraphqlErrorMessage(clientError.response);
40
+ const message = `NestBridge GraphQL request to ${endpoint} failed with status ${clientError.response.status}.${backendMessage === void 0 ? "" : ` ${backendMessage}`}`;
41
+ super(message);
42
+ this.name = "NestBridgeGraphqlError";
43
+ this.status = clientError.response.status;
44
+ this.errors = clientError.response.errors;
45
+ this.data = clientError.response.data;
46
+ this.request = clientError.request;
47
+ }
48
+ }
49
+
50
+ const isAbsoluteUrl = (value) => /^[a-z][a-z\d+.-]*:\/\//i.test(value);
51
+ const resolveGraphqlEndpoint = (config) => {
52
+ const endpoint = config.graphqlEndpoint ?? `${config.baseURL ?? ""}/graphql`;
53
+ if (isAbsoluteUrl(endpoint) || typeof globalThis.location === "undefined") {
54
+ return endpoint;
55
+ }
56
+ return new URL(endpoint, globalThis.location.origin).toString();
57
+ };
58
+
59
+ const graphqlRequest = async (nestBridgeGraphqlRequest) => {
60
+ const config = getNestBridgeConfig();
61
+ const endpoint = resolveGraphqlEndpoint(config);
62
+ const headers = await resolveRequestHeaders(config, void 0, false);
63
+ const client = new GraphQLClient(endpoint, { fetch: config.fetch, headers });
64
+ try {
65
+ return await client.request(
66
+ nestBridgeGraphqlRequest.document,
67
+ nestBridgeGraphqlRequest.variables
68
+ );
69
+ } catch (error) {
70
+ if (error instanceof ClientError) {
71
+ throw new NestBridgeGraphqlError(error, endpoint);
72
+ }
73
+ throw error;
74
+ }
75
+ };
76
+
7
77
  class NestBridgeError extends Error {
8
78
  status;
9
79
  body;
@@ -42,6 +112,25 @@ const buildRequestUrl = (baseURL, path, query) => {
42
112
  return queryString.length > 0 ? `${url}?${queryString}` : url;
43
113
  };
44
114
 
115
+ const extractErrorMessage = (body) => {
116
+ if (typeof body === "string") {
117
+ return body.length > 0 ? body : void 0;
118
+ }
119
+ if (typeof body === "object" && body !== null && "message" in body) {
120
+ const { message } = body;
121
+ if (typeof message === "string") {
122
+ return message;
123
+ }
124
+ if (Array.isArray(message)) {
125
+ return message.join(", ");
126
+ }
127
+ }
128
+ if (typeof body === "object" && body !== null) {
129
+ return JSON.stringify(body);
130
+ }
131
+ return void 0;
132
+ };
133
+
45
134
  const parseResponseBody = async (response) => {
46
135
  if (response.status === 204 || response.status === 205) {
47
136
  return void 0;
@@ -57,20 +146,6 @@ const parseResponseBody = async (response) => {
57
146
  return JSON.parse(text);
58
147
  };
59
148
 
60
- const resolveRequestHeaders = async (config, requestHeaders, hasBody) => {
61
- const globalHeaders = typeof config.headers === "function" ? await config.headers() : config.headers ?? {};
62
- const merged = { ...globalHeaders };
63
- if (hasBody) {
64
- merged["content-type"] = "application/json";
65
- }
66
- for (const [key, value] of Object.entries(requestHeaders ?? {})) {
67
- if (value !== void 0) {
68
- merged[key] = value;
69
- }
70
- }
71
- return merged;
72
- };
73
-
74
149
  const request = async (nestBridgeRequest) => {
75
150
  const config = getNestBridgeConfig();
76
151
  const fetchImplementation = config.fetch ?? globalThis.fetch;
@@ -82,21 +157,21 @@ const request = async (nestBridgeRequest) => {
82
157
  headers,
83
158
  body: hasBody ? JSON.stringify(nestBridgeRequest.body) : void 0
84
159
  });
85
- const responseBody = await parseResponseBody(response);
86
160
  if (!response.ok) {
87
- throw new NestBridgeError(
88
- `NestBridge request to ${url} failed with status ${response.status}.`,
89
- response.status,
90
- responseBody,
91
- response
92
- );
161
+ const responseBody = await parseResponseBody(response);
162
+ const backendMessage = extractErrorMessage(responseBody);
163
+ const message = `NestBridge request to ${url} failed with status ${response.status}.${backendMessage === void 0 ? "" : ` ${backendMessage}`}`;
164
+ throw new NestBridgeError(message, response.status, responseBody, response);
165
+ }
166
+ if (nestBridgeRequest.responseType === "blob") {
167
+ return await response.blob();
93
168
  }
94
- return responseBody;
169
+ return await parseResponseBody(response);
95
170
  };
96
171
 
97
- const version = "0.1.1";
172
+ const version = "1.1.0";
98
173
 
99
174
  const VERSION = version;
100
175
 
101
- export { NestBridgeError, VERSION, configureNestBridge, request };
176
+ export { NestBridgeError, NestBridgeGraphqlError, VERSION, configureNestBridge, graphqlRequest, request };
102
177
  //# sourceMappingURL=nestbridge.runtime.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"nestbridge.runtime.js","sources":["../src/config/configure-nestbridge.ts","../src/http-adapter/nestbridge-error.ts","../src/http-adapter/build-request-url.ts","../src/http-adapter/parse-response-body.ts","../src/http-adapter/resolve-request-headers.ts","../src/http-adapter/request.ts","../src/version.ts"],"sourcesContent":["import type { NestBridgeConfig } from './nestbridge-config';\n\nlet currentConfig: NestBridgeConfig = {};\n\nexport const configureNestBridge = (config: NestBridgeConfig) => {\n currentConfig = config;\n};\n\nexport const getNestBridgeConfig = () => currentConfig;\n","export class NestBridgeError<T = unknown> extends Error {\n readonly status: number;\n readonly body: T;\n readonly response: Response;\n\n constructor(message: string, status: number, body: T, response: Response) {\n super(message);\n this.name = 'NestBridgeError';\n this.status = status;\n this.body = body;\n this.response = response;\n }\n}\n","const serializeQuery = (query: Record<string, unknown>) => {\n const searchParams = new URLSearchParams();\n\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n searchParams.append(key, String(item));\n }\n continue;\n }\n\n searchParams.append(key, String(value));\n }\n\n return searchParams.toString();\n};\n\nexport const buildRequestUrl = (\n baseURL: string | undefined,\n path: string,\n query: Record<string, unknown> | undefined,\n) => {\n const url = `${baseURL ?? ''}${path}`;\n\n if (query === undefined) {\n return url;\n }\n\n const queryString = serializeQuery(query);\n\n return queryString.length > 0 ? `${url}?${queryString}` : url;\n};\n","export const parseResponseBody = async (response: Response): Promise<unknown> => {\n if (response.status === 204 || response.status === 205) {\n return undefined;\n }\n\n const text = await response.text();\n\n if (text.length === 0) {\n return undefined;\n }\n\n const contentType = response.headers.get('content-type') ?? '';\n\n if (!contentType.includes('application/json')) {\n return text;\n }\n\n return JSON.parse(text);\n};\n","import type { NestBridgeConfig } from '../config/nestbridge-config';\n\nexport const resolveRequestHeaders = async (\n config: NestBridgeConfig,\n requestHeaders: Record<string, string | undefined> | undefined,\n hasBody: boolean,\n) => {\n const globalHeaders =\n typeof config.headers === 'function' ? await config.headers() : (config.headers ?? {});\n const merged: Record<string, string> = { ...globalHeaders };\n\n if (hasBody) {\n merged['content-type'] = 'application/json';\n }\n\n for (const [key, value] of Object.entries(requestHeaders ?? {})) {\n if (value !== undefined) {\n merged[key] = value;\n }\n }\n\n return merged;\n};\n","import { getNestBridgeConfig } from '../config';\nimport { buildRequestUrl } from './build-request-url';\nimport { NestBridgeError } from './nestbridge-error';\nimport type { NestBridgeRequest } from './nestbridge-request';\nimport { parseResponseBody } from './parse-response-body';\nimport { resolveRequestHeaders } from './resolve-request-headers';\n\nexport const request = async <T>(nestBridgeRequest: NestBridgeRequest) => {\n const config = getNestBridgeConfig();\n const fetchImplementation = config.fetch ?? globalThis.fetch;\n const hasBody = nestBridgeRequest.body !== undefined;\n const url = buildRequestUrl(config.baseURL, nestBridgeRequest.path, nestBridgeRequest.query);\n const headers = await resolveRequestHeaders(config, nestBridgeRequest.headers, hasBody);\n\n const response = await fetchImplementation(url, {\n method: nestBridgeRequest.method,\n headers,\n body: hasBody ? JSON.stringify(nestBridgeRequest.body) : undefined,\n });\n\n const responseBody = await parseResponseBody(response);\n\n if (!response.ok) {\n throw new NestBridgeError(\n `NestBridge request to ${url} failed with status ${response.status}.`,\n response.status,\n responseBody,\n response,\n );\n }\n\n return responseBody as T;\n};\n","import { version } from '../package.json';\n\nexport const VERSION: string = version;\n"],"names":[],"mappings":"AAEA,IAAI,gBAAkC,EAAC;AAEhC,MAAM,mBAAA,GAAsB,CAAC,MAAA,KAA6B;AAC/D,EAAA,aAAA,GAAgB,MAAA;AAClB;AAEO,MAAM,sBAAsB,MAAM,aAAA;;ACRlC,MAAM,wBAAqC,KAAA,CAAM;AAAA,EAC7C,MAAA;AAAA,EACA,IAAA;AAAA,EACA,QAAA;AAAA,EAET,WAAA,CAAY,OAAA,EAAiB,MAAA,EAAgB,IAAA,EAAS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,iBAAA,KAAyC;AACxE,EAAA,MAAM,SAAS,mBAAA,EAAoB;AACnC,EAAA,MAAM,mBAAA,GAAsB,MAAA,CAAO,KAAA,IAAS,UAAA,CAAW,KAAA;AACvD,EAAA,MAAM,OAAA,GAAU,kBAAkB,IAAA,KAAS,MAAA;AAC3C,EAAA,MAAM,MAAM,eAAA,CAAgB,MAAA,CAAO,SAAS,iBAAA,CAAkB,IAAA,EAAM,kBAAkB,KAAK,CAAA;AAC3F,EAAA,MAAM,UAAU,MAAM,qBAAA,CAAsB,MAAA,EAAQ,iBAAA,CAAkB,SAAS,OAAO,CAAA;AAEtF,EAAA,MAAM,QAAA,GAAW,MAAM,mBAAA,CAAoB,GAAA,EAAK;AAAA,IAC9C,QAAQ,iBAAA,CAAkB,MAAA;AAAA,IAC1B,OAAA;AAAA,IACA,MAAM,OAAA,GAAU,IAAA,CAAK,SAAA,CAAU,iBAAA,CAAkB,IAAI,CAAA,GAAI;AAAA,GAC1D,CAAA;AAED,EAAA,MAAM,YAAA,GAAe,MAAM,iBAAA,CAAkB,QAAQ,CAAA;AAErD,EAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,IAAA,MAAM,IAAI,eAAA;AAAA,MACR,CAAA,sBAAA,EAAyB,GAAG,CAAA,oBAAA,EAAuB,QAAA,CAAS,MAAM,CAAA,CAAA,CAAA;AAAA,MAClE,QAAA,CAAS,MAAA;AAAA,MACT,YAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO,YAAA;AACT;;;;AC9BO,MAAM,OAAA,GAAkB;;"}
1
+ {"version":3,"file":"nestbridge.runtime.js","sources":["../src/config/configure-nestbridge.ts","../src/http-adapter/resolve-request-headers.ts","../src/graphql-adapter/extract-graphql-error-message.ts","../src/graphql-adapter/nestbridge-graphql-error.ts","../src/graphql-adapter/resolve-graphql-endpoint.ts","../src/graphql-adapter/graphql-request.ts","../src/http-adapter/nestbridge-error.ts","../src/http-adapter/build-request-url.ts","../src/http-adapter/extract-error-message.ts","../src/http-adapter/parse-response-body.ts","../src/http-adapter/request.ts","../src/version.ts"],"sourcesContent":["import type { NestBridgeConfig } from './nestbridge-config';\n\nlet currentConfig: NestBridgeConfig = {};\n\nexport const configureNestBridge = (config: NestBridgeConfig) => {\n currentConfig = config;\n};\n\nexport const getNestBridgeConfig = () => currentConfig;\n","import type { NestBridgeConfig } from '../config/nestbridge-config';\n\nexport const resolveRequestHeaders = async (\n config: NestBridgeConfig,\n requestHeaders: Record<string, string | undefined> | undefined,\n hasBody: boolean,\n) => {\n const globalHeaders =\n typeof config.headers === 'function' ? await config.headers() : (config.headers ?? {});\n const merged: Record<string, string> = { ...globalHeaders };\n\n if (hasBody) {\n merged['content-type'] = 'application/json';\n }\n\n for (const [key, value] of Object.entries(requestHeaders ?? {})) {\n if (value !== undefined) {\n merged[key] = value;\n }\n }\n\n return merged;\n};\n","import type { ClientError } from 'graphql-request';\n\nexport const extractGraphqlErrorMessage = (\n response: ClientError['response'],\n): string | undefined => {\n if (response.errors !== undefined && response.errors.length > 0) {\n return response.errors.map((error) => error.message).join(', ');\n }\n\n if (typeof response.body === 'string' && response.body.length > 0) {\n return response.body;\n }\n\n return undefined;\n};\n","import type { ClientError } from 'graphql-request';\n\nimport { extractGraphqlErrorMessage } from './extract-graphql-error-message';\n\nexport class NestBridgeGraphqlError extends Error {\n readonly status: number;\n readonly errors: ClientError['response']['errors'];\n readonly data: ClientError['response']['data'];\n readonly request: ClientError['request'];\n\n constructor(clientError: ClientError, endpoint: string) {\n const backendMessage = extractGraphqlErrorMessage(clientError.response);\n const message = `NestBridge GraphQL request to ${endpoint} failed with status ${\n clientError.response.status\n }.${backendMessage === undefined ? '' : ` ${backendMessage}`}`;\n\n super(message);\n this.name = 'NestBridgeGraphqlError';\n this.status = clientError.response.status;\n this.errors = clientError.response.errors;\n this.data = clientError.response.data;\n this.request = clientError.request;\n }\n}\n","import type { NestBridgeConfig } from '../config';\n\nconst isAbsoluteUrl = (value: string) => /^[a-z][a-z\\d+.-]*:\\/\\//i.test(value);\n\nexport const resolveGraphqlEndpoint = (config: NestBridgeConfig) => {\n const endpoint = config.graphqlEndpoint ?? `${config.baseURL ?? ''}/graphql`;\n\n if (isAbsoluteUrl(endpoint) || typeof globalThis.location === 'undefined') {\n return endpoint;\n }\n\n return new URL(endpoint, globalThis.location.origin).toString();\n};\n","import { ClientError, GraphQLClient } from 'graphql-request';\n\nimport { getNestBridgeConfig } from '../config';\nimport { resolveRequestHeaders } from '../http-adapter/resolve-request-headers';\nimport { NestBridgeGraphqlError } from './nestbridge-graphql-error';\nimport type { NestBridgeGraphqlRequest } from './nestbridge-graphql-request';\nimport { resolveGraphqlEndpoint } from './resolve-graphql-endpoint';\n\nexport const graphqlRequest = async <T>(nestBridgeGraphqlRequest: NestBridgeGraphqlRequest) => {\n const config = getNestBridgeConfig();\n const endpoint = resolveGraphqlEndpoint(config);\n const headers = await resolveRequestHeaders(config, undefined, false);\n const client = new GraphQLClient(endpoint, { fetch: config.fetch, headers });\n\n try {\n return await client.request<T>(\n nestBridgeGraphqlRequest.document,\n nestBridgeGraphqlRequest.variables,\n );\n } catch (error) {\n if (error instanceof ClientError) {\n throw new NestBridgeGraphqlError(error, endpoint);\n }\n\n throw error;\n }\n};\n","export class NestBridgeError<T = unknown> extends Error {\n readonly status: number;\n readonly body: T;\n readonly response: Response;\n\n constructor(message: string, status: number, body: T, response: Response) {\n super(message);\n this.name = 'NestBridgeError';\n this.status = status;\n this.body = body;\n this.response = response;\n }\n}\n","const serializeQuery = (query: Record<string, unknown>) => {\n const searchParams = new URLSearchParams();\n\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n searchParams.append(key, String(item));\n }\n continue;\n }\n\n searchParams.append(key, String(value));\n }\n\n return searchParams.toString();\n};\n\nexport const buildRequestUrl = (\n baseURL: string | undefined,\n path: string,\n query: Record<string, unknown> | undefined,\n) => {\n const url = `${baseURL ?? ''}${path}`;\n\n if (query === undefined) {\n return url;\n }\n\n const queryString = serializeQuery(query);\n\n return queryString.length > 0 ? `${url}?${queryString}` : url;\n};\n","export const extractErrorMessage = (body: unknown): string | undefined => {\n if (typeof body === 'string') {\n return body.length > 0 ? body : undefined;\n }\n\n if (typeof body === 'object' && body !== null && 'message' in body) {\n const { message } = body as { message: unknown };\n\n if (typeof message === 'string') {\n return message;\n }\n\n if (Array.isArray(message)) {\n return message.join(', ');\n }\n }\n\n if (typeof body === 'object' && body !== null) {\n return JSON.stringify(body);\n }\n\n return undefined;\n};\n","export const parseResponseBody = async (response: Response): Promise<unknown> => {\n if (response.status === 204 || response.status === 205) {\n return undefined;\n }\n\n const text = await response.text();\n\n if (text.length === 0) {\n return undefined;\n }\n\n const contentType = response.headers.get('content-type') ?? '';\n\n if (!contentType.includes('application/json')) {\n return text;\n }\n\n return JSON.parse(text);\n};\n","import { getNestBridgeConfig } from '../config';\nimport { buildRequestUrl } from './build-request-url';\nimport { extractErrorMessage } from './extract-error-message';\nimport { NestBridgeError } from './nestbridge-error';\nimport type { NestBridgeRequest } from './nestbridge-request';\nimport { parseResponseBody } from './parse-response-body';\nimport { resolveRequestHeaders } from './resolve-request-headers';\n\nexport const request = async <T>(nestBridgeRequest: NestBridgeRequest) => {\n const config = getNestBridgeConfig();\n const fetchImplementation = config.fetch ?? globalThis.fetch;\n const hasBody = nestBridgeRequest.body !== undefined;\n const url = buildRequestUrl(config.baseURL, nestBridgeRequest.path, nestBridgeRequest.query);\n const headers = await resolveRequestHeaders(config, nestBridgeRequest.headers, hasBody);\n\n const response = await fetchImplementation(url, {\n method: nestBridgeRequest.method,\n headers,\n body: hasBody ? JSON.stringify(nestBridgeRequest.body) : undefined,\n });\n\n if (!response.ok) {\n const responseBody = await parseResponseBody(response);\n const backendMessage = extractErrorMessage(responseBody);\n const message = `NestBridge request to ${url} failed with status ${response.status}.${\n backendMessage === undefined ? '' : ` ${backendMessage}`\n }`;\n\n throw new NestBridgeError(message, response.status, responseBody, response);\n }\n\n if (nestBridgeRequest.responseType === 'blob') {\n return (await response.blob()) as T;\n }\n\n return (await parseResponseBody(response)) as T;\n};\n","import { version } from '../package.json';\n\nexport const VERSION: string = version;\n"],"names":[],"mappings":";;AAEA,IAAI,gBAAkC,EAAC;AAEhC,MAAM,mBAAA,GAAsB,CAAC,MAAA,KAA6B;AAC/D,EAAA,aAAA,GAAgB,MAAA;AAClB;AAEO,MAAM,sBAAsB,MAAM,aAAA;;ACNlC,MAAM,qBAAA,GAAwB,OACnC,MAAA,EACA,cAAA,EACA,OAAA,KACG;AACH,EAAA,MAAM,aAAA,GACJ,OAAO,MAAA,CAAO,OAAA,KAAY,UAAA,GAAa,MAAM,MAAA,CAAO,OAAA,EAAQ,GAAK,MAAA,CAAO,OAAA,IAAW,EAAC;AACtF,EAAA,MAAM,MAAA,GAAiC,EAAE,GAAG,aAAA,EAAc;AAE1D,EAAA,IAAI,OAAA,EAAS;AACX,IAAA,MAAA,CAAO,cAAc,CAAA,GAAI,kBAAA;AAAA,EAC3B;AAEA,EAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,cAAA,IAAkB,EAAE,CAAA,EAAG;AAC/D,IAAA,IAAI,UAAU,MAAA,EAAW;AACvB,MAAA,MAAA,CAAO,GAAG,CAAA,GAAI,KAAA;AAAA,IAChB;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT,CAAA;;ACpBO,MAAM,0BAAA,GAA6B,CACxC,QAAA,KACuB;AACvB,EAAA,IAAI,SAAS,MAAA,KAAW,MAAA,IAAa,QAAA,CAAS,MAAA,CAAO,SAAS,CAAA,EAAG;AAC/D,IAAA,OAAO,QAAA,CAAS,OAAO,GAAA,CAAI,CAAC,UAAU,KAAA,CAAM,OAAO,CAAA,CAAE,IAAA,CAAK,IAAI,CAAA;AAAA,EAChE;AAEA,EAAA,IAAI,OAAO,QAAA,CAAS,IAAA,KAAS,YAAY,QAAA,CA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AAkB,IAAA,EAAM,kBAAkB,KAAK,CAAA;AAC3F,EAAA,MAAM,UAAU,MAAM,qBAAA,CAAsB,MAAA,EAAQ,iBAAA,CAAkB,SAAS,OAAO,CAAA;AAEtF,EAAA,MAAM,QAAA,GAAW,MAAM,mBAAA,CAAoB,GAAA,EAAK;AAAA,IAC9C,QAAQ,iBAAA,CAAkB,MAAA;AAAA,IAC1B,OAAA;AAAA,IACA,MAAM,OAAA,GAAU,IAAA,CAAK,SAAA,CAAU,iBAAA,CAAkB,IAAI,CAAA,GAAI;AAAA,GAC1D,CAAA;AAED,EAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,IAAA,MAAM,YAAA,GAAe,MAAM,iBAAA,CAAkB,QAAQ,CAAA;AACrD,IAAA,MAAM,cAAA,GAAiB,oBAAoB,YAAY,CAAA;AACvD,IAAA,MAAM,OAAA,GAAU,CAAA,sBAAA,EAAyB,GAAG,CAAA,oBAAA,EAAuB,QAAA,CAAS,MAAM,CAAA,CAAA,EAChF,cAAA,KAAmB,MAAA,GAAY,EAAA,GAAK,CAAA,CAAA,EAAI,cAAc,CAAA,CACxD,CAAA,CAAA;AAEA,IAAA,MAAM,IAAI,eAAA,CAAgB,OAAA,EAAS,QAAA,CAAS,MAAA,EAAQ,cAAc,QAAQ,CAAA;AAAA,EAC5E;AAEA,EAAA,IAAI,iBAAA,CAAkB,iBAAiB,MAAA,EAAQ;AAC7C,IAAA,OAAQ,MAAM,SAAS,IAAA,EAAK;AAAA,EAC9B;AAEA,EAAA,OAAQ,MAAM,kBAAkB,QAAQ,CAAA;AAC1C;;;;AClCO,MAAM,OAAA,GAAkB;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestbridge/runtime",
3
- "version": "0.1.1",
3
+ "version": "1.1.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -31,5 +31,10 @@
31
31
  "vite": "^6.0.7",
32
32
  "vite-plugin-dts": "^4.4.0",
33
33
  "vitest": "^5.0.0"
34
+ },
35
+ "dependencies": {
36
+ "graphql": "^16",
37
+ "graphql-request": "^7.4.0",
38
+ "rxjs": "^7.8.2"
34
39
  }
35
40
  }