@layer-drone/protocol 0.0.8 → 0.0.9-alpha.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.
@@ -0,0 +1,181 @@
1
+ import type { Client, Config, RequestOptions } from "./types.js";
2
+ import {
3
+ buildUrl,
4
+ createConfig,
5
+ createInterceptors,
6
+ getParseAs,
7
+ mergeConfigs,
8
+ mergeHeaders,
9
+ setAuthParams,
10
+ } from "./utils.js";
11
+
12
+ type ReqInit = Omit<RequestInit, "body" | "headers"> & {
13
+ body?: any;
14
+ headers: ReturnType<typeof mergeHeaders>;
15
+ };
16
+
17
+ export const createClient = (config: Config = {}): Client => {
18
+ let _config = mergeConfigs(createConfig(), config);
19
+
20
+ const getConfig = (): Config => ({ ..._config });
21
+
22
+ const setConfig = (config: Config): Config => {
23
+ _config = mergeConfigs(_config, config);
24
+ return getConfig();
25
+ };
26
+
27
+ const interceptors = createInterceptors<
28
+ Request,
29
+ Response,
30
+ unknown,
31
+ RequestOptions
32
+ >();
33
+
34
+ const request: Client["request"] = async (options) => {
35
+ const opts = {
36
+ ..._config,
37
+ ...options,
38
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
39
+ headers: mergeHeaders(_config.headers, options.headers),
40
+ };
41
+
42
+ if (opts.security) {
43
+ await setAuthParams({
44
+ ...opts,
45
+ security: opts.security,
46
+ });
47
+ }
48
+
49
+ if (opts.body && opts.bodySerializer) {
50
+ opts.body = opts.bodySerializer(opts.body);
51
+ }
52
+
53
+ // remove Content-Type header if body is empty to avoid sending invalid requests
54
+ if (opts.body === undefined || opts.body === "") {
55
+ opts.headers.delete("Content-Type");
56
+ }
57
+
58
+ const url = buildUrl(opts);
59
+ const requestInit: ReqInit = {
60
+ redirect: "follow",
61
+ ...opts,
62
+ };
63
+
64
+ let request = new Request(url, requestInit);
65
+
66
+ for (const fn of interceptors.request._fns) {
67
+ if (fn) {
68
+ request = await fn(request, opts);
69
+ }
70
+ }
71
+
72
+ // fetch must be assigned here, otherwise it would throw the error:
73
+ // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
74
+ const _fetch = opts.fetch!;
75
+ let response = await _fetch(request);
76
+
77
+ for (const fn of interceptors.response._fns) {
78
+ if (fn) {
79
+ response = await fn(response, request, opts);
80
+ }
81
+ }
82
+
83
+ const result = {
84
+ request,
85
+ response,
86
+ };
87
+
88
+ if (response.ok) {
89
+ if (
90
+ response.status === 204 ||
91
+ response.headers.get("Content-Length") === "0"
92
+ ) {
93
+ return opts.responseStyle === "data"
94
+ ? {}
95
+ : {
96
+ data: {},
97
+ ...result,
98
+ };
99
+ }
100
+
101
+ const parseAs =
102
+ (opts.parseAs === "auto"
103
+ ? getParseAs(response.headers.get("Content-Type"))
104
+ : opts.parseAs) ?? "json";
105
+
106
+ if (parseAs === "stream") {
107
+ return opts.responseStyle === "data"
108
+ ? response.body
109
+ : {
110
+ data: response.body,
111
+ ...result,
112
+ };
113
+ }
114
+
115
+ let data = await response[parseAs]();
116
+ if (parseAs === "json") {
117
+ if (opts.responseValidator) {
118
+ await opts.responseValidator(data);
119
+ }
120
+
121
+ if (opts.responseTransformer) {
122
+ data = await opts.responseTransformer(data);
123
+ }
124
+ }
125
+
126
+ return opts.responseStyle === "data"
127
+ ? data
128
+ : {
129
+ data,
130
+ ...result,
131
+ };
132
+ }
133
+
134
+ let error = await response.text();
135
+
136
+ try {
137
+ error = JSON.parse(error);
138
+ } catch {
139
+ // noop
140
+ }
141
+
142
+ let finalError = error;
143
+
144
+ for (const fn of interceptors.error._fns) {
145
+ if (fn) {
146
+ finalError = (await fn(error, response, request, opts)) as string;
147
+ }
148
+ }
149
+
150
+ finalError = finalError || ({} as string);
151
+
152
+ if (opts.throwOnError) {
153
+ throw finalError;
154
+ }
155
+
156
+ // TODO: we probably want to return error and improve types
157
+ return opts.responseStyle === "data"
158
+ ? undefined
159
+ : {
160
+ error: finalError,
161
+ ...result,
162
+ };
163
+ };
164
+
165
+ return {
166
+ buildUrl,
167
+ connect: (options) => request({ ...options, method: "CONNECT" }),
168
+ delete: (options) => request({ ...options, method: "DELETE" }),
169
+ get: (options) => request({ ...options, method: "GET" }),
170
+ getConfig,
171
+ head: (options) => request({ ...options, method: "HEAD" }),
172
+ interceptors,
173
+ options: (options) => request({ ...options, method: "OPTIONS" }),
174
+ patch: (options) => request({ ...options, method: "PATCH" }),
175
+ post: (options) => request({ ...options, method: "POST" }),
176
+ put: (options) => request({ ...options, method: "PUT" }),
177
+ request,
178
+ setConfig,
179
+ trace: (options) => request({ ...options, method: "TRACE" }),
180
+ };
181
+ };
@@ -0,0 +1,22 @@
1
+ export type { Auth } from "../core/auth.js";
2
+ export type { QuerySerializerOptions } from "../core/bodySerializer.js";
3
+ export {
4
+ formDataBodySerializer,
5
+ jsonBodySerializer,
6
+ urlSearchParamsBodySerializer,
7
+ } from "../core/bodySerializer.js";
8
+ export { buildClientParams } from "../core/params.js";
9
+ export { createClient } from "./client.js";
10
+ export type {
11
+ Client,
12
+ ClientOptions,
13
+ Config,
14
+ CreateClientConfig,
15
+ Options,
16
+ OptionsLegacyParser,
17
+ RequestOptions,
18
+ RequestResult,
19
+ ResponseStyle,
20
+ TDataShape,
21
+ } from "./types.js";
22
+ export { createConfig, mergeHeaders } from "./utils.js";
@@ -0,0 +1,215 @@
1
+ import type { Auth } from "../core/auth.js";
2
+ import type {
3
+ Client as CoreClient,
4
+ Config as CoreConfig,
5
+ } from "../core/types.js";
6
+ import type { Middleware } from "./utils.js";
7
+
8
+ export type ResponseStyle = "data" | "fields";
9
+
10
+ export interface Config<T extends ClientOptions = ClientOptions>
11
+ extends Omit<RequestInit, "body" | "headers" | "method">,
12
+ CoreConfig {
13
+ /**
14
+ * Base URL for all requests made by this client.
15
+ */
16
+ baseUrl?: T["baseUrl"];
17
+ /**
18
+ * Fetch API implementation. You can use this option to provide a custom
19
+ * fetch instance.
20
+ *
21
+ * @default globalThis.fetch
22
+ */
23
+ fetch?: (request: Request) => ReturnType<typeof fetch>;
24
+ /**
25
+ * Please don't use the Fetch client for Next.js applications. The `next`
26
+ * options won't have any effect.
27
+ *
28
+ * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
29
+ */
30
+ next?: never;
31
+ /**
32
+ * Return the response data parsed in a specified format. By default, `auto`
33
+ * will infer the appropriate method from the `Content-Type` response header.
34
+ * You can override this behavior with any of the {@link Body} methods.
35
+ * Select `stream` if you don't want to parse response data at all.
36
+ *
37
+ * @default 'auto'
38
+ */
39
+ parseAs?: Exclude<keyof Body, "body" | "bodyUsed"> | "auto" | "stream";
40
+ /**
41
+ * Should we return only data or multiple fields (data, error, response, etc.)?
42
+ *
43
+ * @default 'fields'
44
+ */
45
+ responseStyle?: ResponseStyle;
46
+ /**
47
+ * Throw an error instead of returning it in the response?
48
+ *
49
+ * @default false
50
+ */
51
+ throwOnError?: T["throwOnError"];
52
+ }
53
+
54
+ export interface RequestOptions<
55
+ TResponseStyle extends ResponseStyle = "fields",
56
+ ThrowOnError extends boolean = boolean,
57
+ Url extends string = string,
58
+ > extends Config<{
59
+ responseStyle: TResponseStyle;
60
+ throwOnError: ThrowOnError;
61
+ }> {
62
+ /**
63
+ * Any body that you want to add to your request.
64
+ *
65
+ * {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
66
+ */
67
+ body?: unknown;
68
+ path?: Record<string, unknown>;
69
+ query?: Record<string, unknown>;
70
+ /**
71
+ * Security mechanism(s) to use for the request.
72
+ */
73
+ security?: ReadonlyArray<Auth>;
74
+ url: Url;
75
+ }
76
+
77
+ export type RequestResult<
78
+ TData = unknown,
79
+ TError = unknown,
80
+ ThrowOnError extends boolean = boolean,
81
+ TResponseStyle extends ResponseStyle = "fields",
82
+ > = ThrowOnError extends true
83
+ ? Promise<
84
+ TResponseStyle extends "data"
85
+ ? TData extends Record<string, unknown>
86
+ ? TData[keyof TData]
87
+ : TData
88
+ : {
89
+ data: TData extends Record<string, unknown>
90
+ ? TData[keyof TData]
91
+ : TData;
92
+ request: Request;
93
+ response: Response;
94
+ }
95
+ >
96
+ : Promise<
97
+ TResponseStyle extends "data"
98
+ ?
99
+ | (TData extends Record<string, unknown>
100
+ ? TData[keyof TData]
101
+ : TData)
102
+ | undefined
103
+ : (
104
+ | {
105
+ data: TData extends Record<string, unknown>
106
+ ? TData[keyof TData]
107
+ : TData;
108
+ error: undefined;
109
+ }
110
+ | {
111
+ data: undefined;
112
+ error: TError extends Record<string, unknown>
113
+ ? TError[keyof TError]
114
+ : TError;
115
+ }
116
+ ) & {
117
+ request: Request;
118
+ response: Response;
119
+ }
120
+ >;
121
+
122
+ export interface ClientOptions {
123
+ baseUrl?: string;
124
+ responseStyle?: ResponseStyle;
125
+ throwOnError?: boolean;
126
+ }
127
+
128
+ type MethodFn = <
129
+ TData = unknown,
130
+ TError = unknown,
131
+ ThrowOnError extends boolean = false,
132
+ TResponseStyle extends ResponseStyle = "fields",
133
+ >(
134
+ options: Omit<RequestOptions<TResponseStyle, ThrowOnError>, "method">,
135
+ ) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
136
+
137
+ type RequestFn = <
138
+ TData = unknown,
139
+ TError = unknown,
140
+ ThrowOnError extends boolean = false,
141
+ TResponseStyle extends ResponseStyle = "fields",
142
+ >(
143
+ options: Omit<RequestOptions<TResponseStyle, ThrowOnError>, "method"> &
144
+ Pick<Required<RequestOptions<TResponseStyle, ThrowOnError>>, "method">,
145
+ ) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
146
+
147
+ type BuildUrlFn = <
148
+ TData extends {
149
+ body?: unknown;
150
+ path?: Record<string, unknown>;
151
+ query?: Record<string, unknown>;
152
+ url: string;
153
+ },
154
+ >(
155
+ options: Pick<TData, "url"> & Options<TData>,
156
+ ) => string;
157
+
158
+ export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn> & {
159
+ interceptors: Middleware<Request, Response, unknown, RequestOptions>;
160
+ };
161
+
162
+ /**
163
+ * The `createClientConfig()` function will be called on client initialization
164
+ * and the returned object will become the client's initial configuration.
165
+ *
166
+ * You may want to initialize your client this way instead of calling
167
+ * `setConfig()`. This is useful for example if you're using Next.js
168
+ * to ensure your client always has the correct values.
169
+ */
170
+ export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (
171
+ override?: Config<ClientOptions & T>,
172
+ ) => Config<Required<ClientOptions> & T>;
173
+
174
+ export interface TDataShape {
175
+ body?: unknown;
176
+ headers?: unknown;
177
+ path?: unknown;
178
+ query?: unknown;
179
+ url: string;
180
+ }
181
+
182
+ type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
183
+
184
+ export type Options<
185
+ TData extends TDataShape = TDataShape,
186
+ ThrowOnError extends boolean = boolean,
187
+ TResponseStyle extends ResponseStyle = "fields",
188
+ > = OmitKeys<
189
+ RequestOptions<TResponseStyle, ThrowOnError>,
190
+ "body" | "path" | "query" | "url"
191
+ > &
192
+ Omit<TData, "url">;
193
+
194
+ export type OptionsLegacyParser<
195
+ TData = unknown,
196
+ ThrowOnError extends boolean = boolean,
197
+ TResponseStyle extends ResponseStyle = "fields",
198
+ > = TData extends { body?: any }
199
+ ? TData extends { headers?: any }
200
+ ? OmitKeys<
201
+ RequestOptions<TResponseStyle, ThrowOnError>,
202
+ "body" | "headers" | "url"
203
+ > &
204
+ TData
205
+ : OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, "body" | "url"> &
206
+ TData &
207
+ Pick<RequestOptions<TResponseStyle, ThrowOnError>, "headers">
208
+ : TData extends { headers?: any }
209
+ ? OmitKeys<
210
+ RequestOptions<TResponseStyle, ThrowOnError>,
211
+ "headers" | "url"
212
+ > &
213
+ TData &
214
+ Pick<RequestOptions<TResponseStyle, ThrowOnError>, "body">
215
+ : OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, "url"> & TData;