@autometa/http 1.4.20 → 2.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +107 -2
  2. package/dist/assertions/http-adapters.d.ts +35 -0
  3. package/dist/assertions/http-assertions-plugin.d.ts +16 -0
  4. package/dist/assertions/http-ensure.d.ts +42 -0
  5. package/dist/axios-transport.d.ts +22 -0
  6. package/dist/default-schema.d.ts +8 -0
  7. package/dist/fetch-transport.d.ts +21 -0
  8. package/dist/http-request.d.ts +109 -0
  9. package/dist/http-response.d.ts +77 -0
  10. package/dist/http.d.ts +300 -0
  11. package/dist/index.cjs +2076 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.ts +15 -1116
  14. package/dist/index.js +1727 -845
  15. package/dist/index.js.map +1 -1
  16. package/dist/plugins.d.ts +43 -0
  17. package/dist/request-meta.config.d.ts +56 -0
  18. package/dist/schema.map.d.ts +11 -0
  19. package/dist/transform-response.d.ts +1 -0
  20. package/dist/transport.d.ts +11 -0
  21. package/dist/types.d.ts +39 -0
  22. package/package.json +31 -31
  23. package/.eslintignore +0 -3
  24. package/.eslintrc.cjs +0 -4
  25. package/.turbo/turbo-lint$colon$fix.log +0 -4
  26. package/.turbo/turbo-prettify.log +0 -5
  27. package/.turbo/turbo-test.log +0 -120
  28. package/CHANGELOG.md +0 -335
  29. package/dist/esm/index.js +0 -1117
  30. package/dist/esm/index.js.map +0 -1
  31. package/dist/index.d.cts +0 -1116
  32. package/src/axios-client.ts +0 -35
  33. package/src/default-client-factory.axios.spec.ts +0 -9
  34. package/src/default-client-factory.other.spec.ts +0 -13
  35. package/src/default-client-factory.ts +0 -7
  36. package/src/default-schema.spec.ts +0 -74
  37. package/src/default-schema.ts +0 -127
  38. package/src/http-client.ts +0 -20
  39. package/src/http-request.spec.ts +0 -172
  40. package/src/http-request.ts +0 -201
  41. package/src/http-response.ts +0 -107
  42. package/src/http.spec.ts +0 -189
  43. package/src/http.ts +0 -907
  44. package/src/index.ts +0 -13
  45. package/src/node_modules/.vitest/deps/_metadata.json +0 -8
  46. package/src/node_modules/.vitest/deps/package.json +0 -3
  47. package/src/node_modules/.vitest/results.json +0 -1
  48. package/src/request-meta.config.spec.ts +0 -81
  49. package/src/request-meta.config.ts +0 -134
  50. package/src/request.config.ts +0 -34
  51. package/src/schema.map.spec.ts +0 -50
  52. package/src/schema.map.ts +0 -68
  53. package/src/transform-response.ts +0 -43
  54. package/src/types.ts +0 -37
  55. package/tsup.config.ts +0 -14
