@hyper-fetch/core 6.0.1 → 7.0.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.
Files changed (83) hide show
  1. package/.eslintrc.json +8 -3
  2. package/README.md +5 -5
  3. package/dist/browser/index.js +3714 -0
  4. package/dist/browser/index.js.map +7 -0
  5. package/dist/index.d.ts +1669 -1091
  6. package/dist/index.js +3952 -0
  7. package/dist/index.js.map +7 -0
  8. package/package.json +16 -18
  9. package/src/adapter/adapter.bindings.ts +261 -165
  10. package/src/adapter/adapter.ts +480 -8
  11. package/src/adapter/adapter.types.ts +111 -139
  12. package/src/adapter/adapter.utils.ts +71 -25
  13. package/src/adapter/index.ts +1 -2
  14. package/src/cache/cache.events.ts +58 -14
  15. package/src/cache/cache.ts +158 -91
  16. package/src/cache/cache.types.ts +15 -25
  17. package/src/cache/cache.utils.ts +17 -10
  18. package/src/client/client.create.ts +17 -0
  19. package/src/client/client.ts +247 -266
  20. package/src/client/client.types.ts +43 -21
  21. package/src/client/client.utils.ts +7 -168
  22. package/src/client/index.ts +1 -0
  23. package/src/constants/http.constants.ts +6 -6
  24. package/src/constants/time.constants.ts +10 -10
  25. package/src/dispatcher/dispatcher.constants.ts +5 -5
  26. package/src/dispatcher/dispatcher.events.ts +85 -20
  27. package/src/dispatcher/dispatcher.ts +265 -199
  28. package/src/dispatcher/dispatcher.types.ts +6 -7
  29. package/src/dispatcher/dispatcher.utils.ts +26 -10
  30. package/src/http-adapter/http-adapter.browser.ts +101 -0
  31. package/src/http-adapter/http-adapter.constants.ts +8 -0
  32. package/src/http-adapter/http-adapter.server.ts +134 -0
  33. package/src/http-adapter/http-adapter.ts +11 -0
  34. package/src/http-adapter/http-adapter.types.ts +86 -0
  35. package/src/http-adapter/http-adapter.utils.ts +177 -0
  36. package/src/http-adapter/index.ts +4 -0
  37. package/src/index.ts +2 -1
  38. package/src/managers/app/app.manager.constants.ts +4 -4
  39. package/src/managers/app/app.manager.events.ts +12 -12
  40. package/src/managers/app/app.manager.ts +10 -7
  41. package/src/managers/app/app.manager.utils.ts +12 -2
  42. package/src/managers/logger/logger.manager.constants.ts +13 -18
  43. package/src/managers/logger/logger.manager.ts +37 -49
  44. package/src/managers/logger/logger.manager.types.ts +32 -21
  45. package/src/managers/logger/logger.manager.utils.ts +23 -17
  46. package/src/managers/request/request.manager.events.ts +222 -109
  47. package/src/managers/request/request.manager.ts +5 -2
  48. package/src/managers/request/request.manager.types.ts +35 -7
  49. package/src/managers/request/request.manager.utils.ts +29 -17
  50. package/src/mocker/mocker.ts +115 -81
  51. package/src/mocker/mocker.types.ts +29 -25
  52. package/src/plugin/index.ts +2 -0
  53. package/src/plugin/plugin.ts +159 -0
  54. package/src/plugin/plugin.types.ts +181 -0
  55. package/src/request/request.ts +366 -323
  56. package/src/request/request.types.ts +144 -148
  57. package/src/request/request.utils.ts +35 -32
  58. package/src/types/adapter.types.ts +63 -0
  59. package/src/types/client.types.ts +3 -3
  60. package/src/types/helpers.types.ts +16 -3
  61. package/src/types/hydration.types.ts +16 -0
  62. package/src/types/index.ts +3 -1
  63. package/src/types/request.types.ts +73 -0
  64. package/src/utils/emitter.utils.ts +52 -0
  65. package/src/utils/index.ts +1 -0
  66. package/src/utils/uuid.utils.ts +4 -2
  67. package/tsconfig.base.json +4 -5
  68. package/tsconfig.json +5 -4
  69. package/dist/browser/index.cjs.js +0 -2420
  70. package/dist/browser/index.cjs.js.map +0 -7
  71. package/dist/browser/index.esm.js +0 -2395
  72. package/dist/browser/index.esm.js.map +0 -7
  73. package/dist/index.cjs.js +0 -2579
  74. package/dist/index.cjs.js.map +0 -7
  75. package/dist/index.esm.js +0 -2474
  76. package/dist/index.esm.js.map +0 -7
  77. package/src/adapter/adapter.browser.ts +0 -100
  78. package/src/adapter/adapter.constants.ts +0 -8
  79. package/src/adapter/adapter.server.ts +0 -93
  80. package/src/effect/index.ts +0 -2
  81. package/src/effect/request.effect.ts +0 -31
  82. package/src/effect/request.effect.types.ts +0 -44
  83. package/src/types/fetch.types.ts +0 -50
