@unshared/client 0.3.0 → 0.3.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 (45) hide show
  1. package/dist/chunks/0ZzUT3m_.js +46 -0
  2. package/dist/chunks/0ZzUT3m_.js.map +1 -0
  3. package/dist/chunks/{D51s1VII.js → BUeqbyph.js} +3 -45
  4. package/dist/chunks/BUeqbyph.js.map +1 -0
  5. package/dist/chunks/{B92aAMq0.d.ts → CO11DuYE.d.ts} +1 -1
  6. package/dist/chunks/CYmaYL5B.cjs +45 -0
  7. package/dist/chunks/CYmaYL5B.cjs.map +1 -0
  8. package/dist/chunks/{CfKxYeRr.cjs → Cayg8606.cjs} +4 -47
  9. package/dist/chunks/Cayg8606.cjs.map +1 -0
  10. package/dist/chunks/{lMH6B5BV.js → DJJsADWD.js} +2 -2
  11. package/dist/chunks/{lMH6B5BV.js.map → DJJsADWD.js.map} +1 -1
  12. package/dist/chunks/{CjU0376e.d.ts → DOZHjge0.d.ts} +12 -17
  13. package/dist/chunks/Du56lBvc.js +75 -0
  14. package/dist/chunks/Du56lBvc.js.map +1 -0
  15. package/dist/chunks/{iA98-4f5.cjs → Du_W5H6e.cjs} +2 -2
  16. package/dist/chunks/{iA98-4f5.cjs.map → Du_W5H6e.cjs.map} +1 -1
  17. package/dist/chunks/VkINJoq7.cjs +74 -0
  18. package/dist/chunks/VkINJoq7.cjs.map +1 -0
  19. package/dist/createClient.cjs +16 -15
  20. package/dist/createClient.cjs.map +1 -1
  21. package/dist/createClient.d.ts +43 -27
  22. package/dist/createClient.js +18 -16
  23. package/dist/createClient.js.map +1 -1
  24. package/dist/createService.cjs +2 -1
  25. package/dist/createService.cjs.map +1 -1
  26. package/dist/createService.d.ts +2 -2
  27. package/dist/createService.js +2 -1
  28. package/dist/createService.js.map +1 -1
  29. package/dist/index.cjs +6 -22
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.ts +4 -6
  32. package/dist/index.js +6 -25
  33. package/dist/openapi.d.ts +2 -2
  34. package/dist/utils.cjs +4 -4
  35. package/dist/utils.d.ts +2 -2
  36. package/dist/utils.js +7 -6
  37. package/dist/utils.js.map +1 -1
  38. package/dist/websocket.cjs +7 -0
  39. package/dist/websocket.cjs.map +1 -0
  40. package/dist/websocket.d.ts +148 -0
  41. package/dist/websocket.js +8 -0
  42. package/dist/websocket.js.map +1 -0
  43. package/package.json +9 -4
  44. package/dist/chunks/CfKxYeRr.cjs.map +0 -1
  45. package/dist/chunks/D51s1VII.js.map +0 -1
package/dist/index.d.ts CHANGED
@@ -1,13 +1,11 @@
1
- export { Client, ClientRoutes, createClient } from './createClient.js';
1
+ export { Client, createClient } from './createClient.js';
2
2
  export { Service, ServiceOptions, createService } from './createService.js';
3
3
  export { HttpHeader } from './HttpHeaders.js';
4
4
  export { HttpMethod } from './HttpMethods.js';
5
5
  export { HttpStatusCode } from './HttpStatusCodes.js';
6
- export { k as OpenAPIRoutes, O as OpenAPIV2, a as OpenAPIV3, c as Operation, d as OperationById, j as OperationByRoute, b as OperationId, e as OperationOptions, h as OperationResponse, f as OperationResult, i as OperationRoute, S as ServerUrl, g as getServerUrl, r as resolveOperation } from './chunks/CjU0376e.js';
7
- export { OpenAPIReference, OpenAPIReferenceDecoded, OpenAPIReferencePath, OpenAPIReferenceResolved, OpenAPIResolved, isReferenceObject, resolveDocument, resolveReference } from './openapi.js';
8
- export { FormDataLike, fetch, handleResponse, handleResponseStreamJson, isFormDataLike, isObjectLike, parseRequestBody, parseRequestHeaders, parseRequestParameters, parseRequestQuery, parseRequestUrl, toFormData } from './utils.js';
9
- export { a as FetchHeaders, F as FetchMethod, b as FetchOptions, R as RequestContext, c as RequestOptions, d as SearchArrayFormat, S as SearchParamsObject, T as ToSearchParamsOptions, p as parseRequest, r as request, t as toSearchParams } from './chunks/B92aAMq0.js';
10
6
  import '@unshared/functions/attempt';
7
+ import './chunks/DOZHjge0.js';
11
8
  import '@unshared/types';
9
+ import './chunks/CO11DuYE.js';
12
10
  import 'openapi-types';
13
- import '@unshared/functions/awaitable';
11
+ import './websocket.js';
package/dist/index.js CHANGED
@@ -3,38 +3,19 @@ import { createService } from "./createService.js";
3
3
  import { HttpHeader } from "./HttpHeaders.js";
4
4
  import { HttpMethod } from "./HttpMethods.js";
5
5
  import { HttpStatusCode } from "./HttpStatusCodes.js";
6
- import { isReferenceObject, resolveDocument, resolveReference } from "./openapi.js";
7
- import "./utils.js";
8
- import { g, r } from "./chunks/Biic1J5b.js";
9
- import { f, h, a, i, b, p, c, d, e, g as g2, j, t, k } from "./chunks/D51s1VII.js";
10
- import { r as r2 } from "./chunks/lMH6B5BV.js";
11
6
  import "@unshared/functions/attempt";
7
+ import "./chunks/BUeqbyph.js";
8
+ import "./chunks/0ZzUT3m_.js";
12
9
  import "@unshared/functions/awaitable";
10
+ import "./chunks/DJJsADWD.js";
11
+ import "./chunks/Du56lBvc.js";
12
+ import "./chunks/Biic1J5b.js";
13
13
  export {
14
14
  Client,
15
15
  HttpHeader,
16
16
  HttpMethod,
17
17
  HttpStatusCode,
18
18
  createClient,
19
- createService,
20
- f as fetch,
21
- g as getServerUrl,
22
- h as handleResponse,
23
- a as handleResponseStreamJson,
24
- i as isFormDataLike,
25
- b as isObjectLike,
26
- isReferenceObject,
27
- p as parseRequest,
28
- c as parseRequestBody,
29
- d as parseRequestHeaders,
30
- e as parseRequestParameters,
31
- g2 as parseRequestQuery,
32
- j as parseRequestUrl,
33
- r2 as request,
34
- resolveDocument,
35
- r as resolveOperation,
36
- resolveReference,
37
- t as toFormData,
38
- k as toSearchParams
19
+ createService
39
20
  };
40
21
  //# sourceMappingURL=index.js.map