package/dist/index.d.ts CHANGED
@@ -1,1116 +1,15 @@
1
- import { StatusCodes } from '@autometa/status-codes';
2
- import { AxiosRequestConfig } from 'axios';
3
- import { Class } from '@autometa/types';
4
-
5
- declare class HTTPResponse<T = unknown> {
6
- status: StatusCode;
7
- statusText: string;
8
- data: T;
9
- headers: Record<string, string>;
10
- request: HTTPRequest<unknown>;
11
- constructor();
12
- static fromRaw<T>(response: HTTPResponse<T>): HTTPResponse<T>;
13
- /**
14
- * Decomposes a response, creating an exact copy of the current response,
15
- * but with a new data value. The data can be provided directly as is, or it
16
- * can be generated through a callback function which receives the current
17
- * response data as an argument.
18
- *
19
- * ```ts
20
- * const response = await http.get("/products");
21
- *
22
- * // direct value
23
- * const products = response.data;
24
- * const firstProduct = response.decompose(products[0]);
25
- * // callback transformer
26
- * const secondProduct = response.decompose((products) => products[1]);
27
- * // callback transformer with destructuring
28
- * const secondProduct = response.decompose(([product]) => product);
29
- * ```
30
- * @param value
31
- */
32
- decompose<K>(value: K): HTTPResponse<K>;
33
- decompose<K>(transformFn: (response: T) => K): HTTPResponse<K>;
34
- }
35
- declare class HTTPResponseBuilder {
36
- #private;
37
- static create(): HTTPResponseBuilder;
38
- derive(): HTTPResponseBuilder;
39
- status(code: StatusCode): this;
40
- statusText(text: string): this;
41
- data<T>(data: T): this;
42
- headers(dict: Record<string, string>): this;
43
- header(name: string, value: string): this;
44
- request(request: HTTPRequest<unknown>): this;
45
- build(): HTTPResponse<unknown>;
46
- }
47
-
48
- type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS" | "TRACE" | "CONNECT" | "get" | "post" | "put" | "delete" | "patch" | "head" | "options" | "trace" | "connect";
49
- type HTTPAdditionalOptions<T> = {
50
- [P in keyof T]: T[P];
51
- };
52
- type SchemaParser = {
53
- parse: (data: unknown) => unknown;
54
- } | {
55
- validate: (data: unknown) => unknown;
56
- } | ((data: unknown) => unknown);
57
- type StatusCode<T extends typeof StatusCodes = typeof StatusCodes> = {
58
- [P in keyof T]: T[P] extends {
59
- status: infer U;
60
- } ? U : never;
61
- }[keyof T];
62
- type RequestHook = <T = unknown>(state: HTTPRequest<T>) => unknown;
63
- type ResponseHook<T> = (state: HTTPResponse<T>) => unknown;
64
-
65
- interface RequestBaseConfig {
66
- headers?: Record<string, string>;
67
- params?: Record<string, string | string[] | Record<string, unknown>>;
68
- baseUrl?: string;
69
- route?: string[];
70
- method: HTTPMethod;
71
- /**
72
- * Returns the full URL of the request, including the base url,
73
- * routes, and query parameters.
74
- *
75
- * ```ts
76
- * console.log(request.fullUrl())// https://example.com/foo?bar=baz?array=1,2,3
77
- * ```
78
- *
79
- * Note characters may be converted to escape codes. I.e (space => %20) and (comma => %2C)
80
- *
81
- * N.B this method estimates what the url will be. The actual value
82
- * might be different depending on your underlying HTTPClient and
83
- * configuration. For example, query parameters might
84
- * use different array formats.
85
- * @returns The full url of the request
86
- */
87
- get fullUrl(): string;
88
- }
89
- interface RequestData<T = unknown> {
90
- data: T;
91
- }
92
- type RequestConfig<T> = RequestBaseConfig & RequestData<T>;
93
- type RequestConfigBasic = RequestConfig<Record<string, unknown>>;
94
-
95
- declare class HTTPRequest<T = unknown> implements RequestConfig<T> {
96
- headers: Record<string, string>;
97
- params: Record<string, string | string[] | Record<string, unknown>>;
98
- baseUrl?: string;
99
- route: string[];
100
- method: HTTPMethod;
101
- data: T;
102
- constructor(config?: RequestConfigBasic);
103
- /**
104
- * Returns the full URL of the request, including the base url,
105
- * routes, and query parameters.
106
- *
107
- * ```ts
108
- * console.log(request.fullUrl())// https://example.com/foo?bar=baz?array=1,2,3
109
- * ```
110
- *
111
- * Note characters may be converted to escape codes. I.e (space => %20) and (comma => %2C)
112
- *
113
- * N.B this getter estimates what the url will be. The actual value
114
- * might be different depending on your underlying HTTPClient and
115
- * configuration. For example, query parameters might
116
- * use different array formats.
117
- */
118
- get fullUrl(): string;
119
- /**
120
- * Returns a new independent copy of the request.
121
- */
122
- static derive(original: HTTPRequest<unknown>): HTTPRequest<unknown>;
123
- }
124
- declare class HTTPRequestBuilder<T extends HTTPRequest<unknown>> {
125
- #private;
126
- constructor(request?: T | (() => T));
127
- static create<T extends HTTPRequest<unknown>>(): HTTPRequestBuilder<T>;
128
- get request(): T;
129
- resolveDynamicHeaders(request?: HTTPRequest<T>): Promise<this>;
130
- url(url: string): this;
131
- route(...route: string[]): this;
132
- param(name: string, value: string | number | boolean | (string | number | boolean)[] | Record<string, string | number | boolean>): this;
133
- params(dict: Record<string, unknown>): this;
134
- data<T>(data: T): this;
135
- header(name: string, value: string | number | boolean | null | (string | number | boolean)[] | (() => string | number | boolean | null) | (() => Promise<string | number | boolean | null>), onArray?: (value: (string | number | boolean)[]) => string): this;
136
- headers(dict: Record<string, string>): this;
137
- get(): T;
138
- method(method: HTTPMethod): this;
139
- derive(): HTTPRequestBuilder<T>;
140
- build(): HTTPRequest<T>;
141
- buildAsync(): Promise<HTTPRequest<T>>;
142
- }
143
-
144
- declare let defaultClient: Class<HTTPClient>;
145
- declare abstract class HTTPClient {
146
- static Use(): (target: Class<HTTPClient>) => void;
147
- abstract request<TRequestType, TResponseType>(request: HTTPRequest<TRequestType>, options?: HTTPAdditionalOptions<unknown>): Promise<HTTPResponse<TResponseType>>;
148
- }
149
-
150
- declare class AxiosClient extends HTTPClient {
151
- request<TRequestType, TResponseType>(request: HTTPRequest<TRequestType>, options: HTTPAdditionalOptions<AxiosRequestConfig>): Promise<HTTPResponse<TResponseType>>;
152
- }
153
-
154
- declare class SchemaMap {
155
- #private;
156
- constructor(map?: Map<StatusCode, SchemaParser> | SchemaMap);
157
- derive(): SchemaMap;
158
- registerStatus(parser: SchemaParser, ...codes: StatusCode[]): void;
159
- registerRange(parser: SchemaParser, from: StatusCode, to: StatusCode): void;
160
- validate(status: StatusCode, data: unknown, requireSchema: boolean): unknown;
161
- getParser(status: StatusCode, requireSchema: boolean): SchemaParser;
162
- toObject(): Record<StatusCode<{
163
- readonly CONTINUE: {
164
- readonly status: 100;
165
- readonly statusText: "Continue";
166
- };
167
- readonly SWITCHING_PROTOCOLS: {
168
- readonly status: 101;
169
- readonly statusText: "Switching Protocols";
170
- };
171
- readonly PROCESSING: {
172
- readonly status: 102;
173
- readonly statusText: "Processing";
174
- };
175
- readonly OK: {
176
- readonly status: 200;
177
- readonly statusText: "OK";
178
- };
179
- readonly CREATED: {
180
- readonly status: 201;
181
- readonly statusText: "Created";
182
- };
183
- readonly ACCEPTED: {
184
- readonly status: 202;
185
- readonly statusText: "Accepted";
186
- };
187
- readonly NON_AUTHORITATIVE_INFORMATION: {
188
- readonly status: 203;
189
- readonly statusText: "Non Authoritative Information";
190
- };
191
- readonly NO_CONTENT: {
192
- readonly status: 204;
193
- readonly statusText: "No Content";
194
- };
195
- readonly RESET_CONTENT: {
196
- readonly status: 205;
197
- readonly statusText: "Reset Content";
198
- };
199
- readonly PARTIAL_CONTENT: {
200
- readonly status: 206;
201
- readonly statusText: "Partial Content";
202
- };
203
- readonly MULTI_STATUS: {
204
- readonly status: 207;
205
- readonly statusText: "Multi-Status";
206
- };
207
- readonly MULTIPLE_CHOICES: {
208
- readonly status: 300;
209
- readonly statusText: "Multiple Choices";
210
- };
211
- readonly MOVED_PERMANENTLY: {
212
- readonly status: 301;
213
- readonly statusText: "Moved Permanently";
214
- };
215
- readonly MOVED_TEMPORARILY: {
216
- readonly status: 302;
217
- readonly statusText: "Moved Temporarily";
218
- };
219
- readonly SEE_OTHER: {
220
- readonly status: 303;
221
- readonly statusText: "See Other";
222
- };
223
- readonly NOT_MODIFIED: {
224
- readonly status: 304;
225
- readonly statusText: "Not Modified";
226
- };
227
- readonly USE_PROXY: {
228
- readonly status: 305;
229
- readonly statusText: "Use Proxy";
230
- };
231
- readonly TEMPORARY_REDIRECT: {
232
- readonly status: 307;
233
- readonly statusText: "Temporary Redirect";
234
- };
235
- readonly PERMANENT_REDIRECT: {
236
- readonly status: 308;
237
- readonly statusText: "Permanent Redirect";
238
- };
239
- readonly BAD_REQUEST: {
240
- readonly status: 400;
241
- readonly statusText: "Bad Request";
242
- };
243
- readonly UNAUTHORIZED: {
244
- readonly status: 401;
245
- readonly statusText: "Unauthorized";
246
- };
247
- readonly PAYMENT_REQUIRED: {
248
- readonly status: 402;
249
- readonly statusText: "Unauthorized";
250
- };
251
- readonly FORBIDDEN: {
252
- readonly status: 403;
253
- readonly statusText: "Forbidden";
254
- };
255
- readonly NOT_FOUND: {
256
- readonly status: 404;
257
- readonly statusText: "Not Found";
258
- };
259
- readonly METHOD_NOT_ALLOWED: {
260
- readonly status: 405;
261
- readonly statusText: "Method Not Allowed";
262
- };
263
- readonly NOT_ACCEPTABLE: {
264
- readonly status: 406;
265
- readonly statusText: "Not Acceptable";
266
- };
267
- readonly PROXY_AUTHENTICATION_REQUIRED: {
268
- readonly status: 407;
269
- readonly statusText: "Proxy Authentication Required";
270
- };
271
- readonly REQUEST_TIMEOUT: {
272
- readonly status: 408;
273
- readonly statusText: "Request Timeout";
274
- };
275
- readonly CONFLICT: {
276
- readonly status: 409;
277
- readonly statusText: "Conflict";
278
- };
279
- readonly GONE: {
280
- readonly status: 410;
281
- readonly statusText: "Gone";
282
- };
283
- readonly LENGTH_REQUIRED: {
284
- readonly status: 411;
285
- readonly statusText: "Length Required";
286
- };
287
- readonly PRECONDITION_FAILED: {
288
- readonly status: 412;
289
- readonly statusText: "Precondition Failed";
290
- };
291
- readonly REQUEST_TOO_LONG: {
292
- readonly status: 413;
293
- readonly statusText: "Request Entity Too Large";
294
- };
295
- readonly REQUEST_URI_TOO_LONG: {
296
- readonly status: 414;
297
- readonly statusText: "Request-URI Too Long";
298
- };
299
- readonly UNSUPPORTED_MEDIA_TYPE: {
300
- readonly status: 415;
301
- readonly statusText: "Unsupported Media Type";
302
- };
303
- readonly REQUESTED_RANGE_NOT_SATISFIABLE: {
304
- readonly status: 416;
305
- readonly statusText: "Requested Range Not Satisfiable";
306
- };
307
- readonly EXPECTATION_FAILED: {
308
- readonly status: 417;
309
- readonly statusText: "Expectation Failed";
310
- };
311
- readonly IM_A_TEAPOT: {
312
- readonly status: 418;
313
- readonly statusText: "I'm a teapot";
314
- };
315
- readonly INSUFFICIENT_SPACE_ON_RESOURCE: {
316
- readonly status: 419;
317
- readonly statusText: "Insufficient Space on Resource";
318
- };
319
- readonly METHOD_FAILURE: {
320
- readonly status: 420;
321
- readonly statusText: "Method Failure";
322
- };
323
- readonly MISDIRECTED_REQUEST: {
324
- readonly status: 421;
325
- readonly statusText: "Misdirected Request";
326
- };
327
- readonly UNPROCESSABLE_ENTITY: {
328
- readonly status: 422;
329
- readonly statusText: "Unprocessable Entity";
330
- };
331
- readonly LOCKED: {
332
- readonly status: 423;
333
- readonly statusText: "Unprocessable Entity";
334
- };
335
- readonly FAILED_DEPENDENCY: {
336
- readonly status: 424;
337
- readonly statusText: "Failed Dependency";
338
- };
339
- readonly PRECONDITION_REQUIRED: {
340
- readonly status: 428;
341
- readonly statusText: "Precondition Failed";
342
- };
343
- readonly TOO_MANY_REQUESTS: {
344
- readonly status: 429;
345
- readonly statusText: "Too Many Requests";
346
- };
347
- readonly REQUEST_HEADER_FIELDS_TOO_LARGE: {
348
- readonly status: 431;
349
- readonly statusText: "Request Header Fields Too Large";
350
- };
351
- readonly UNAVAILABLE_FOR_LEGAL_REASONS: {
352
- readonly status: 451;
353
- readonly statusText: "Unavailable For Legal Reasons";
354
- };
355
- readonly INTERNAL_SERVER_ERROR: {
356
- readonly status: 500;
357
- readonly statusText: "Internal Server Error";
358
- };
359
- readonly NOT_IMPLEMENTED: {
360
- readonly status: 501;
361
- readonly statusText: "Not Implemented";
362
- };
363
- readonly BAD_GATEWAY: {
364
- readonly status: 502;
365
- readonly statusText: "Bad Gateway";
366
- };
367
- readonly SERVICE_UNAVAILABLE: {
368
- readonly status: 503;
369
- readonly statusText: "Service Unavailable";
370
- };
371
- readonly GATEWAY_TIMEOUT: {
372
- readonly status: 504;
373
- readonly statusText: "Bad Gateway";
374
- };
375
- readonly HTTP_VERSION_NOT_SUPPORTED: {
376
- readonly status: 505;
377
- readonly statusText: "HTTP Version Not Supported";
378
- };
379
- readonly INSUFFICIENT_STORAGE: {
380
- readonly status: 507;
381
- readonly statusText: "Insufficient Storage";
382
- };
383
- readonly NETWORK_AUTHENTICATION_REQUIRED: {
384
- readonly status: 511;
385
- readonly statusText: "Network Authentication Required";
386
- };
387
- }>, SchemaParser>;
388
- }
389
-
390
- interface SchemaConfig {
391
- schemas: SchemaMap;
392
- requireSchema: boolean;
393
- allowPlainText: boolean;
394
- }
395
- interface HTTPHooks {
396
- onSend: [string, RequestHook][];
397
- onReceive: [string, ResponseHook<unknown>][];
398
- }
399
- declare class MetaConfig implements SchemaConfig, HTTPHooks {
400
- schemas: SchemaMap;
401
- requireSchema: boolean;
402
- allowPlainText: boolean;
403
- onSend: [string, RequestHook][];
404
- onReceive: [string, ResponseHook<unknown>][];
405
- throwOnServerError: boolean;
406
- options: HTTPAdditionalOptions<unknown>;
407
- }
408
- declare class MetaConfigBuilder {
409
- #private;
410
- options(options: HTTPAdditionalOptions<unknown>): this;
411
- schemaMap(map: SchemaMap): this;
412
- schema(parser: SchemaParser, ...codes: StatusCode[]): MetaConfigBuilder;
413
- schema(parser: SchemaParser, ...range: {
414
- from: StatusCode;
415
- to: StatusCode;
416
- }[]): MetaConfigBuilder;
417
- schema(parser: SchemaParser, ...args: (StatusCode | {
418
- from: StatusCode;
419
- to: StatusCode;
420
- })[]): MetaConfigBuilder;
421
- requireSchema(value: boolean): this;
422
- allowPlainText(value: boolean): this;
423
- onBeforeSend(description: string, hook: RequestHook): this;
424
- throwOnServerError(value: boolean): this;
425
- onReceiveResponse(description: string, hook: ResponseHook<unknown>): this;
426
- build(): MetaConfig;
427
- derive(): MetaConfigBuilder;
428
- }
429
-
430
- /**
431
- * The HTTP fixture allows requests to be built and sent to a server. In general,
432
- * there are 2 modes of operation:
433
- *
434
- * * Shared Chain: The shared chain is used to configure the client for all requests, such as
435
- * routes this instance will always be used. When a shared chain method is called, it returns
436
- * the same instance of HTTP which can be further chained to configure the client.
437
- * * Request Chain: The request chain is used to configure a single request, inheriting values
438
- * set by the shared chain. When called, a new HTTP client instance is created and inherits the values
439
- * set by it's parent.
440
- *
441
- * The 2 modes are intended to simplify configuring an object through an inheritance chain. For example,
442
- * assume we have an API with 2 controller routes, `/product` and `/seller`. We can set up a Base Client
443
- * which consumes the HTTP fixture and configures it with the base url of our API.
444
- *
445
- * Inheritors can further configure their HTTP instance's routes.
446
- *
447
- * ```ts
448
- * \@Constructor(HTTP)
449
- * export class BaseClient {
450
- * constructor(protected readonly http: HTTP) {
451
- * this.http.url("https://api.example.com");
452
- * }
453
- * }
454
- *
455
- * export class ProductClient extends BaseClient {
456
- * constructor(http: HTTP) {
457
- * super(http);
458
- * this.http.sharedRoute("product");
459
- * }
460
- * getProduct(id: number) {
461
- * return this.http.route(id).get();
462
- * }
463
- *
464
- * export class SellerClient extends BaseClient {
465
- * constructor(http: HTTP) {
466
- * super(http);
467
- * this.http.sharedRoute("seller");
468
- * }
469
- *
470
- * getSeller(id: number) {
471
- * return this.http.route(id).get();
472
- * }
473
- * }
474
- * ```
475
- *
476
- * 'Schemas' can also be configured. A Schema is a function or an object with a `parse` method, which
477
- * takes a response data payload and returns a validated object. Schemas are mapped to
478
- * HTTP Status Codes, and if configured to be required the request will fail if no schema is found
479
- * matching that code.
480
- *
481
- * Defining a schema function:
482
- *
483
- * ```
484
- * // user.schema.ts
485
- * export function UserSchema(data: unknown) {
486
- * if(typeof data !== "object") {
487
- * throw new Error("Expected an object");
488
- * }
489
- *
490
- * if(typeof data.name !== "string") {
491
- * throw new Error("Expected a string");
492
- * }
493
- *
494
- * return data as { name: string };
495
- * }
496
- *
497
- * // user.controller.ts
498
- * \@Fixture(INJECTION_SCOPE.TRANSIENT)
499
- * export class UserController extends BaseController {
500
- * constructor(private readonly http: HTTP) {
501
- * super(http);
502
- * this.http
503
- * .sharedRoute("user")
504
- * .sharedSchema(ErrorSchema, { from: 400, to: 499 });
505
- * }
506
- *
507
- * getUser(id: number) {
508
- * return this.http.route(id).schema(UserSchema, 200).get();
509
- * // or
510
- * return this.http
511
- * .route(id)
512
- * .schema(UserSchema, { from: 200, to: 299 })
513
- * .get();
514
- * // or
515
- * return this.http
516
- * .route(id)
517
- * .schema(UserSchema, 200, 201, 202)
518
- * .get();
519
- * }
520
- * }
521
- * ```
522
- *
523
- * Validation libraries which use a `.parse` or `.validation`, method, such as Zod or MyZod, can also be used as schemas:
524
- *
525
- * ```ts
526
- * // user.schema.ts
527
- * import { z } from "myzod";
528
- *
529
- * export const UserSchema = z.object({
530
- * name: z.string()
531
- * });
532
- *
533
- * // user.controller.ts
534
- * \@Fixture(INJECTION_SCOPE.TRANSIENT)
535
- * export class UserController extends BaseController {
536
- * constructor(private readonly http: HTTP) {
537
- * super(http);
538
- * this.http
539
- * .sharedRoute("user")
540
- * .sharedSchema(ErrorSchema, { from: 400, to: 499 })
541
- * }
542
- *
543
- * getUser(id: number) {
544
- * return this.http.route(id).schema(UserSchema, 200).get();
545
- * }
546
- * }
547
- * ```
548
- */
549
- declare class HTTP {
550
- #private;
551
- private readonly client;
552
- constructor(client?: HTTPClient, builder?: HTTPRequestBuilder<HTTPRequest<unknown>>, metaConfig?: MetaConfigBuilder);
553
- static create(client?: HTTPClient, builder?: HTTPRequestBuilder<HTTPRequest<unknown>>, metaConfig?: MetaConfigBuilder): HTTP;
554
- /**
555
- * Sets the base url of the request for this client, such as
556
- * `https://api.example.com`, and could include always-used routes like
557
- * the api version, such as `/v1` or `/api/v1` at the end.
558
- *
559
- * ```ts
560
- *
561
- * \@Fixture(INJECTION_SCOPE.TRANSIENT)
562
- * export abstract class BaseClient {
563
- * constructor(protected readonly http: HTTP) {
564
- * this.http.url("https://api.example.com");
565
- * }
566
- * }
567
- * ```
568
- * @param url
569
- * @returns
570
- */
571
- url(url: string): this;
572
- sharedOptions(options: HTTPAdditionalOptions<unknown>): this;
573
- /**
574
- * If set to true, all requests derived from this client will require a schema be defined
575
- * matching any response status code. If set to false, a schema will still be used for validation
576
- * if defined, or the unadulterated original body will be returned if no schema matches.
577
- *
578
- * @param required Whether or not a schema is required for all responses.
579
- * @returns This instance of HTTP.
580
- */
581
- requireSchema(required: boolean): this;
582
- /**
583
- * If set to true, all requests derived from this client will allow plain text
584
- * responses. If set to false, plain text responses will throw an serialization error.
585
- *
586
- * Useful when an endpoint returns a HTML or plain text response. If the plain text
587
- * is the value of `true` or `false`, or a number, it will be parsed into the
588
- * appropriate type.
589
- *
590
- * This method is a shared chain method, and will return the same instance of HTTP.
591
- *
592
- * @param allow Whether or not plain text responses are allowed.
593
- * @returns This instance of HTTP.
594
- */
595
- sharedAllowPlainText(allow: boolean): this;
596
- /**
597
- * If set to true, all requests derived from this client will allow plain text
598
- * responses. If set to false, plain text responses will throw an serialization error.
599
- *
600
- * Useful when an endpoint returns a HTML or plain text response. If the plain text
601
- * is the value of `true` or `false`, or a number, it will be parsed into the
602
- * appropriate type.
603
- *
604
- * This method is a request chain method, and will return a new instance of HTTP.
605
- *
606
- * @param allow Whether or not plain text responses are allowed.
607
- * @returns A new child instance of HTTP derived from this one.
608
- */
609
- allowPlainText(allow: boolean): HTTP;
610
- /**
611
- * Attaches a route to the request, such as `/product` or `/user`. Subsequent calls
612
- * to this method will append the route to the existing route, such as `/product/1`.
613
- *
614
- * Numbers will be converted to strings automatically. Routes can be defined one
615
- * at a time or as a spread argument.
616
- *
617
- * ```ts
618
- * constructor(http: HTTP) {
619
- * super(http);
620
- * this.http.sharedRoute("user", id).get();
621
- * }
622
- *
623
- * // or
624
- *
625
- * constructor(http: HTTP) {
626
- * super(http);
627
- * this.http
628
- * .sharedRoute("user")
629
- * .sharedRoute(id)
630
- * .get();
631
- * }
632
- * ```
633
- *
634
- * This method is a shared chain method, and will return the same instance of HTTP. All
635
- * child clients will inherit the routes defined by this method. Useful to configure
636
- * in the constructor body.
637
- *
638
- * @param route A route or spread list of routes to append to the request.
639
- * @returns This instance of HTTP.
640
- */
641
- sharedRoute(...route: (string | number | boolean)[]): this;
642
- /**
643
- * Attaches a route to the request, such as `/product` or `/user`. Subsequent calls
644
- * to this method will append the route to the existing route, such as `/product/1`.
645
- *
646
- * Numbers will be converted to strings automatically. Routes can be defined one
647
- * at a time or as a spread argument.
648
- *
649
- * ```ts
650
- * getUser(id: number) {
651
- * return this.http.route("user", id).get();
652
- * }
653
- *
654
- * // or
655
- *
656
- * getUser(id: number) {
657
- * return this.http
658
- * .route("user")
659
- * .route(id)
660
- * .get();
661
- * }
662
- * ```
663
- *
664
- * This method is a request chain method, and will return a new instance of HTTP, inheriting
665
- * any routes previously defined and appending the new route. Useful to configure
666
- * in class methods as part of finalizing a request.
667
- *
668
- * @param route A route or spread list of routes to append to the request.
669
- * @returns A new child instance of HTTP derived from this one.
670
- */
671
- route(...route: (string | number | boolean)[]): HTTP;
672
- /**
673
- * Attaches a shared schema mapping for all requests by this client. Schemas are
674
- * mapped to HTTP Status Codes, and if configured to be required the request will fail
675
- * if no schema is found matching that code.
676
- *
677
- * The status code mapping can be defined as a single code, a range of codes, or a spread list.
678
- *
679
- * ```ts
680
- * \@Fixture(INJECTION_SCOPE.TRANSIENT)
681
- * export class UserController extends BaseController {
682
- * constructor(private readonly http: HTTP) {
683
- * super(http);
684
- * this.http
685
- * .sharedRoute("user")
686
- * .sharedSchema(UserSchema, 200)
687
- * .sharedSchema(EmptySchema, 201, 204)
688
- * .sharedSchema(ErrorSchema, { from: 400, to: 499 });
689
- * }
690
- * }
691
- * ```
692
- *
693
- * This method is a shared chain method, and will return the same instance of HTTP. All
694
- * child clients will inherit the schemas defined by this method. Useful to configure
695
- * in the constructor body.
696
- *
697
- * @param parser The schema parser to use for this mapping.
698
- * @param codes A single status code, a range of status codes, or a spread list of status codes.
699
- * @returns This instance of HTTP.
700
- */
701
- sharedSchema(parser: SchemaParser, ...codes: StatusCode[]): HTTP;
702
- sharedSchema(parser: SchemaParser, ...range: {
703
- from: StatusCode;
704
- to: StatusCode;
705
- }[]): HTTP;
706
- /**
707
- * Attaches a schema mapping for this request. Schemas are
708
- * mapped to HTTP Status Codes, and if configured to be required the request will fail
709
- * if no schema is found matching that code.
710
- *
711
- * The status code mapping can be defined as a single code, a range of codes, or a spread list.
712
- *
713
- * ```ts
714
- * \@Fixture(INJECTION_SCOPE.TRANSIENT)
715
- * export class UserController extends BaseController {
716
- * constructor(private readonly http: HTTP) {
717
- * super(http);
718
- * this.http
719
- * .sharedRoute("user")
720
- * .schema(ErrorSchema, { from: 400, to: 499 });
721
- * }
722
- *
723
- * getUser(id: number) {
724
- * return this.http.route(id).schema(UserSchema, 200).get();
725
- * }
726
- *
727
- * getUsers(...ids: number[]) {
728
- * return this.http
729
- * .route("users")
730
- * .schema(UserSchema, { from: 200, to: 299 })
731
- * .schema(UserSchema, 200)
732
- * .get();
733
- * }
734
- * ```
735
- *
736
- * This method is a request chain method, and will return a new instance of HTTP, inheriting
737
- * any schemas previously defined and appending the new schema. Useful to configure
738
- * in class methods as part of finalizing a request.
739
- *
740
- * @param parser The schema parser to use for this mapping.
741
- * @param codes A single status code, a range of status codes, or a spread list of status codes.
742
- * @returns A new child instance of HTTP derived from this one.
743
- */
744
- schema(parser: SchemaParser, ...codes: StatusCode[]): HTTP;
745
- schema(parser: SchemaParser, ...range: {
746
- from: StatusCode;
747
- to: StatusCode;
748
- }[]): HTTP;
749
- /**
750
- * Attaches a shared query string parameter to all requests by this client. Query string
751
- * parameters are key-value pairs which are appended to the request url, such as
752
- * `https://api.example.com?name=John&age=30`.
753
- *
754
- * This method is a shared chain method, and will return the same instance of HTTP. All
755
- * child clients will inherit the query string parameters defined by this method. Useful to configure
756
- * in the constructor body.
757
- *
758
- * @param name The name of the query string parameter.
759
- * @param value The value of the query string parameter.
760
- * @returns This instance of HTTP.
761
- */
762
- sharedParam(name: string, value: Record<string, unknown>): HTTP;
763
- sharedParam(name: string, ...value: (string | number | boolean)[]): HTTP;
764
- sharedParam(name: string, value: (string | number | boolean)[]): HTTP;
765
- /**
766
- * `onSend` is a pre-request hook which will be executed in order of definition
767
- * immediately before the request is sent. This hook can be used to analyze or
768
- * log the request state.
769
- *
770
- * ```ts
771
- *
772
- * \@Fixture(INJECTION_SCOPE.TRANSIENT)
773
- * export class UserController extends BaseController {
774
- * constructor(private readonly http: HTTP) {
775
- * super(http);
776
- * this.http
777
- * .sharedRoute("user")
778
- * .sharedOnSend("log request",
779
- * (request) => console.log(JSON.stringify(request, null, 2))
780
- * );
781
- * }
782
- * }
783
- * ```
784
- *
785
- * This method is a shared chain method, and will return the same instance of HTTP. All
786
- * child clients will inherit the onSend hooks defined by this method. Useful to configure
787
- * in the constructor body.
788
- *
789
- * @param description A description of the hook, used for debugging.
790
- * @param hook The hook to execute.
791
- * @returns This instance of HTTP.
792
- */
793
- sharedOnSend(description: string, hook: RequestHook): this;
794
- /**
795
- * `onReceive` is a post-request hook which will be executed in order of definition
796
- * immediately after the response is received. This hook can be used to analyze or
797
- * log the response state.
798
- *
799
- * ```ts
800
- *
801
- * \@Fixture(INJECTION_SCOPE.TRANSIENT)
802
- * export class UserController extends BaseController {
803
- * constructor(private readonly http: HTTP) {
804
- * super(http);
805
- * this.http
806
- * .sharedRoute("user")
807
- * .sharedOnReceive("log response",
808
- * (response) => console.log(JSON.stringify(response, null, 2))
809
- * );
810
- * }
811
- * }
812
- * ```
813
- *
814
- * This method is a shared chain method, and will return the same instance of HTTP. All
815
- * child clients will inherit the onReceive hooks defined by this method. Useful to configure
816
- * in the constructor body.
817
- *
818
- * @param description A description of the hook, used for debugging.
819
- * @param hook The hook to execute.
820
- * @returns This instance of HTTP.
821
- */
822
- sharedOnReceive(description: string, hook: ResponseHook<unknown>): this;
823
- /**
824
- * Attaches a query string parameter object to the request. Query string
825
- * parameters are key-value pairs which are appended to the request url, such as
826
- * `https://api.example.com?name=John&age=30`.
827
- *
828
- * This method is a shared chain method, and will return the same instance of HTTP. All
829
- * child clients will inherit the query string parameters defined by this method. Useful to configure
830
- * in the constructor body.
831
- *
832
- * ```ts
833
- * constructor(http: HTTP) {
834
- * super(http);
835
- * this.http
836
- * .sharedParams({ 'is-test': "true" })
837
- * ```
838
- * @param name The name of the query string parameter.
839
- * @param value The value of the query string parameter.
840
- * @returns This instance of HTTP.
841
- */
842
- sharedParams(dict: Record<string, unknown>): this;
843
- /**
844
- * Attaches a query string parameter to the request. Query string
845
- * parameters are key-value pairs which are appended to the request url, such as
846
- * `https://api.example.com?name=John&age=30`.
847
- *
848
- * This method is a request chain method, and will return a new instance of HTTP, inheriting
849
- * any query string parameters previously defined and appending the new parameter. Useful to configure
850
- * in class methods as part of finalizing a request.
851
- *
852
- * ```ts
853
- * getUser(id: number) {
854
- * return this.http
855
- * .route(id)
856
- * .param("name", "John")
857
- * .param("age", 30)
858
- * ```
859
- *
860
- * Note: Numbers and Booleans will be converted to strings automatically.
861
- *
862
- * @param name The name of the query string parameter.
863
- * @param value The value of the query string parameter.
864
- * @returns A new child instance of HTTP derived from this one.
865
- */
866
- param(name: string, value: Record<string, unknown>): HTTP;
867
- param(name: string, ...value: (string | number | boolean)[]): HTTP;
868
- param(name: string, value: (string | number | boolean)[]): HTTP;
869
- /**
870
- * Attaches a query string parameter object to the request. Query string
871
- * parameters are key-value pairs which are appended to the request url, such as
872
- * `https://api.example.com?name=John&age=30`.
873
- *
874
- * This method is a shared chain method, and will return the same instance of HTTP. All
875
- * child clients will inherit the query string parameters defined by this method. Useful to configure
876
- * in the constructor body.
877
- *
878
- * ```ts
879
- * getUser(id: number) {
880
- * return this.http
881
- * .route(id)
882
- * .param({ name: "John", age: "30" })
883
- *
884
- * @param name The name of the query string parameter.
885
- * @param value The value of the query string parameter.
886
- * @returns This instance of HTTP.
887
- */
888
- params(dict: Record<string, unknown>): HTTP;
889
- /**
890
- * Attaches a shared data payload to this client. The data payload is the body of the request,
891
- * and can be any type. If the data payload is an object, it will be serialized to JSON.
892
- *
893
- * This method is a shared chain method, and will return the same instance of HTTP. All
894
- * child clients will inherit the data payload defined by this method. Useful to configure
895
- * in the constructor body.
896
- *
897
- * @param data The data payload to attach to the request.
898
- * @returns This instance of HTTP.
899
- */
900
- sharedData<T>(data: T): this;
901
- /**
902
- * Attaches a shared header to this client. Headers are string:string key-value pairs which are
903
- * sent with the request, such as `Content-Type: application/json`.
904
- *
905
- * Numbers, Booleans and Null will be converted to string values automatically.
906
- *
907
- * A Factory function can also be provided to generate the header value at the time of request.
908
- *
909
- * This method is a shared chain method, and will return the same instance of HTTP. All
910
- * child clients will inherit the header defined by this method. Useful to configure
911
- * in the constructor body.
912
- *
913
- * @param name The name of the header.
914
- * @param value The value of the header.
915
- */
916
- sharedHeader(name: string, value: string | number | boolean | null | (string | number | boolean)[] | (() => string | number | boolean | null) | (() => Promise<string | number | boolean | null>)): this;
917
- header(name: string, value: string | number | boolean | null | (string | number | boolean)[] | (() => string | number | boolean | null) | (() => Promise<string | number | boolean | null>)): HTTP;
918
- /**
919
- * Attaches a data payload to this request. The data payload is the body of the request,
920
- * and can be any type. If the data payload is an object, it will be serialized to JSON.
921
- *
922
- * This method is a request chain method, and will return a new instance of HTTP, inheriting
923
- * any data payload previously defined and appending the new payload. Useful to configure
924
- * in class methods as part of finalizing a request.
925
- *
926
- * @param data The data payload to attach to the request.
927
- * @returns A new child instance of HTTP derived from this one.
928
- */
929
- data<T>(data: T): HTTP;
930
- /**
931
- * `onSend` is a pre-request hook which will be executed in order of definition
932
- * immediately before the request is sent. This hook can be used to modify the request,
933
- * or to log the state of a request before final send-off.
934
- *
935
- * ```ts
936
- *
937
- * \@Fixture(INJECTION_SCOPE.TRANSIENT)
938
- * export class UserController extends BaseController {
939
- * constructor(private readonly http: HTTP) {
940
- * super(http);
941
- * }
942
- *
943
- * getUser(id: number) {
944
- * return this.http
945
- * .route(id)
946
- * .onSend("log request",
947
- * (request) => console.log(JSON.stringify(request, null, 2)
948
- * )
949
- * .get();
950
- * }
951
- * ```
952
- *
953
- * This method is a request chain method, and will return a new instance of HTTP, inheriting
954
- * any onSend hooks previously defined and appending the new hook. Useful to configure
955
- * in class methods as part of finalizing a request.
956
- *
957
- * @param description A description of the hook, used for debugging.
958
- * @param hook The hook to execute.
959
- * @returns A new child instance of HTTP derived from this one.
960
- */
961
- onSend(description: string, hook: RequestHook): HTTP;
962
- /**
963
- * `onReceive` is a post-request hook which will be executed in order of definition
964
- * immediately after the response is received. This hook can be used to modify the response,
965
- * or to log the state of a response after it is received.
966
- *
967
- * ```ts
968
- *
969
- * \@Fixture(INJECTION_SCOPE.TRANSIENT)
970
- * export class UserController extends BaseController {
971
- * constructor(private readonly http: HTTP) {
972
- * super(http);
973
- * }
974
- *
975
- * getUser(id: number) {
976
- * return this.http
977
- * .route(id)
978
- * .onReceive("log response",
979
- * (response) => console.log(JSON.stringify(response, null, 2)
980
- * )
981
- * .get();
982
- * }
983
- * ```
984
- *
985
- * This method is a request chain method, and will return a new instance of HTTP, inheriting
986
- * any onReceive hooks previously defined and appending the new hook. Useful to configure
987
- * in class methods as part of finalizing a request.
988
- *
989
- * @param description A description of the hook, used for debugging.
990
- * @param hook The hook to execute.
991
- * @returns A new child instance of HTTP derived from this one.
992
- */
993
- onReceive(description: string, hook: ResponseHook<unknown>): HTTP;
994
- /**
995
- * Executes the current request state as a GET request.
996
- *
997
- * @param options Additional options to pass to the underlying http client, such
998
- * as e.g Axios configuration values.
999
- * @returns A promise which resolves to the response.
1000
- */
1001
- get<TResponseType>(options?: HTTPAdditionalOptions<unknown>): Promise<HTTPResponse<TResponseType>>;
1002
- /**
1003
- * Executes the current request state as a POST request.
1004
- *
1005
- * @param data The data payload to attach to the request.
1006
- * @param options Additional options to pass to the underlying http client, such
1007
- * as e.g Axios configuration values.
1008
- * @returns A promise which resolves to the response.
1009
- */
1010
- post<TResponseType>(options?: HTTPAdditionalOptions<unknown>): Promise<HTTPResponse<TResponseType>>;
1011
- /**
1012
- * Executes the current request state as a DELETE request.
1013
- *
1014
- * @param options Additional options to pass to the underlying http client, such
1015
- * as e.g Axios configuration values.
1016
- * @returns A promise which resolves to the response.
1017
- * as e.g Axios configuration values.
1018
- */
1019
- delete<TResponseType>(options?: HTTPAdditionalOptions<unknown>): Promise<HTTPResponse<TResponseType>>;
1020
- /**
1021
- * Executes the current request state as a PUT request.
1022
- *
1023
- * @param options Additional options to pass to the underlying http client, such
1024
- * as e.g Axios configuration values.
1025
- * @returns A promise which resolves to the response.
1026
- */
1027
- put<TResponseType>(options?: HTTPAdditionalOptions<unknown>): Promise<HTTPResponse<TResponseType>>;
1028
- /**
1029
- * Executes the current request state as a PATCH request.
1030
- *
1031
- * @param options Additional options to pass to the underlying http client, such
1032
- * as e.g Axios configuration values.
1033
- * @returns A promise which resolves to the response.
1034
- */
1035
- patch<TResponseType>(options?: HTTPAdditionalOptions<unknown>): Promise<HTTPResponse<TResponseType>>;
1036
- head<TResponseType>(options?: HTTPAdditionalOptions<unknown>): Promise<HTTPResponse<TResponseType>>;
1037
- options<TResponseType>(options?: HTTPAdditionalOptions<unknown>): Promise<HTTPResponse<TResponseType>>;
1038
- trace<TResponseType>(options?: HTTPAdditionalOptions<unknown>): Promise<HTTPResponse<TResponseType>>;
1039
- connect<TResponseType>(options?: HTTPAdditionalOptions<unknown>): Promise<HTTPResponse<TResponseType>>;
1040
- private runOnSendHooks;
1041
- private runOnReceiveHooks;
1042
- }
1043
-
1044
- /**
1045
- * Schema which does not care about data validation.
1046
- *
1047
- * Useful if `requireSchema` is set to true, but a specific
1048
- * endpoints response does not matter.
1049
- * @param data
1050
- * @returns
1051
- */
1052
- declare function AnySchema(data: unknown): unknown;
1053
- /**
1054
- * Schema which validates that a response is empty. This can mean
1055
- * the data payload was `null`, `undefined` or the string `'null'`.
1056
- *
1057
- * Useful if `requireSchema` is set to true, but a specific
1058
- * endpoints response should be null or not defined.
1059
- * @param data
1060
- * @returns
1061
- */
1062
- declare function EmptySchema(data: unknown): null | undefined;
1063
- /**
1064
- * Schema which validates a response was null.
1065
- *
1066
- * Useful if `requireSchema` is set to true, but a specific
1067
- * endpoints response should be null.
1068
- * @param data
1069
- * @returns
1070
- */
1071
- declare function NullSchema(data: unknown): null;
1072
- /**
1073
- * Schema which validates a response was undefined.
1074
- *
1075
- * Useful if `requireSchema` is set to true, but a specific
1076
- * endpoints response should be undefined.
1077
- *
1078
- * @param data
1079
- * @returns
1080
- */
1081
- declare function UndefinedSchema(data: unknown): undefined;
1082
- /**
1083
- * Schema which validates a response was a boolean, or a string of value
1084
- * `'true'` or `'false'`.
1085
- *
1086
- * Useful if `requireSchema` is set to true, but a specific
1087
- * endpoints response should be a boolean.
1088
- *
1089
- * @param data
1090
- * @returns
1091
- */
1092
- declare function BooleanSchema(data: unknown): any;
1093
- /**
1094
- * Schema which validates a response was a number, or a string of value
1095
- * of a number.
1096
- *
1097
- * Useful if `requireSchema` is set to true, but a specific
1098
- * endpoints response should be a number.
1099
- *
1100
- * @param data
1101
- * @returns
1102
- */
1103
- declare function NumberSchema(data: unknown): any;
1104
- /**
1105
- * Schema which validates a response was a string.
1106
- *
1107
- * Useful if `requireSchema` is set to true, but a specific
1108
- * endpoints response should be a string.
1109
- *
1110
- * @param data
1111
- * @returns
1112
- */
1113
- declare function StringSchema(data: unknown): string;
1114
- declare function JSONSchema<T = unknown>(data: unknown): any;
1115
-
1116
- export { AnySchema, AxiosClient, BooleanSchema, EmptySchema, HTTP, HTTPAdditionalOptions, HTTPClient, HTTPMethod, HTTPRequest, HTTPRequestBuilder, HTTPResponse, HTTPResponseBuilder, JSONSchema, NullSchema, NumberSchema, RequestHook, ResponseHook, SchemaParser, StringSchema, UndefinedSchema, defaultClient };
1
+ export { HTTP, type HTTPCreateOptions, HTTPError, HTTPTransportError, HTTPSchemaValidationError, } from "./http";
2
+ export { HTTPRequest, HTTPRequestBuilder, type HeaderPrimitive, type HeaderFactory, type ParamValue, type ParamDictionary, type RequestConfigBasic, } from "./http-request";
3
+ export { HTTPResponse, HTTPResponseBuilder } from "./http-response";
4
+ export { SchemaMap } from "./schema.map";
5
+ export { AnySchema, EmptySchema, NullSchema, UndefinedSchema, BooleanSchema, NumberSchema, StringSchema, JSONSchema, } from "./default-schema";
6
+ export { type HTTPPlugin, type HTTPRequestContext, type HTTPResponseContext, type HTTPErrorContext, type HTTPLogEvent, type HTTPLogSink, createLoggingPlugin, } from "./plugins";
7
+ export { MetaConfig, MetaConfigBuilder } from "./request-meta.config";
8
+ export { createFetchTransport, type FetchLike, type FetchRequestOptions, } from "./fetch-transport";
9
+ export { createAxiosTransport, type AxiosLike, type AxiosRequestConfigLike, type AxiosResponseLike, } from "./axios-transport";
10
+ export { transformResponse } from "./transform-response";
11
+ export { type HTTPTransport, type HTTPTransportResponse, } from "./transport";
12
+ export { httpAssertionsPlugin, type HttpAssertionsFacet, } from "./assertions/http-assertions-plugin";
13
+ export { ensureHttp, type HttpEnsureChain, type HttpResponseLike, type StatusExpectation, type HeaderExpectation, type CacheControlExpectation, } from "./assertions/http-ensure";
14
+ export { fromFetchResponse, fromHttpResponse, } from "./assertions/http-adapters";
15
+ export type { HTTPAdditionalOptions, HTTPMethod, SchemaParser, RequestHook, ResponseHook, StatusCode, HTTPRetryOptions, HTTPRetryPredicate, HTTPRetryContext, } from "./types";