@@ -1,24 +1,22 @@
1
- import { Dispatcher } from "dispatcher";
2
1
  import { RequestInstance } from "request";
3
2
 
4
3
  export type DispatcherOptionsType = {
5
4
  storage?: DispatcherStorageType;
6
- onInitialization?: (dispatcherInstance: Dispatcher) => void;
7
- onUpdateStorage?: <Request extends RequestInstance>(queueKey: string, data: QueueDataType<Request>) => void;
8
- onDeleteFromStorage?: <Request extends RequestInstance>(queueKey: string, data: QueueDataType<Request>) => void;
9
- onClearStorage?: (dispatcherInstance: Dispatcher) => void;
10
5
  };
11
6
 
12
7
  // Values
13
- export type QueueElementType<Request extends RequestInstance = RequestInstance> = {
8
+ export type QueueItemType<Request extends RequestInstance = RequestInstance> = {
14
9
  requestId: string;
15
10
  request: Request;
16
11
  retries: number;
17
12
  timestamp: number;
18
13
  stopped: boolean;
14
+ /** Resolved when we receive response */
15
+ resolved: boolean;
19
16
  };
20
17
  export type QueueDataType<Request extends RequestInstance = RequestInstance> = {
21
- requests: QueueElementType<Request>[];
18
+ queryKey: string;
19
+ requests: QueueItemType<Request>[];
22
20
  stopped: boolean;
23
21
  };
24
22
 
@@ -27,6 +25,7 @@ export type DispatcherStorageType = {
27
25
  set: <Request extends RequestInstance = RequestInstance>(key: string, data: QueueDataType<Request>) => void;
28
26
  get: <Request extends RequestInstance = RequestInstance>(key: string) => QueueDataType<Request> | undefined;
29
27
  keys: () => string[] | IterableIterator<string>;
28
+ entries: () => [string, QueueDataType] | IterableIterator<[string, QueueDataType<any>]>;
30
29
  delete: (key: string) => void;
31
30
  clear: () => void;
32
31
  };
@@ -1,15 +1,24 @@
1
1
  import { RequestInstance } from "request";
2
- import { DispatcherRequestType, QueueElementType } from "dispatcher";
2
+ import { DispatcherMode, QueueItemType } from "dispatcher";
3
3
 
4
4
  // Events
5
5
 
6
- export const getDispatcherDrainedEventKey = (key: string): string => {
6
+ export const getDispatcherDrainedKey = (): string => {
7
+ return `drained-event`;
8
+ };
9
+ export const getDispatcherDrainedByKey = (key: string): string => {
7
10
  return `${key}-drained-event`;
8
11
  };
9
- export const getDispatcherStatusEventKey = (key: string): string => {
12
+ export const getDispatcherStatusKey = (): string => {
13
+ return `status-event`;
14
+ };
15
+ export const getDispatcherStatusByKey = (key: string): string => {
10
16
  return `${key}-status-event`;
11
17
  };
12
- export const getDispatcherChangeEventKey = (key: string): string => {
18
+ export const getDispatcherChangeKey = (): string => {
19
+ return `change-event`;
20
+ };
21
+ export const getDispatcherChangeByKey = (key: string): string => {
13
22
  return `${key}-change-event`;
14
23
  };
15
24
 
@@ -29,18 +38,25 @@ export const canRetryRequest = (currentRetries: number, retry: number | undefine
29
38
  return false;
30
39
  };
31
40
 
32
- export const getRequestType = (request: RequestInstance, latestRequest: QueueElementType | undefined) => {
41
+ const isInDeduplicateRange = (request: RequestInstance, latestRequest: QueueItemType) => {
42
+ if (request.deduplicateTime) {
43
+ return +new Date() - latestRequest.timestamp <= request.deduplicateTime;
44
+ }
45
+ return true;
46
+ };
47
+
48
+ export const getRequestType = (request: RequestInstance, latestRequest: QueueItemType | undefined) => {
33
49
  const { queued, cancelable, deduplicate } = request;
34
- const canDeduplicate = latestRequest ? +new Date() - latestRequest.timestamp <= request.deduplicateTime : false;
50
+ const canDeduplicate = latestRequest ? isInDeduplicateRange(request, latestRequest) : false;
35
51
 
36
52
  if (queued) {
37
- return DispatcherRequestType.oneByOne;
53
+ return DispatcherMode.ONE_BY_ONE;
38
54
  }
39
55
  if (cancelable) {
40
- return DispatcherRequestType.previousCanceled;
56
+ return DispatcherMode.PREVIOUS_CANCELED;
41
57
  }
42
58
  if (canDeduplicate && deduplicate) {
43
- return DispatcherRequestType.deduplicated;
59
+ return DispatcherMode.DEDUPLICATED;
44
60
  }
45
- return DispatcherRequestType.allAtOnce;
61
+ return DispatcherMode.ALL_AT_ONCE;
46
62
  };
@@ -0,0 +1,101 @@
1
+ import { getResponseHeaders, parseErrorResponse, parseResponse, stringifyQueryParams } from "./http-adapter.utils";
2
+ import { defaultTimeout, xhrExtra } from "./http-adapter.constants";
3
+ import { Adapter } from "../adapter/adapter";
4
+ import { HttpMethods } from "constants/http.constants";
5
+ import { HttpMethodsType, HttpStatusType } from "types";
6
+ import { HttpAdapterOptionsType, HttpAdapterExtraType } from "./http-adapter.types";
7
+ import { QueryParamsType } from "adapter";
8
+
9
+ export const getAdapter = () =>
10
+ new Adapter<
11
+ HttpAdapterOptionsType,
12
+ HttpMethodsType,
13
+ HttpStatusType,
14
+ HttpAdapterExtraType,
15
+ QueryParamsType | string | null,
16
+ undefined,
17
+ string
18
+ >({
19
+ name: "http-browser",
20
+ defaultMethod: HttpMethods.GET,
21
+ defaultExtra: xhrExtra,
22
+ systemErrorStatus: 0 as number,
23
+ systemErrorExtra: xhrExtra,
24
+ })
25
+ .setQueryParamsMapper(stringifyQueryParams)
26
+ .setFetcher(
27
+ async ({
28
+ request,
29
+ adapterOptions,
30
+ headers,
31
+ payload,
32
+ onError,
33
+ onResponseEnd,
34
+ onTimeoutError,
35
+ onRequestEnd,
36
+ createAbortListener,
37
+ onResponseProgress,
38
+ onResponseStart,
39
+ onBeforeRequest,
40
+ onRequestStart,
41
+ onRequestProgress,
42
+ onSuccess,
43
+ }) => {
44
+ const { method, client, endpoint } = request;
45
+ const fullUrl = `${client.url}${endpoint}`;
46
+ const xhr = new XMLHttpRequest();
47
+ xhr.timeout = defaultTimeout;
48
+ const onAbort = () => xhr.abort();
49
+ // Inject xhr options
50
+ if (adapterOptions) {
51
+ Object.entries(adapterOptions).forEach(([name, value]) => {
52
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
53
+ // @ts-ignore
54
+ xhr[name] = value;
55
+ });
56
+ }
57
+ // Open connection
58
+ xhr.open(method, fullUrl, true);
59
+ // Set Headers
60
+ Object.entries(headers).forEach(([name, value]) => xhr.setRequestHeader(name, value as string));
61
+ // Listen to abort signal
62
+ const unmountListener = createAbortListener({ status: 0, extra: xhrExtra, onAbort });
63
+ // Request handlers
64
+ xhr.upload.onprogress = onRequestProgress;
65
+ // Response handlers
66
+ xhr.onloadstart = (): void => {
67
+ onRequestEnd();
68
+ onResponseStart();
69
+ };
70
+ xhr.onprogress = onResponseProgress;
71
+ xhr.onloadend = () => {
72
+ onResponseEnd();
73
+ unmountListener();
74
+ };
75
+
76
+ /* istanbul ignore next */
77
+ xhr.ontimeout = () => onTimeoutError({ status: 0, extra: xhrExtra });
78
+ // Data handler
79
+ xhr.onreadystatechange = (e: Event) => {
80
+ const event = e as unknown as ProgressEvent<XMLHttpRequest>;
81
+ const finishedState = 4;
82
+ if (event.target && event.target.readyState === finishedState) {
83
+ const { status } = event.target;
84
+ const success = String(status).startsWith("2") || String(status).startsWith("3");
85
+ const responseHeaders = getResponseHeaders(xhr.getAllResponseHeaders());
86
+ if (success) {
87
+ const data = parseResponse(event.target.response);
88
+ onSuccess({ data, status, extra: { headers: responseHeaders } });
89
+ } else {
90
+ // delay to finish after onabort/ontimeout
91
+ const error = parseErrorResponse(event.target.response);
92
+ onError({ error, status, extra: { headers: responseHeaders } });
93
+ }
94
+ }
95
+ };
96
+ // Start request
97
+ onBeforeRequest();
98
+ onRequestStart();
99
+ xhr.send(payload as XMLHttpRequestBodyInit);
100
+ },
101
+ );
@@ -0,0 +1,8 @@
1
+ import { Time } from "constants/time.constants";
2
+ import { HttpAdapterExtraType } from "./http-adapter.types";
3
+
4
+ export const defaultTimeout = Time.SEC * 5;
5
+
6
+ export const xhrExtra: HttpAdapterExtraType = {
7
+ headers: {},
8
+ };
@@ -0,0 +1,134 @@
1
+ import http, { OutgoingHttpHeaders } from "http";
2
+ import https from "https";
3
+
4
+ import { Adapter } from "../adapter/adapter";
5
+ import { HttpAdapterOptionsType, HttpAdapterExtraType } from "./http-adapter.types";
6
+ import { HttpMethods } from "constants/http.constants";
7
+ import { HttpMethodsType, HttpStatusType } from "types";
8
+ import { parseErrorResponse, parseResponse, stringifyQueryParams } from "./http-adapter.utils";
9
+ import { QueryParamsType } from "adapter";
10
+ import { defaultTimeout, xhrExtra } from "./http-adapter.constants";
11
+
12
+ export const getAdapter = () =>
13
+ new Adapter<
14
+ HttpAdapterOptionsType,
15
+ HttpMethodsType,
16
+ HttpStatusType,
17
+ HttpAdapterExtraType,
18
+ QueryParamsType | string | null,
19
+ undefined,
20
+ string
21
+ >({
22
+ name: "http-server",
23
+ defaultMethod: HttpMethods.GET,
24
+ defaultExtra: xhrExtra,
25
+ systemErrorStatus: 0 as number,
26
+ systemErrorExtra: xhrExtra,
27
+ })
28
+ .setQueryParamsMapper(stringifyQueryParams)
29
+ .setFetcher(
30
+ async ({
31
+ request,
32
+ adapterOptions,
33
+ adapter,
34
+ headers,
35
+ payload,
36
+ onError,
37
+ onResponseEnd,
38
+ onTimeoutError,
39
+ onRequestEnd,
40
+ createAbortListener,
41
+ getAbortController,
42
+ onResponseProgress,
43
+ onResponseStart,
44
+ onBeforeRequest,
45
+ onRequestStart,
46
+ onSuccess,
47
+ }) => {
48
+ const { method, client, endpoint } = request;
49
+ const { url } = client;
50
+ const httpClient = client.url.includes("https://") ? https : http;
51
+ const options = {
52
+ method,
53
+ headers: headers as OutgoingHttpHeaders,
54
+ timeout: defaultTimeout,
55
+ signal: getAbortController()?.signal,
56
+ } satisfies https.RequestOptions;
57
+
58
+ if (adapterOptions) {
59
+ Object.entries(adapterOptions).forEach(([name, value]) => {
60
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
61
+ // @ts-ignore
62
+ options[name] = value;
63
+ });
64
+ }
65
+
66
+ onBeforeRequest();
67
+
68
+ if (payload) {
69
+ options.headers["Content-Length"] = Buffer.byteLength(JSON.stringify(payload));
70
+ }
71
+
72
+ const fullUrl = `${url}${endpoint}`;
73
+
74
+ const unmountListener = createAbortListener({
75
+ status: 0,
76
+ extra: xhrExtra,
77
+ });
78
+
79
+ const httpRequest = httpClient.request(fullUrl, options, (response) => {
80
+ // TODO - Change to settable from options
81
+ response.setEncoding("utf8");
82
+ onRequestStart();
83
+
84
+ let chunks = "";
85
+ const totalDownloadBytes = Number(response.headers["content-length"]);
86
+ let downloadedBytes = 0;
87
+
88
+ response.on("data", (chunk) => {
89
+ /* istanbul ignore next */
90
+ if (!chunks) {
91
+ onRequestEnd();
92
+ onResponseStart();
93
+ }
94
+ downloadedBytes += chunk.length;
95
+ chunks += chunk;
96
+
97
+ onResponseProgress({ total: totalDownloadBytes, loaded: downloadedBytes });
98
+ });
99
+
100
+ response.on("end", async () => {
101
+ /* istanbul ignore next */
102
+ const { statusCode = adapter.systemErrorStatus } = response;
103
+ const success = String(statusCode).startsWith("2") || String(statusCode).startsWith("3");
104
+
105
+ if (success) {
106
+ const data = parseResponse(chunks);
107
+ onSuccess({
108
+ data,
109
+ status: statusCode,
110
+ extra: { headers: response.headers as Record<string, string> },
111
+ });
112
+ } else {
113
+ // delay to finish after onabort/ontimeout
114
+ const data = parseErrorResponse(chunks);
115
+ onError({
116
+ error: data,
117
+ status: statusCode,
118
+ extra: { headers: response.headers as Record<string, string> },
119
+ });
120
+ }
121
+
122
+ unmountListener();
123
+ onResponseEnd();
124
+ });
125
+ });
126
+
127
+ httpRequest.on("timeout", () => onTimeoutError({ status: 0, extra: xhrExtra }));
128
+ httpRequest.on("error", (error) => onError({ error, status: 0, extra: xhrExtra }));
129
+ if (payload) {
130
+ httpRequest.write(payload);
131
+ }
132
+ httpRequest.end();
133
+ },
134
+ );
@@ -0,0 +1,11 @@
1
+ import * as browser from "@browser-adapter";
2
+ import * as server from "@server-adapter";
3
+
4
+ import { HttpAdapterType } from "http-adapter/http-adapter.types";
5
+
6
+ export const HttpAdapter = (): HttpAdapterType => {
7
+ if (typeof XMLHttpRequest !== "undefined") {
8
+ return browser.getAdapter();
9
+ }
10
+ return server.getAdapter();
11
+ };
@@ -0,0 +1,86 @@
1
+ import { HttpMethodsType, HttpStatusType } from "../types";
2
+ import { DeclareAdapterType, QueryParamsType, QueryParamType } from "adapter";
3
+ import { stringifyQueryParams } from "./http-adapter.utils";
4
+ /**
5
+ * Base Adapter
6
+ */
7
+
8
+ export type HttpAdapterType = DeclareAdapterType<{
9
+ adapterOptions: HttpAdapterOptionsType;
10
+ methodType: HttpMethodsType;
11
+ statusType: HttpStatusType;
12
+ extra: HttpAdapterExtraType;
13
+ queryParams: QueryParamsType | string | null;
14
+ endpointType: string;
15
+ queryParamsMapperType: typeof stringifyQueryParams;
16
+ }>;
17
+
18
+ /**
19
+ * Options
20
+ */
21
+ export interface HttpAdapterRequest extends Omit<XMLHttpRequest, "responseType"> {
22
+ responseType: XMLHttpRequestResponseType | "stream";
23
+ }
24
+ export type HttpAdapterOptionsType = Partial<HttpAdapterRequest>;
25
+
26
+ export type HttpAdapterExtraType = {
27
+ headers: Record<string, string>;
28
+ };
29
+
30
+ // Headers
31
+
32
+ export type HttpAdapterHeadersProps = {
33
+ isFormData: boolean;
34
+ headers: HeadersInit | undefined;
35
+ };
36
+
37
+ // Stringify
38
+
39
+ export type QueryStringifyOptionsType = {
40
+ /**
41
+ * Strict URI encoding
42
+ */
43
+ strict?: boolean;
44
+ /**
45
+ * Encode keys and values
46
+ */
47
+ encode?: boolean;
48
+ /**
49
+ * Array encoding type
50
+ */
51
+ arrayFormat?: "bracket" | "index" | "comma" | "separator" | "bracket-separator" | "none";
52
+ /**
53
+ * Array format separator
54
+ */
55
+ arraySeparator?: string;
56
+ /**
57
+ * Skip keys with null values
58
+ */
59
+ skipNull?: boolean;
60
+ /**
61
+ * Skip keys with empty string
62
+ */
63
+ skipEmptyString?: boolean;
64
+
65
+ /**
66
+ * Parsing function for date type query param
67
+ */
68
+ dateParser?: (value: QueryParamType) => string;
69
+ /**
70
+ * Parsing function for object type query param
71
+ */
72
+ objectParser?: (value: QueryParamType) => string;
73
+ };
74
+
75
+ export type BufferEncoding =
76
+ | "ascii"
77
+ | "utf8"
78
+ | "utf-8"
79
+ | "utf16le"
80
+ | "ucs2"
81
+ | "ucs-2"
82
+ | "base64"
83
+ | "base64url"
84
+ | "latin1"
85
+ | "binary"
86
+ | "hex";
@@ -0,0 +1,177 @@
1
+ import { getErrorMessage, QueryParamsType, QueryParamType, QueryParamValuesType } from "adapter";
2
+ import { RequestInstance } from "request";
3
+ import { ExtractErrorType, EmptyTypes } from "types";
4
+ import { HttpAdapterRequest, BufferEncoding, QueryStringifyOptionsType } from "./http-adapter.types";
5
+ import { stringifyDefaultOptions } from "client";
6
+
7
+ // Utils
8
+
9
+ export const getResponseHeaders = (headersString: string): Record<string, string> => {
10
+ const arr = headersString.trim().split(/[\r\n]+/);
11
+
12
+ const headers: Record<string, string> = {};
13
+ arr.forEach((line) => {
14
+ const parts = line.split(": ");
15
+ const header = parts.shift();
16
+ const value = parts.join(": ");
17
+ if (header) {
18
+ headers[header] = value;
19
+ }
20
+ });
21
+
22
+ return headers;
23
+ };
24
+
25
+ // Responses
26
+
27
+ export const parseResponse = (response: string | unknown) => {
28
+ try {
29
+ return JSON.parse(response as string);
30
+ } catch (err) {
31
+ return response;
32
+ }
33
+ };
34
+
35
+ export const handleResponse = (
36
+ responseChunks: any[],
37
+ responseType: HttpAdapterRequest["responseType"],
38
+ responseEncoding: BufferEncoding,
39
+ ) => {
40
+ const bufferedResponse = Buffer.concat(responseChunks);
41
+ switch (responseType) {
42
+ case "arraybuffer":
43
+ return bufferedResponse;
44
+ case "json":
45
+ return parseResponse(bufferedResponse.toString(responseEncoding));
46
+ default:
47
+ return bufferedResponse.toString(responseEncoding);
48
+ }
49
+ };
50
+
51
+ export const parseErrorResponse = <T extends RequestInstance>(response: unknown): ExtractErrorType<T> => {
52
+ return response ? parseResponse(response) : getErrorMessage();
53
+ };
54
+
55
+ // Stringify
56
+
57
+ const isValidValue = (options: QueryStringifyOptionsType) => {
58
+ return (value: QueryParamType) => {
59
+ const { skipNull, skipEmptyString } = options;
60
+
61
+ if (skipEmptyString && value === undefined) {
62
+ return false;
63
+ }
64
+ if (skipEmptyString && value === "") {
65
+ return false;
66
+ }
67
+ if (skipNull && value === null) {
68
+ return false;
69
+ }
70
+ return true;
71
+ };
72
+ };
73
+
74
+ const encodeValue = (
75
+ value: string,
76
+ { encode, strict }: Pick<QueryStringifyOptionsType, "encode" | "strict">,
77
+ ): string => {
78
+ if (encode && strict) {
79
+ return encodeURIComponent(value).replace(/[!'()*]/g, (s) => `%${s.charCodeAt(0).toString(16).toUpperCase()}`);
80
+ }
81
+ if (encode) {
82
+ return encodeURIComponent(value);
83
+ }
84
+ return value;
85
+ };
86
+
87
+ const encodeParams = (key: string, value: QueryParamType, options: QueryStringifyOptionsType) => {
88
+ const shouldSkip = !isValidValue(options)(value);
89
+
90
+ if (!key || shouldSkip) {
91
+ return "";
92
+ }
93
+
94
+ const parsedValue = () => {
95
+ if (value instanceof Date) {
96
+ return options.dateParser?.(value) || value.toISOString();
97
+ }
98
+
99
+ if (typeof value === "object" && !Array.isArray(value)) {
100
+ return options.objectParser?.(value) || JSON.stringify(value);
101
+ }
102
+
103
+ return String(value);
104
+ };
105
+
106
+ return `${encodeValue(key, options)}=${encodeValue(parsedValue(), options)}`;
107
+ };
108
+
109
+ const encodeArray = (key: string, array: Array<QueryParamValuesType>, options: QueryStringifyOptionsType): string => {
110
+ const { arrayFormat, arraySeparator } = options;
111
+
112
+ return array
113
+ .filter(isValidValue(options))
114
+ .reduce<string[]>((acc, value, index) => {
115
+ switch (arrayFormat) {
116
+ case "index": {
117
+ const keyValue = `${encodeValue(key, options)}[${encodeValue(String(index), options)}]=`;
118
+ acc.push(`${keyValue}${encodeValue(String(value), options)}`);
119
+ break;
120
+ }
121
+ case "bracket": {
122
+ const keyValue = `${encodeValue(key, options)}[]=`;
123
+ acc.push(`${keyValue}${encodeValue(String(value), options)}`);
124
+ break;
125
+ }
126
+ case "comma": {
127
+ const keyValue = (!acc.length && `${encodeValue(key, options)}=`) || "";
128
+ return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(",")];
129
+ }
130
+ case "separator": {
131
+ const keyValue = (!acc.length && `${encodeValue(key, options)}=`) || "";
132
+ return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(arraySeparator || "|")];
133
+ }
134
+ case "bracket-separator": {
135
+ const keyValue = (!acc.length && `${encodeValue(key, options)}[]=`) || "";
136
+ return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(arraySeparator || "|")];
137
+ }
138
+ default: {
139
+ const keyValue = `${encodeValue(key, options)}=`;
140
+ acc.push(`${keyValue}${encodeValue(String(value), options)}`);
141
+ }
142
+ }
143
+
144
+ return acc;
145
+ }, [])
146
+ .join("&");
147
+ };
148
+
149
+ export const stringifyQueryParams = (
150
+ queryParams: QueryParamsType | string | EmptyTypes,
151
+ options: QueryStringifyOptionsType = stringifyDefaultOptions,
152
+ ): string => {
153
+ if (!queryParams || !Object.keys(queryParams).length) {
154
+ return "";
155
+ }
156
+
157
+ if (typeof queryParams === "string") {
158
+ const hasQuestionMark = queryParams[0] === "?";
159
+ return hasQuestionMark ? queryParams : `?${queryParams}`;
160
+ }
161
+
162
+ const stringified = Object.entries(queryParams)
163
+ .map(([key, value]): string => {
164
+ if (Array.isArray(value)) {
165
+ return encodeArray(key, value, options);
166
+ }
167
+
168
+ return encodeParams(key, value, options);
169
+ })
170
+ .filter(Boolean)
171
+ .join("&");
172
+
173
+ if (stringified) {
174
+ return `?${stringified}`;
175
+ }
176
+ return "";
177
+ };
@@ -0,0 +1,4 @@
1
+ export * from "./http-adapter";
2
+ export * from "./http-adapter.types";
3
+ export * from "./http-adapter.utils";
4
+ export * from "./http-adapter.constants";
package/src/index.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  // rollup client entry point
2
2
 
3
- export * from "./effect";
3
+ export * from "./plugin";
4
4
  export * from "./client";
5
5
  export * from "./cache";
6
6
  export * from "./adapter";
7
+ export * from "./http-adapter";
7
8
  export * from "./request";
8
9
  export * from "./constants/time.constants";
9
10
  export * from "./constants/http.constants";
@@ -3,10 +3,10 @@ import { AppManagerOptionsType } from "managers";
3
3
  import { onWindowEvent, onDocumentEvent } from "./app.manager.utils";
4
4
 
5
5
  export enum AppEvents {
6
- focus = "focus",
7
- blur = "blur",
8
- online = "online",
9
- offline = "offline",
6
+ FOCUS = "focus",
7
+ BLUR = "blur",
8
+ ONLINE = "online",
9
+ OFFLINE = "offline",
10
10
  }
11
11
 
12
12
  export const appManagerInitialOptions: RequiredKeys<AppManagerOptionsType> = {