package/dist/openapi.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- export { k as OpenAPIRoutes, O as OpenAPIV2, a as OpenAPIV3, c as Operation, d as OperationById, j as OperationByRoute, b as OperationId, e as OperationOptions, h as OperationResponse, f as OperationResult, i as OperationRoute, S as ServerUrl, g as getServerUrl, r as resolveOperation } from './chunks/CjU0376e.js';
1
+ export { O as OpenAPILike, a as OpenAPIOptionsMap, h as OpenAPIV2, j as OpenAPIV2Like, f as OpenAPIV3, k as OpenAPIV3Like, i as Operation, c as OperationById, n as OperationByRoute, b as OperationId, d as OperationOptions, l as OperationResponse, e as OperationResult, m as OperationRoute, S as ServerUrl, g as getServerUrl, r as resolveOperation } from './chunks/DOZHjge0.js';
2
2
  import { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';
3
3
  import { StringReplace, WriteableDeep, StringJoin, Substract } from '@unshared/types';
4
- import './chunks/B92aAMq0.js';
4
+ import './chunks/CO11DuYE.js';
5
5
  import './HttpHeaders.js';
6
6
  import './HttpMethods.js';
7
7
 
package/dist/utils.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- var handleResponse = require("./chunks/CfKxYeRr.cjs"), request = require("./chunks/iA98-4f5.cjs");
2
+ var handleResponse = require("./chunks/Cayg8606.cjs"), parseRequestQuery = require("./chunks/CYmaYL5B.cjs"), request = require("./chunks/Du_W5H6e.cjs");
3
3
  require("@unshared/functions/awaitable");
4
4
  exports.fetch = handleResponse.fetch;
5
5
  exports.handleResponse = handleResponse.handleResponse;
@@ -9,10 +9,10 @@ exports.isObjectLike = handleResponse.isObjectLike;
9
9
  exports.parseRequest = handleResponse.parseRequest;
10
10
  exports.parseRequestBody = handleResponse.parseRequestBody;
11
11
  exports.parseRequestHeaders = handleResponse.parseRequestHeaders;
12
- exports.parseRequestParameters = handleResponse.parseRequestParameters;
13
- exports.parseRequestQuery = handleResponse.parseRequestQuery;
14
12
  exports.parseRequestUrl = handleResponse.parseRequestUrl;
15
13
  exports.toFormData = handleResponse.toFormData;
16
- exports.toSearchParams = handleResponse.toSearchParams;
14
+ exports.parseRequestParameters = parseRequestQuery.parseRequestParameters;
15
+ exports.parseRequestQuery = parseRequestQuery.parseRequestQuery;
16
+ exports.toSearchParams = parseRequestQuery.toSearchParams;
17
17
  exports.request = request.request;
18
18
  //# sourceMappingURL=utils.cjs.map
package/dist/utils.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { b as FetchOptions, c as RequestOptions, R as RequestContext } from './chunks/B92aAMq0.js';
2
- export { a as FetchHeaders, F as FetchMethod, d as SearchArrayFormat, S as SearchParamsObject, T as ToSearchParamsOptions, p as parseRequest, r as request, t as toSearchParams } from './chunks/B92aAMq0.js';
1
+ import { a as FetchOptions, R as RequestOptions, b as RequestContext } from './chunks/CO11DuYE.js';
2
+ export { c as FetchHeaders, F as FetchMethod, d as SearchArrayFormat, S as SearchParamsObject, T as ToSearchParamsOptions, p as parseRequest, r as request, t as toSearchParams } from './chunks/CO11DuYE.js';
3
3
  import { Awaitable } from '@unshared/functions/awaitable';
4
4
  import { ObjectLike } from '@unshared/types';
5
5
  import './HttpHeaders.js';
package/dist/utils.js CHANGED
@@ -1,5 +1,6 @@
1
- import { f, h, a, i, b, p, c, d, e, g, j, t, k } from "./chunks/D51s1VII.js";
2
- import { r } from "./chunks/lMH6B5BV.js";
1
+ import { f, h, a, i, b, p, c, d, e, t } from "./chunks/BUeqbyph.js";
2
+ import { p as p2, a as a2, t as t2 } from "./chunks/0ZzUT3m_.js";
3
+ import { r } from "./chunks/DJJsADWD.js";
3
4
  import "@unshared/functions/awaitable";
4
5
  export {
5
6
  f as fetch,
@@ -10,11 +11,11 @@ export {
10
11
  p as parseRequest,
11
12
  c as parseRequestBody,
12
13
  d as parseRequestHeaders,
13
- e as parseRequestParameters,
14
- g as parseRequestQuery,
15
- j as parseRequestUrl,
14
+ p2 as parseRequestParameters,
15
+ a2 as parseRequestQuery,
16
+ e as parseRequestUrl,
16
17
  r as request,
17
18
  t as toFormData,
18
- k as toSearchParams
19
+ t2 as toSearchParams
19
20
  };
20
21
  //# sourceMappingURL=utils.js.map
package/dist/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;"}
1
+ {"version":3,"file":"utils.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;"}
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ var connect = require("./chunks/VkINJoq7.cjs");
3
+ require("./chunks/CYmaYL5B.cjs");
4
+ exports.WebSocketChannel = connect.WebSocketChannel;
5
+ exports.connect = connect.connect;
6
+ exports.parseConnectOptions = connect.parseConnectOptions;
7
+ //# sourceMappingURL=websocket.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;"}
@@ -0,0 +1,148 @@
1
+ import { ObjectLike, Loose, UnionMerge } from '@unshared/types';
2
+
3
+ /** The protocols to use for the connection. */
4
+ type ConnectProtocol = 'WS' | 'WSS';
5
+ /** Options to pass to the `createChannel` function. */
6
+ interface ConnectOptions<BaseUrl extends string = string, Query extends ObjectLike = ObjectLike, Parameters extends ObjectLike = ObjectLike, ClientData extends ObjectLike = ObjectLike, ServerData extends ObjectLike = ObjectLike> {
7
+ /** The protocol to use when connecting to the server. */
8
+ protocol?: Lowercase<ConnectProtocol> | Uppercase<ConnectProtocol>;
9
+ /** The base URL to connect to. */
10
+ baseUrl?: BaseUrl;
11
+ /**
12
+ * The path parameters to use when connecting to the server. These parameters will be used to
13
+ * fill in the path parameters of the connection URL.
14
+ *
15
+ * @example { id: 1 }
16
+ */
17
+ parameters?: Parameters;
18
+ /**
19
+ * The query parameters to use when connecting to the server. These parameters will be used to
20
+ * fill in the query parameters of the connection URL.
21
+ *
22
+ * @example { limit: 10, offset: 0 }
23
+ */
24
+ query?: Loose<Query>;
25
+ /**
26
+ * The data to send when creating the connection. Namely, the path parameters
27
+ * to use when connecting to the server.
28
+ *
29
+ * @example
30
+ *
31
+ * // Create a new connection to `http://localhost:8080/users/1`.
32
+ * connect('GET /users/:id', {
33
+ * data: { id: 1 },
34
+ * baseUrl: 'http://localhost:8080'
35
+ * })
36
+ */
37
+ data?: UnionMerge<Loose<Query> | Parameters>;
38
+ /**
39
+ * The payload to send when creating the connection. Namely, the initial message
40
+ * to send to the server when the connection is established.
41
+ */
42
+ initialPayload?: Loose<ClientData>;
43
+ /**
44
+ * Automatically open the connection when it is created. If `true`, the connection
45
+ * will automatically open when it is created. If `false`, the connection will not
46
+ * open when it is created.
47
+ *
48
+ * @default false
49
+ */
50
+ autoOpen?: boolean;
51
+ /**
52
+ * Weather to reconnect the connection when it is closed unexpectedly. If `true`,
53
+ * the connection will automatically reconnect when it is closed. If `false`, the
54
+ * connection will not reconnect when it is closed.
55
+ *
56
+ * @default false
57
+ */
58
+ autoReconnect?: boolean;
59
+ /**
60
+ * The delay in milliseconds to wait before reconnecting the connection. This delay
61
+ * will be used to wait before reconnecting the connection after it is closed.
62
+ *
63
+ * @default 0
64
+ */
65
+ reconnectDelay?: number;
66
+ /**
67
+ * The maximum number of times to reconnect the connection before giving up. This
68
+ * number will be used to determine when to stop trying to reconnect the connection.
69
+ *
70
+ * @default 3
71
+ */
72
+ reconnectLimit?: number;
73
+ /**
74
+ * The function to call when the connection is opened. This function will be called
75
+ * when the connection is successfully opened or reconnected.
76
+ */
77
+ onOpen?: (event: Event) => void;
78
+ /**
79
+ * The function to call when the connection is closed with an error. This function will
80
+ * be called when the connection is closed unexpectedly with an error.
81
+ */
82
+ onError?: (event: Event) => void;
83
+ /**
84
+ * The function to call when the connection is closed. This function will be called
85
+ * when the connection is closed unexpectedly or when the connection is closed manually.
86
+ */
87
+ onClose?: (event: CloseEvent) => void;
88
+ /**
89
+ * The function to call when a message is received from the server. This function will
90
+ * be called when a message is received from the server.
91
+ */
92
+ onMessage?: (data: ServerData) => void;
93
+ }
94
+ interface WebSocketParameters {
95
+ url: URL;
96
+ protocol?: 'ws' | 'wss';
97
+ }
98
+ declare function parseConnectOptions(channel: string, options: ConnectOptions): WebSocketParameters;
99
+
100
+ type RemoveListener = () => void;
101
+ type ClientData<T extends ConnectOptions> = T extends ConnectOptions<any, any, any, infer R extends ObjectLike, any> ? R : ObjectLike;
102
+ type ServerData<T extends ConnectOptions> = T extends ConnectOptions<any, any, any, any, infer R extends ObjectLike> ? R : ObjectLike;
103
+ declare class WebSocketChannel<T extends ConnectOptions = ConnectOptions> {
104
+ channel: string;
105
+ options: T;
106
+ constructor(channel: string, options: T);
107
+ /** The WebSocket connection to the server. */
108
+ webSocket: WebSocket | undefined;
109
+ /**
110
+ * Open a new WebSocket connection to the server. The connection will be opened with the given
111
+ * URL and protocols. If the connection is already open, the connection will be closed before
112
+ * opening a new connection. Also add the event listeners that were passed in the options.
113
+ */
114
+ open(): Promise<void>;
115
+ /**
116
+ * Send a payload to the server. The payload will be serialized to JSON before sending.
117
+ *
118
+ * @param payload The data to send to the server.
119
+ */
120
+ send(payload: ClientData<T>): void;
121
+ /**
122
+ * Listen for events from the server. The event will be deserialized from JSON before calling the callback.
123
+ *
124
+ * @param event The event to listen for.
125
+ * @param callback The callback to call when the event is received.
126
+ * @returns A function to remove the event listener.
127
+ */
128
+ on(event: 'message', callback: (data: ServerData<T>) => void): RemoveListener;
129
+ on(event: 'close', callback: (event: CloseEvent) => void): RemoveListener;
130
+ on(event: 'error', callback: (event: Event) => void): RemoveListener;
131
+ on(event: 'open', callback: (event: Event) => void): RemoveListener;
132
+ /**
133
+ * Close the WebSocket connection to the server. The connection will not be able to send or receive
134
+ * messages after it is closed.
135
+ */
136
+ close(): Promise<void>;
137
+ }
138
+ /**
139
+ * Create a new WebSocket connection to the server with the given path. The connection will
140
+ * automatically reconnect if the connection is closed unexpectedly.
141
+ *
142
+ * @param route The name of the route to connect to.
143
+ * @param options The options to pass to the connection.
144
+ * @returns The WebSocket connection.
145
+ */
146
+ declare function connect(route: string, options: ConnectOptions): WebSocketChannel;
147
+
148
+ export { type ConnectOptions, type ConnectProtocol, WebSocketChannel, type WebSocketParameters, connect, parseConnectOptions };
@@ -0,0 +1,8 @@
1
+ import { W, c, p } from "./chunks/Du56lBvc.js";
2
+ import "./chunks/0ZzUT3m_.js";
3
+ export {
4
+ W as WebSocketChannel,
5
+ c as connect,
6
+ p as parseConnectOptions
7
+ };
8
+ //# sourceMappingURL=websocket.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unshared/client",
3
3
  "type": "module",
4
- "version": "0.3.0",
4
+ "version": "0.3.1",
5
5
  "license": "MIT",
6
6
  "sideEffects": false,
7
7
  "author": "Stanley Horwood <stanley@hsjm.io>",
@@ -51,6 +51,11 @@
51
51
  "types": "./dist/utils.d.ts",
52
52
  "import": "./dist/utils.js"
53
53
  },
54
+ "./websocket": {
55
+ "require": "./dist/websocket.cjs",
56
+ "types": "./dist/websocket.d.ts",
57
+ "import": "./dist/websocket.js"
58
+ },
54
59
  ".": {
55
60
  "require": "./dist/index.cjs",
56
61
  "types": "./dist/index.d.ts",
@@ -63,12 +68,12 @@
63
68
  "LICENSE.md"
64
69
  ],
65
70
  "dependencies": {
66
- "@unshared/functions": "0.3.0",
67
- "@unshared/types": "0.3.0",
71
+ "@unshared/functions": "0.3.1",
72
+ "@unshared/types": "0.3.1",
68
73
  "openapi-types": "12.1.3"
69
74
  },
70
75
  "devDependencies": {
71
- "@unshared/scripts": "0.3.0"
76
+ "@unshared/scripts": "0.3.1"
72
77
  },
73
78
  "scripts": {
74
79
  "build:httpMethods": "tsx ./scripts/buildHttpMethods.ts",
@@ -1 +0,0 @@
1
- {"version":3,"file":"CfKxYeRr.cjs","sources":["../../utils/isObjectLike.ts","../../utils/isFormDataLike.ts","../../utils/toFormData.ts","../../utils/parseRequestBody.ts","../../utils/parseRequestHeaders.ts","../../utils/parseRequestParameters.ts","../../utils/toSearchParams.ts","../../utils/parseRequestQuery.ts","../../utils/parseRequestUrl.ts","../../utils/parseRequest.ts","../../utils/fetch.ts","../../utils/handleResponseStreamJson.ts","../../utils/handleResponse.ts"],"sourcesContent":["import type { ObjectLike } from '@unshared/types'\n\n/**\n * Predicate to check if a value is an object-like value.\n *\n * @param value The value to check.\n * @returns `true` if the value is an object-like value, `false` otherwise.\n * @example isObjectLike({}) // true\n */\nexport function isObjectLike(value: unknown): value is ObjectLike {\n return typeof value === 'object' && value !== null && value.constructor === Object\n}\n","/**\n * A type that represents a FormData-like object, which is a plain object with\n * nested Blob, File, or FileList values. Or a FormData instance.\n */\nexport type FormDataLike = FormData | Record<string, Blob | File | FileList>\n\n/**\n * Predicate to check if a value is FormData-like, meaning it is a plain object\n * with nested Blob, File, or FileList values.\n *\n * @param value The value to check.\n * @returns `true` if the value is FormData-like, `false` otherwise.\n * @example isFormDataLike({ file: new File(['test'], 'test.txt') }) // true\n */\nexport function isFormDataLike(value: unknown): value is FormDataLike {\n if (typeof value !== 'object' || value === null) return false\n if (value instanceof FormData) return true\n const values = Object.values(value)\n if (values.length === 0) return false\n return values.every((x) => {\n if (x instanceof File) return true\n if (Array.isArray(x)) return x.every(item => item instanceof File)\n return x instanceof Blob\n })\n}\n","import type { FormDataLike } from './isFormDataLike'\n\n/**\n * Casts an object that may contain `Blob`, `File`, or `FileList` values to a `FormData` object.\n *\n * @param object The object to cast to a `FormData` object.\n * @returns The `FormData` object.\n */\nexport function toFormData(object: FormDataLike): FormData {\n if (object instanceof FormData) return object\n const formData = new FormData()\n for (const key in object) {\n const value = object[key]\n if (value === undefined) continue\n if (Array.isArray(value)) {\n for (const item of value)\n formData.append(key, item as Blob | string)\n }\n else {\n formData.append(key, value as Blob | string)\n }\n }\n return formData\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { isFormDataLike } from './isFormDataLike'\nimport { isObjectLike } from './isObjectLike'\nimport { toFormData } from './toFormData'\n\n/**\n * Parse the request body based on the provided data and options.\n *\n * @param context The request context.\n * @param options The request options.\n */\nexport function parseRequestBody(context: RequestContext, options: FetchOptions): void {\n const { body } = options\n\n // --- If the method is `GET`, `HEAD`, or `DELETE`, return early.\n if (!context.init?.method) return\n if (['get', 'head', 'delete'].includes(context.init.method ?? 'get')) return\n\n // --- If no data is provided, return early.\n if (body === null || body === undefined) return\n\n // --- If data contains a `File` object, create a FormData object.\n if (isFormDataLike(body)) {\n context.init.body = toFormData(body)\n context.init.headers = context.init.headers ?? {}\n context.init.headers = { ...context.init.headers, 'Content-Type': 'multipart/form-data' }\n }\n\n // --- If the data is a `ReadableStream`, pass it directly to the body.\n else if (body instanceof ReadableStream) {\n context.init.body = body\n context.init.headers = context.init.headers ?? {}\n context.init.headers = { ...context.init.headers, 'Content-Type': 'application/octet-stream' }\n }\n\n // --- If the data is a Blob, pass it directly to the body.\n else if (body instanceof File) {\n context.init.body = body.stream()\n context.init.headers = context.init.headers ?? {}\n context.init.headers = { ...context.init.headers, 'Content-Type': 'application/octet-stream' }\n }\n\n // --- Otherwise, stringify the data and set the content type to JSON.\n else if (isObjectLike(body)) {\n context.init.body = JSON.stringify(body)\n context.init.headers = context.init.headers ?? {}\n context.init.headers = { ...context.init.headers, 'Content-Type': 'application/json' }\n }\n\n // --- For all other data types, set the body directly.\n else {\n context.init.body = body as BodyInit\n }\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\n\n/**\n * Parse the request headers based on the provided data and options.\n *\n * @param context The request context.\n * @param options The request options.\n * @example\n *\n * // Append the `Content-Type` header to the request.\n * const context = {}\n * parseRequestHeaders(context, { headers: { 'Content-Type': 'application/json' } })\n *\n * // Will mutate the `init` object to include the headers.\n * console.log(context) // => { init: { headers: { 'Content-Type': 'application/json' } } }\n */\nexport function parseRequestHeaders(context: RequestContext, options: FetchOptions): void {\n const { headers } = options\n\n // --- Merge the headers with the existing headers.\n for (const key in headers) {\n const value = headers[key]\n if (((typeof value !== 'string' || value.length === 0) && typeof value !== 'number')) continue\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n context.init.headers = { ...context.init.headers, [key]: String(value) }\n }\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\n\n/** Regular expression to match path parameters in the URL. */\nconst EXP_PATH_PARAMETER = /:([\\w-]+)|%7B([\\w-]+)%7D/g\n\n/**\n * Parse the request parameters from the request data. This function will mutate the\n * `url` object of the context to include the path parameters based on the provided data.\n *\n * @param context The request context to mutate.\n * @param options The options to pass to the request.\n * @example\n *\n * // Using `express` style path parameters.\n * const context = { url: new URL('https://api.example.com/users/:id') }\n * parseRequestParameters(context, { parameters: { id: 1 } })\n * console.log(context.url.pathname) // 'https://api.example.com/users/1'\n *\n * // Using `OpenAPI` style path parameters.\n * const context = { url: new URL('https://api.example.com/users/{id}') }\n * parseRequestParameters(context, { parameters: { id: 1 } })\n * console.log(context.url.pathname) // 'https://api.example.com/users/1'\n */\nexport function parseRequestParameters(context: RequestContext, options: FetchOptions): void {\n const { url } = context\n const { parameters } = options\n\n // --- Return early if the parameters is not an object.\n if (typeof parameters !== 'object' || parameters === null) return\n if (url === undefined) return\n if (url instanceof URL === false) throw new Error('The `url` must be an instance of `URL`.')\n\n // --- If the method has a parameter, fill the path with the data.\n const pathParameters = url.pathname.match(EXP_PATH_PARAMETER)\n if (!pathParameters) return\n\n // --- Apply the path parameters to the URL.\n for (const parameter of pathParameters.values()) {\n const key = parameter.replaceAll(EXP_PATH_PARAMETER, '$1$2')\n const value = parameters[key]\n\n // --- If the parameter is provided, replace the path with the value.\n if (\n (typeof value === 'string' && value.length > 0)\n || (typeof value === 'number' && Number.isFinite(value))\n || (typeof value === 'boolean')\n ) {\n url.pathname = url.pathname.replace(parameter, value.toString())\n delete parameters[key]\n }\n }\n}\n","/* eslint-disable unicorn/prevent-abbreviations */\nimport type { MaybeArray } from '@unshared/types'\n\n/** An object that can be converted to a query string. */\nexport type SearchParamsObject = Record<string, MaybeArray<boolean | number | string> | undefined>\n\n/** The search array format options. */\nexport type SearchArrayFormat = 'brackets' | 'comma' | 'flat' | 'indices' | 'path'\n\n/** Options for the query string conversion. */\nexport interface ToSearchParamsOptions {\n\n /**\n * Defines how to handle arrays in the object. There is no standard way to\n * represent arrays in query strings, so this option allows you to choose\n * how to handle them. Additionally, you can provide a custom function to\n * handle it yourself.\n *\n * - `brackets` (default): Convert arrays to `key[]=value&key[]=value` format.\n * - `indices`: Convert arrays to `key[0]=value&key[1]=value` format.\n * - `comma`: Convert arrays to `key=value1,value2` format.\n * - `path`: Convert arrays to `key.0=value&key.1=value` format.\n * - `flat`: Convert arrays to `key=value1&key=value2` format.\n *\n * @default 'flat'\n */\n format?: SearchArrayFormat\n}\n\n/**\n * Convert object to query string parameters. Converting all values to strings\n * and arrays to `key[0]=value&key[1]=value` format.\n *\n * @param object The object to convert to a query string.\n * @param options The query string options.\n * @returns The `URLSearchParams` object.\n */\nexport function toSearchParams(object: SearchParamsObject, options: ToSearchParamsOptions = {}): URLSearchParams {\n const { format = 'flat' } = options\n const search = new URLSearchParams()\n for (const key in object) {\n const value = object[key]\n if (value === undefined) continue\n\n // --- Convert arrays based on the format.\n if (Array.isArray(value)) {\n if (format === 'brackets') for (const v of value) search.append(`${key}[]`, String(v))\n else if (format === 'indices') for (const [i, v] of value.entries()) search.append(`${key}[${i}]`, String(v))\n else if (format === 'comma') search.append(key, value.join(','))\n else if (format === 'path') for (const [i, v] of value.entries()) search.append(`${key}.${i}`, String(v))\n else if (format === 'flat') for (const v of value) search.append(key, String(v))\n }\n\n // --- Convert all values to strings.\n else { search.append(key, value.toString()) }\n }\n\n // --- Return the query string.\n return search\n}\n","/* eslint-disable unicorn/prevent-abbreviations */\nimport type { FetchOptions, RequestContext } from './parseRequest'\nimport type { SearchParamsObject as SearchParametersObject } from './toSearchParams'\nimport { toSearchParams } from './toSearchParams'\n\n/**\n * Parse the query parameters from the request data. This function will append\n * the query parameters to the URL based on the method and the data provided.\n *\n * @param context The request context to modify.\n * @param options The options to pass to the request.\n */\nexport function parseRequestQuery(context: RequestContext, options: FetchOptions): void {\n const { url } = context\n const { query, queryArrayFormat } = options\n\n // --- Return early if the query is not an object or the URL is not provided.\n if (url === undefined) return\n if (url instanceof URL === false) throw new Error('The `url` must be an instance of `URL.')\n if (typeof query !== 'object' || query === null) return\n\n // --- Append the `data` to the query parameters if the method does not expect a body.\n const queryObject: SearchParametersObject = {}\n for (const key in query) {\n const value = query[key]\n if (\n (typeof value === 'string' && value.length > 0)\n || (typeof value === 'number' && Number.isFinite(value))\n || (typeof value === 'boolean')\n || Array.isArray(value) && value.length > 0 && value.every(v => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean')\n ) {\n queryObject[key] = value\n delete query[key]\n }\n }\n\n // --- Apply the query parameters to the URL.\n url.search = toSearchParams(queryObject, { format: queryArrayFormat }).toString()\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\n\n/** Regular expression to match the request method and URL. */\nconst EXP_REQUEST = /^((?<method>[a-z]+) )?(?<url>[^:]+?:\\/{2}[^/]+)?(?<path>\\/[^\\s?]*)/i\n\n/** Valid HTTP methods. */\nconst METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options'])\n\n/**\n * Parses the route name to extract the URL and method. It allows the url and method to be\n * provided in the route name, or in the options object. The method will default to 'get'.\n *\n * @param context The request context to mutate.\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @example parseRequestUrl('GET /users', { baseUrl: 'https://api.example.com' }, context)\n */\nexport function parseRequestUrl(context: RequestContext, route: string, options: FetchOptions): void {\n const { method, baseUrl } = options\n\n // --- Extract the path, method, and base URL from the route name.\n const match = EXP_REQUEST.exec(route)\n if (!match?.groups) throw new Error('Could not resolve the `RequestInit` object: Invalid route name.')\n const routeMethod = method ?? match.groups.method ?? 'get'\n const routeBaseUrl = baseUrl ?? match.groups.url\n\n // --- Assert the base URL is provided, either in the options or the route name.\n if (!routeBaseUrl) throw new Error('Could not resolve the `RequestInit` object: the `baseUrl` is missing.')\n\n // --- Assert the method is valid.\n const methodLower = routeMethod.toLowerCase()\n const methodIsValid = METHODS.has(methodLower)\n if (!methodIsValid) throw new Error(`Could not resolve the \\`RequestInit\\` object:, the method \\`${routeMethod}\\` is invalid.`)\n\n // --- Create the url and apply the method.\n context.init = context.init ?? {}\n context.init.method = methodLower\n context.url = new URL(routeBaseUrl)\n\n // --- Append the path to the URL while making sure there are no double slashes.\n context.url.pathname += context.url.pathname.endsWith('/') ? match.groups.path.slice(1) : match.groups.path\n}\n","import type { Loose, MaybeLiteral, ObjectLike } from '@unshared/types'\nimport type { UnionMerge } from '@unshared/types'\nimport type { HttpHeader } from '../HttpHeaders'\nimport type { HttpMethod } from '../HttpMethods'\nimport type { SearchArrayFormat } from './toSearchParams'\nimport { isObjectLike } from './isObjectLike'\nimport { parseRequestBody } from './parseRequestBody'\nimport { parseRequestHeaders } from './parseRequestHeaders'\nimport { parseRequestParameters } from './parseRequestParameters'\nimport { parseRequestQuery } from './parseRequestQuery'\nimport { parseRequestUrl } from './parseRequestUrl'\n\n/** The methods to use for the request. */\nexport type FetchMethod = Lowercase<keyof typeof HttpMethod> | Uppercase<keyof typeof HttpMethod>\n\n/** Headers to include in the request. */\nexport type FetchHeaders = Partial<Record<MaybeLiteral<HttpHeader>, number | string>>\n\n/** Options to pass to the request. */\nexport interface FetchOptions<\n Method extends FetchMethod = FetchMethod,\n BaseUrl extends string = string,\n Parameters extends ObjectLike = ObjectLike,\n Query extends ObjectLike = ObjectLike,\n Body = unknown,\n Headers extends ObjectLike = ObjectLike,\n> extends Omit<RequestInit, 'body' | 'headers' | 'method'> {\n\n /**\n * The method to use for the request.\n *\n * @example 'GET'\n */\n method?: Method\n\n /**\n * The base URL to use for the request. This URL will be used to resolve the\n * path and query parameters of the request.\n *\n * @example 'https://api.example.com'\n */\n baseUrl?: BaseUrl\n\n /**\n * The data to include in the request. This data will be used to populate the\n * query parameters, body, and headers of the request based on the method type.\n *\n * @example { id: 1 }\n */\n data?: Loose<UnionMerge<Body | Headers | Query>>\n\n /**\n * The path parameters to include in the request.\n */\n parameters?: Parameters\n\n /**\n * The query parameters to include in the request.\n */\n query?: Loose<Query>\n\n /**\n * The format to use when serializing the query parameters.\n */\n queryArrayFormat?: SearchArrayFormat\n\n /**\n * The body to include in the request.\n */\n body?: Body extends ObjectLike ? Loose<Body> : Body\n\n /**\n * The headers to include in the request.\n */\n headers?: FetchHeaders & Headers\n}\n\nexport interface RequestContext {\n url?: URL\n init?: RequestInit\n}\n\n/**\n * Resolves the request body and/or query parameters based on the method type. This function\n * will mutate the `init` object to include the request body and headers based on the data type.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The URL and the `RequestInit` object.\n */\nexport function parseRequest(route: string, options: FetchOptions = {}): RequestContext {\n const { data, body, query, parameters, headers, method, baseUrl, queryArrayFormat, ...init } = options\n const context: RequestContext = { init }\n const dataObject = isObjectLike(data) ? data : undefined\n\n // --- Parse the URL and insert the path parameters.\n parseRequestUrl(context, route, { baseUrl, method })\n parseRequestParameters(context, { parameters: parameters ?? dataObject })\n\n // --- Depending on the method, parse the query, body, and headers.\n const requestMethod = context.init?.method?.toLowerCase() ?? 'get'\n const requestExpectsBody = ['post', 'put', 'patch'].includes(requestMethod)\n parseRequestQuery(context, { queryArrayFormat, query: requestExpectsBody ? query : query ?? dataObject })\n parseRequestBody(context, { body: requestExpectsBody ? body ?? dataObject : undefined })\n parseRequestHeaders(context, { headers })\n\n // --- Return the context with the URL and the `RequestInit` object.\n return context\n}\n","import type { FetchOptions } from './parseRequest'\nimport { parseRequest } from './parseRequest'\n\n/**\n * Fetch a route with the provided options. This function will parse the route and\n * options to create a `Request` object and return the response from the server.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The response from the server.\n * @example fetch('GET /users', { query: { limit: 10 } })\n */\nexport async function fetch(route: string, options?: FetchOptions): Promise<Response>\nexport async function fetch(route: string, options: FetchOptions = {}): Promise<Response> {\n const { url, init } = parseRequest(route, options)\n if (!url) throw new Error('Could not parse request URL')\n return await globalThis.fetch(url, init)\n}\n","import type { Awaitable } from '@unshared/functions/awaitable'\nimport type { RequestOptions } from './request'\nimport { awaitable } from '@unshared/functions/awaitable'\n\nasync function * createResponseStreamJsonIterator(response: Response, options: RequestOptions): AsyncGenerator<unknown, void, unknown> {\n const { onError, onSuccess, onData, onEnd } = options\n try {\n const body = response.body\n if (body === null) throw new Error('Could not read the response body, it is empty.')\n const reader = body.getReader()\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n const parts = new TextDecoder().decode(value).trim().split('\\0').filter(Boolean)\n\n // --- For each part, parse as JSON and yield the data.\n for (const part of parts) {\n const payload = JSON.parse(part) as unknown\n if (onData) onData(payload)\n yield payload\n }\n }\n if (onSuccess) onSuccess(response)\n }\n catch (error) {\n if (onError) onError(error as Error)\n }\n finally {\n if (onEnd) onEnd(response)\n }\n}\n\n/**\n * Handle a request response where the content type is a stream of JSON objects. This function\n * will parse the JSON objects and yield the data to the caller. If an error occurs, the `onError`\n * callback will be called and the function will return.\n *\n * @param response The response to handle.\n * @param options The options to pass to the request.\n * @returns An awaitable iterator that yields the parsed JSON objects.\n */\nexport function handleResponseStreamJson(response: Response, options: RequestOptions): Awaitable<AsyncIterable<unknown>, unknown[]> {\n const responseIterator = createResponseStreamJsonIterator(response, options)\n return awaitable(responseIterator)\n}\n","import type { RequestOptions } from './request'\nimport { handleResponseStreamJson } from './handleResponseStreamJson'\n\n/**\n * Handle a request response. This function will parse the response based on the content type and\n * return the data. If an error occurs, the `onError` callback will be called and the function will\n * throw an error.\n *\n * @param response The response to handle.\n * @param options The options to pass to the request.\n * @returns The parsed data from the response.\n */\nexport async function handleResponse(response: Response, options: RequestOptions = {}): Promise<unknown> {\n const { onError, onSuccess, onData, onEnd, onFailure } = options\n const contentType = response.headers.get('Content-Type')\n\n // --- If the response is not OK, throw an error with the response message.\n if (!response.ok) {\n if (onFailure) onFailure(response)\n if (onEnd) onEnd(response)\n throw new Error(response.statusText)\n }\n\n // --- If the status code is 204, return an empty response early.\n if (response.status === 204) {\n if (onSuccess) onSuccess(response)\n if (onEnd) onEnd(response)\n return\n }\n\n // --- If the response is a text content type, return the text response.\n if (contentType?.startsWith('text/')) {\n return await response.text()\n .then((data) => {\n if (onData) onData(data)\n if (onSuccess) onSuccess(response)\n return data\n })\n .catch((error: Error) => {\n if (onError) onError(error)\n throw error\n })\n .finally(() => {\n if (onEnd) onEnd(response)\n })\n }\n\n // --- If the response is a application/json, parse the JSON and return it.\n if (contentType === 'application/json') {\n return await response.json()\n .then((data) => {\n if (onData) onData(data)\n if (onSuccess) onSuccess(response)\n return data as unknown\n })\n .catch((error: Error) => {\n if (onError) onError(error)\n throw error\n })\n .finally(() => {\n if (onEnd) onEnd(response)\n })\n }\n\n // --- If the response is a application/stream+json, return an iterator that parses the JSON.\n if (contentType === 'application/stream+json')\n return handleResponseStreamJson(response, options)\n\n // --- Otherwise, fallback to returning the response body as-is.\n if (onSuccess) onSuccess(response)\n if (onEnd) onEnd(response)\n return response.body\n}\n"],"names":["awaitable"],"mappings":";;AASO,SAAS,aAAa,OAAqC;AAChE,SAAO,OAAO,SAAU,YAAY,UAAU,QAAQ,MAAM,gBAAgB;AAC9E;ACGO,SAAS,eAAe,OAAuC;AACpE,MAAI,OAAO,SAAU,YAAY,UAAU,KAAa,QAAA;AACpD,MAAA,iBAAiB,SAAiB,QAAA;AAChC,QAAA,SAAS,OAAO,OAAO,KAAK;AAC9B,SAAA,OAAO,WAAW,IAAU,KACzB,OAAO,MAAM,CAAC,MACf,aAAa,OAAa,KAC1B,MAAM,QAAQ,CAAC,IAAU,EAAE,MAAM,UAAQ,gBAAgB,IAAI,IAC1D,aAAa,IACrB;AACH;AChBO,SAAS,WAAW,QAAgC;AACrD,MAAA,kBAAkB,SAAiB,QAAA;AACjC,QAAA,WAAW,IAAI,SAAS;AAC9B,aAAW,OAAO,QAAQ;AAClB,UAAA,QAAQ,OAAO,GAAG;AACxB,QAAI,UAAU;AACV,UAAA,MAAM,QAAQ,KAAK;AACrB,mBAAW,QAAQ;AACR,mBAAA,OAAO,KAAK,IAAqB;AAAA;AAGnC,iBAAA,OAAO,KAAK,KAAsB;AAAA,EAAA;AAGxC,SAAA;AACT;ACZgB,SAAA,iBAAiB,SAAyB,SAA6B;AAC/E,QAAA,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CAC1B,IAID,gBAAgB,qBACX,MAAM,SAAS,OACnB,KAAK,CAAC,UACD,UAAQ,OAAO,IAAI,GACnB,aAAW,UAAU,QAAQ,GAC1B,KACR,EACA,MAAM,CAAC,UAAiB;AACnB,UAAA,WAAS,QAAQ,KAAK,GACpB;AAAA,EAAA,CACP,EACA,QAAQ,MAAM;AACT,aAAO,MAAM,QAAQ;AAAA,EAAA,CAC1B,IAID,gBAAgB,4BACX,yBAAyB,UAAU,OAAO,KAG/C,aAAW,UAAU,QAAQ,GAC7B,SAAO,MAAM,QAAQ,GAClB,SAAS;AAClB;;;;;;;;;;;;;;"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"D51s1VII.js","sources":["../../utils/isObjectLike.ts","../../utils/isFormDataLike.ts","../../utils/toFormData.ts","../../utils/parseRequestBody.ts","../../utils/parseRequestHeaders.ts","../../utils/parseRequestParameters.ts","../../utils/toSearchParams.ts","../../utils/parseRequestQuery.ts","../../utils/parseRequestUrl.ts","../../utils/parseRequest.ts","../../utils/fetch.ts","../../utils/handleResponseStreamJson.ts","../../utils/handleResponse.ts"],"sourcesContent":["import type { ObjectLike } from '@unshared/types'\n\n/**\n * Predicate to check if a value is an object-like value.\n *\n * @param value The value to check.\n * @returns `true` if the value is an object-like value, `false` otherwise.\n * @example isObjectLike({}) // true\n */\nexport function isObjectLike(value: unknown): value is ObjectLike {\n return typeof value === 'object' && value !== null && value.constructor === Object\n}\n","/**\n * A type that represents a FormData-like object, which is a plain object with\n * nested Blob, File, or FileList values. Or a FormData instance.\n */\nexport type FormDataLike = FormData | Record<string, Blob | File | FileList>\n\n/**\n * Predicate to check if a value is FormData-like, meaning it is a plain object\n * with nested Blob, File, or FileList values.\n *\n * @param value The value to check.\n * @returns `true` if the value is FormData-like, `false` otherwise.\n * @example isFormDataLike({ file: new File(['test'], 'test.txt') }) // true\n */\nexport function isFormDataLike(value: unknown): value is FormDataLike {\n if (typeof value !== 'object' || value === null) return false\n if (value instanceof FormData) return true\n const values = Object.values(value)\n if (values.length === 0) return false\n return values.every((x) => {\n if (x instanceof File) return true\n if (Array.isArray(x)) return x.every(item => item instanceof File)\n return x instanceof Blob\n })\n}\n","import type { FormDataLike } from './isFormDataLike'\n\n/**\n * Casts an object that may contain `Blob`, `File`, or `FileList` values to a `FormData` object.\n *\n * @param object The object to cast to a `FormData` object.\n * @returns The `FormData` object.\n */\nexport function toFormData(object: FormDataLike): FormData {\n if (object instanceof FormData) return object\n const formData = new FormData()\n for (const key in object) {\n const value = object[key]\n if (value === undefined) continue\n if (Array.isArray(value)) {\n for (const item of value)\n formData.append(key, item as Blob | string)\n }\n else {\n formData.append(key, value as Blob | string)\n }\n }\n return formData\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\nimport { isFormDataLike } from './isFormDataLike'\nimport { isObjectLike } from './isObjectLike'\nimport { toFormData } from './toFormData'\n\n/**\n * Parse the request body based on the provided data and options.\n *\n * @param context The request context.\n * @param options The request options.\n */\nexport function parseRequestBody(context: RequestContext, options: FetchOptions): void {\n const { body } = options\n\n // --- If the method is `GET`, `HEAD`, or `DELETE`, return early.\n if (!context.init?.method) return\n if (['get', 'head', 'delete'].includes(context.init.method ?? 'get')) return\n\n // --- If no data is provided, return early.\n if (body === null || body === undefined) return\n\n // --- If data contains a `File` object, create a FormData object.\n if (isFormDataLike(body)) {\n context.init.body = toFormData(body)\n context.init.headers = context.init.headers ?? {}\n context.init.headers = { ...context.init.headers, 'Content-Type': 'multipart/form-data' }\n }\n\n // --- If the data is a `ReadableStream`, pass it directly to the body.\n else if (body instanceof ReadableStream) {\n context.init.body = body\n context.init.headers = context.init.headers ?? {}\n context.init.headers = { ...context.init.headers, 'Content-Type': 'application/octet-stream' }\n }\n\n // --- If the data is a Blob, pass it directly to the body.\n else if (body instanceof File) {\n context.init.body = body.stream()\n context.init.headers = context.init.headers ?? {}\n context.init.headers = { ...context.init.headers, 'Content-Type': 'application/octet-stream' }\n }\n\n // --- Otherwise, stringify the data and set the content type to JSON.\n else if (isObjectLike(body)) {\n context.init.body = JSON.stringify(body)\n context.init.headers = context.init.headers ?? {}\n context.init.headers = { ...context.init.headers, 'Content-Type': 'application/json' }\n }\n\n // --- For all other data types, set the body directly.\n else {\n context.init.body = body as BodyInit\n }\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\n\n/**\n * Parse the request headers based on the provided data and options.\n *\n * @param context The request context.\n * @param options The request options.\n * @example\n *\n * // Append the `Content-Type` header to the request.\n * const context = {}\n * parseRequestHeaders(context, { headers: { 'Content-Type': 'application/json' } })\n *\n * // Will mutate the `init` object to include the headers.\n * console.log(context) // => { init: { headers: { 'Content-Type': 'application/json' } } }\n */\nexport function parseRequestHeaders(context: RequestContext, options: FetchOptions): void {\n const { headers } = options\n\n // --- Merge the headers with the existing headers.\n for (const key in headers) {\n const value = headers[key]\n if (((typeof value !== 'string' || value.length === 0) && typeof value !== 'number')) continue\n context.init = context.init ?? {}\n context.init.headers = context.init.headers ?? {}\n context.init.headers = { ...context.init.headers, [key]: String(value) }\n }\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\n\n/** Regular expression to match path parameters in the URL. */\nconst EXP_PATH_PARAMETER = /:([\\w-]+)|%7B([\\w-]+)%7D/g\n\n/**\n * Parse the request parameters from the request data. This function will mutate the\n * `url` object of the context to include the path parameters based on the provided data.\n *\n * @param context The request context to mutate.\n * @param options The options to pass to the request.\n * @example\n *\n * // Using `express` style path parameters.\n * const context = { url: new URL('https://api.example.com/users/:id') }\n * parseRequestParameters(context, { parameters: { id: 1 } })\n * console.log(context.url.pathname) // 'https://api.example.com/users/1'\n *\n * // Using `OpenAPI` style path parameters.\n * const context = { url: new URL('https://api.example.com/users/{id}') }\n * parseRequestParameters(context, { parameters: { id: 1 } })\n * console.log(context.url.pathname) // 'https://api.example.com/users/1'\n */\nexport function parseRequestParameters(context: RequestContext, options: FetchOptions): void {\n const { url } = context\n const { parameters } = options\n\n // --- Return early if the parameters is not an object.\n if (typeof parameters !== 'object' || parameters === null) return\n if (url === undefined) return\n if (url instanceof URL === false) throw new Error('The `url` must be an instance of `URL`.')\n\n // --- If the method has a parameter, fill the path with the data.\n const pathParameters = url.pathname.match(EXP_PATH_PARAMETER)\n if (!pathParameters) return\n\n // --- Apply the path parameters to the URL.\n for (const parameter of pathParameters.values()) {\n const key = parameter.replaceAll(EXP_PATH_PARAMETER, '$1$2')\n const value = parameters[key]\n\n // --- If the parameter is provided, replace the path with the value.\n if (\n (typeof value === 'string' && value.length > 0)\n || (typeof value === 'number' && Number.isFinite(value))\n || (typeof value === 'boolean')\n ) {\n url.pathname = url.pathname.replace(parameter, value.toString())\n delete parameters[key]\n }\n }\n}\n","/* eslint-disable unicorn/prevent-abbreviations */\nimport type { MaybeArray } from '@unshared/types'\n\n/** An object that can be converted to a query string. */\nexport type SearchParamsObject = Record<string, MaybeArray<boolean | number | string> | undefined>\n\n/** The search array format options. */\nexport type SearchArrayFormat = 'brackets' | 'comma' | 'flat' | 'indices' | 'path'\n\n/** Options for the query string conversion. */\nexport interface ToSearchParamsOptions {\n\n /**\n * Defines how to handle arrays in the object. There is no standard way to\n * represent arrays in query strings, so this option allows you to choose\n * how to handle them. Additionally, you can provide a custom function to\n * handle it yourself.\n *\n * - `brackets` (default): Convert arrays to `key[]=value&key[]=value` format.\n * - `indices`: Convert arrays to `key[0]=value&key[1]=value` format.\n * - `comma`: Convert arrays to `key=value1,value2` format.\n * - `path`: Convert arrays to `key.0=value&key.1=value` format.\n * - `flat`: Convert arrays to `key=value1&key=value2` format.\n *\n * @default 'flat'\n */\n format?: SearchArrayFormat\n}\n\n/**\n * Convert object to query string parameters. Converting all values to strings\n * and arrays to `key[0]=value&key[1]=value` format.\n *\n * @param object The object to convert to a query string.\n * @param options The query string options.\n * @returns The `URLSearchParams` object.\n */\nexport function toSearchParams(object: SearchParamsObject, options: ToSearchParamsOptions = {}): URLSearchParams {\n const { format = 'flat' } = options\n const search = new URLSearchParams()\n for (const key in object) {\n const value = object[key]\n if (value === undefined) continue\n\n // --- Convert arrays based on the format.\n if (Array.isArray(value)) {\n if (format === 'brackets') for (const v of value) search.append(`${key}[]`, String(v))\n else if (format === 'indices') for (const [i, v] of value.entries()) search.append(`${key}[${i}]`, String(v))\n else if (format === 'comma') search.append(key, value.join(','))\n else if (format === 'path') for (const [i, v] of value.entries()) search.append(`${key}.${i}`, String(v))\n else if (format === 'flat') for (const v of value) search.append(key, String(v))\n }\n\n // --- Convert all values to strings.\n else { search.append(key, value.toString()) }\n }\n\n // --- Return the query string.\n return search\n}\n","/* eslint-disable unicorn/prevent-abbreviations */\nimport type { FetchOptions, RequestContext } from './parseRequest'\nimport type { SearchParamsObject as SearchParametersObject } from './toSearchParams'\nimport { toSearchParams } from './toSearchParams'\n\n/**\n * Parse the query parameters from the request data. This function will append\n * the query parameters to the URL based on the method and the data provided.\n *\n * @param context The request context to modify.\n * @param options The options to pass to the request.\n */\nexport function parseRequestQuery(context: RequestContext, options: FetchOptions): void {\n const { url } = context\n const { query, queryArrayFormat } = options\n\n // --- Return early if the query is not an object or the URL is not provided.\n if (url === undefined) return\n if (url instanceof URL === false) throw new Error('The `url` must be an instance of `URL.')\n if (typeof query !== 'object' || query === null) return\n\n // --- Append the `data` to the query parameters if the method does not expect a body.\n const queryObject: SearchParametersObject = {}\n for (const key in query) {\n const value = query[key]\n if (\n (typeof value === 'string' && value.length > 0)\n || (typeof value === 'number' && Number.isFinite(value))\n || (typeof value === 'boolean')\n || Array.isArray(value) && value.length > 0 && value.every(v => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean')\n ) {\n queryObject[key] = value\n delete query[key]\n }\n }\n\n // --- Apply the query parameters to the URL.\n url.search = toSearchParams(queryObject, { format: queryArrayFormat }).toString()\n}\n","import type { FetchOptions, RequestContext } from './parseRequest'\n\n/** Regular expression to match the request method and URL. */\nconst EXP_REQUEST = /^((?<method>[a-z]+) )?(?<url>[^:]+?:\\/{2}[^/]+)?(?<path>\\/[^\\s?]*)/i\n\n/** Valid HTTP methods. */\nconst METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options'])\n\n/**\n * Parses the route name to extract the URL and method. It allows the url and method to be\n * provided in the route name, or in the options object. The method will default to 'get'.\n *\n * @param context The request context to mutate.\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @example parseRequestUrl('GET /users', { baseUrl: 'https://api.example.com' }, context)\n */\nexport function parseRequestUrl(context: RequestContext, route: string, options: FetchOptions): void {\n const { method, baseUrl } = options\n\n // --- Extract the path, method, and base URL from the route name.\n const match = EXP_REQUEST.exec(route)\n if (!match?.groups) throw new Error('Could not resolve the `RequestInit` object: Invalid route name.')\n const routeMethod = method ?? match.groups.method ?? 'get'\n const routeBaseUrl = baseUrl ?? match.groups.url\n\n // --- Assert the base URL is provided, either in the options or the route name.\n if (!routeBaseUrl) throw new Error('Could not resolve the `RequestInit` object: the `baseUrl` is missing.')\n\n // --- Assert the method is valid.\n const methodLower = routeMethod.toLowerCase()\n const methodIsValid = METHODS.has(methodLower)\n if (!methodIsValid) throw new Error(`Could not resolve the \\`RequestInit\\` object:, the method \\`${routeMethod}\\` is invalid.`)\n\n // --- Create the url and apply the method.\n context.init = context.init ?? {}\n context.init.method = methodLower\n context.url = new URL(routeBaseUrl)\n\n // --- Append the path to the URL while making sure there are no double slashes.\n context.url.pathname += context.url.pathname.endsWith('/') ? match.groups.path.slice(1) : match.groups.path\n}\n","import type { Loose, MaybeLiteral, ObjectLike } from '@unshared/types'\nimport type { UnionMerge } from '@unshared/types'\nimport type { HttpHeader } from '../HttpHeaders'\nimport type { HttpMethod } from '../HttpMethods'\nimport type { SearchArrayFormat } from './toSearchParams'\nimport { isObjectLike } from './isObjectLike'\nimport { parseRequestBody } from './parseRequestBody'\nimport { parseRequestHeaders } from './parseRequestHeaders'\nimport { parseRequestParameters } from './parseRequestParameters'\nimport { parseRequestQuery } from './parseRequestQuery'\nimport { parseRequestUrl } from './parseRequestUrl'\n\n/** The methods to use for the request. */\nexport type FetchMethod = Lowercase<keyof typeof HttpMethod> | Uppercase<keyof typeof HttpMethod>\n\n/** Headers to include in the request. */\nexport type FetchHeaders = Partial<Record<MaybeLiteral<HttpHeader>, number | string>>\n\n/** Options to pass to the request. */\nexport interface FetchOptions<\n Method extends FetchMethod = FetchMethod,\n BaseUrl extends string = string,\n Parameters extends ObjectLike = ObjectLike,\n Query extends ObjectLike = ObjectLike,\n Body = unknown,\n Headers extends ObjectLike = ObjectLike,\n> extends Omit<RequestInit, 'body' | 'headers' | 'method'> {\n\n /**\n * The method to use for the request.\n *\n * @example 'GET'\n */\n method?: Method\n\n /**\n * The base URL to use for the request. This URL will be used to resolve the\n * path and query parameters of the request.\n *\n * @example 'https://api.example.com'\n */\n baseUrl?: BaseUrl\n\n /**\n * The data to include in the request. This data will be used to populate the\n * query parameters, body, and headers of the request based on the method type.\n *\n * @example { id: 1 }\n */\n data?: Loose<UnionMerge<Body | Headers | Query>>\n\n /**\n * The path parameters to include in the request.\n */\n parameters?: Parameters\n\n /**\n * The query parameters to include in the request.\n */\n query?: Loose<Query>\n\n /**\n * The format to use when serializing the query parameters.\n */\n queryArrayFormat?: SearchArrayFormat\n\n /**\n * The body to include in the request.\n */\n body?: Body extends ObjectLike ? Loose<Body> : Body\n\n /**\n * The headers to include in the request.\n */\n headers?: FetchHeaders & Headers\n}\n\nexport interface RequestContext {\n url?: URL\n init?: RequestInit\n}\n\n/**\n * Resolves the request body and/or query parameters based on the method type. This function\n * will mutate the `init` object to include the request body and headers based on the data type.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The URL and the `RequestInit` object.\n */\nexport function parseRequest(route: string, options: FetchOptions = {}): RequestContext {\n const { data, body, query, parameters, headers, method, baseUrl, queryArrayFormat, ...init } = options\n const context: RequestContext = { init }\n const dataObject = isObjectLike(data) ? data : undefined\n\n // --- Parse the URL and insert the path parameters.\n parseRequestUrl(context, route, { baseUrl, method })\n parseRequestParameters(context, { parameters: parameters ?? dataObject })\n\n // --- Depending on the method, parse the query, body, and headers.\n const requestMethod = context.init?.method?.toLowerCase() ?? 'get'\n const requestExpectsBody = ['post', 'put', 'patch'].includes(requestMethod)\n parseRequestQuery(context, { queryArrayFormat, query: requestExpectsBody ? query : query ?? dataObject })\n parseRequestBody(context, { body: requestExpectsBody ? body ?? dataObject : undefined })\n parseRequestHeaders(context, { headers })\n\n // --- Return the context with the URL and the `RequestInit` object.\n return context\n}\n","import type { FetchOptions } from './parseRequest'\nimport { parseRequest } from './parseRequest'\n\n/**\n * Fetch a route with the provided options. This function will parse the route and\n * options to create a `Request` object and return the response from the server.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The response from the server.\n * @example fetch('GET /users', { query: { limit: 10 } })\n */\nexport async function fetch(route: string, options?: FetchOptions): Promise<Response>\nexport async function fetch(route: string, options: FetchOptions = {}): Promise<Response> {\n const { url, init } = parseRequest(route, options)\n if (!url) throw new Error('Could not parse request URL')\n return await globalThis.fetch(url, init)\n}\n","import type { Awaitable } from '@unshared/functions/awaitable'\nimport type { RequestOptions } from './request'\nimport { awaitable } from '@unshared/functions/awaitable'\n\nasync function * createResponseStreamJsonIterator(response: Response, options: RequestOptions): AsyncGenerator<unknown, void, unknown> {\n const { onError, onSuccess, onData, onEnd } = options\n try {\n const body = response.body\n if (body === null) throw new Error('Could not read the response body, it is empty.')\n const reader = body.getReader()\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n const parts = new TextDecoder().decode(value).trim().split('\\0').filter(Boolean)\n\n // --- For each part, parse as JSON and yield the data.\n for (const part of parts) {\n const payload = JSON.parse(part) as unknown\n if (onData) onData(payload)\n yield payload\n }\n }\n if (onSuccess) onSuccess(response)\n }\n catch (error) {\n if (onError) onError(error as Error)\n }\n finally {\n if (onEnd) onEnd(response)\n }\n}\n\n/**\n * Handle a request response where the content type is a stream of JSON objects. This function\n * will parse the JSON objects and yield the data to the caller. If an error occurs, the `onError`\n * callback will be called and the function will return.\n *\n * @param response The response to handle.\n * @param options The options to pass to the request.\n * @returns An awaitable iterator that yields the parsed JSON objects.\n */\nexport function handleResponseStreamJson(response: Response, options: RequestOptions): Awaitable<AsyncIterable<unknown>, unknown[]> {\n const responseIterator = createResponseStreamJsonIterator(response, options)\n return awaitable(responseIterator)\n}\n","import type { RequestOptions } from './request'\nimport { handleResponseStreamJson } from './handleResponseStreamJson'\n\n/**\n * Handle a request response. This function will parse the response based on the content type and\n * return the data. If an error occurs, the `onError` callback will be called and the function will\n * throw an error.\n *\n * @param response The response to handle.\n * @param options The options to pass to the request.\n * @returns The parsed data from the response.\n */\nexport async function handleResponse(response: Response, options: RequestOptions = {}): Promise<unknown> {\n const { onError, onSuccess, onData, onEnd, onFailure } = options\n const contentType = response.headers.get('Content-Type')\n\n // --- If the response is not OK, throw an error with the response message.\n if (!response.ok) {\n if (onFailure) onFailure(response)\n if (onEnd) onEnd(response)\n throw new Error(response.statusText)\n }\n\n // --- If the status code is 204, return an empty response early.\n if (response.status === 204) {\n if (onSuccess) onSuccess(response)\n if (onEnd) onEnd(response)\n return\n }\n\n // --- If the response is a text content type, return the text response.\n if (contentType?.startsWith('text/')) {\n return await response.text()\n .then((data) => {\n if (onData) onData(data)\n if (onSuccess) onSuccess(response)\n return data\n })\n .catch((error: Error) => {\n if (onError) onError(error)\n throw error\n })\n .finally(() => {\n if (onEnd) onEnd(response)\n })\n }\n\n // --- If the response is a application/json, parse the JSON and return it.\n if (contentType === 'application/json') {\n return await response.json()\n .then((data) => {\n if (onData) onData(data)\n if (onSuccess) onSuccess(response)\n return data as unknown\n })\n .catch((error: Error) => {\n if (onError) onError(error)\n throw error\n })\n .finally(() => {\n if (onEnd) onEnd(response)\n })\n }\n\n // --- If the response is a application/stream+json, return an iterator that parses the JSON.\n if (contentType === 'application/stream+json')\n return handleResponseStreamJson(response, options)\n\n // --- Otherwise, fallback to returning the response body as-is.\n if (onSuccess) onSuccess(response)\n if (onEnd) onEnd(response)\n return response.body\n}\n"],"names":[],"mappings":";AASO,SAAS,aAAa,OAAqC;AACh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