@unshared/client 0.3.2 → 0.3.3

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 (60) hide show
  1. package/dist/chunks/{0ZzUT3m_.js → B6pUErTM.js} +2 -2
  2. package/dist/chunks/B6pUErTM.js.map +1 -0
  3. package/dist/chunks/{CYmaYL5B.cjs → BDxlAULu.cjs} +2 -2
  4. package/dist/chunks/BDxlAULu.cjs.map +1 -0
  5. package/dist/chunks/{CO11DuYE.d.ts → BZ5qrH6f.d.ts} +22 -2
  6. package/dist/chunks/{Biic1J5b.js → B_Gz6Yz8.js} +23 -1
  7. package/dist/chunks/B_Gz6Yz8.js.map +1 -0
  8. package/dist/chunks/{BMbsYNBd.cjs → BdFNzMcu.cjs} +2 -2
  9. package/dist/chunks/{BMbsYNBd.cjs.map → BdFNzMcu.cjs.map} +1 -1
  10. package/dist/chunks/{mHfUAX_g.d.ts → Bs2VarsP.d.ts} +5 -3
  11. package/dist/chunks/{6IxvRpmY.js → Bys4-xE2.js} +2 -2
  12. package/dist/chunks/{6IxvRpmY.js.map → Bys4-xE2.js.map} +1 -1
  13. package/dist/chunks/CS5r-m4U.js +191 -0
  14. package/dist/chunks/CS5r-m4U.js.map +1 -0
  15. package/dist/chunks/CVzmr2NA.cjs +189 -0
  16. package/dist/chunks/CVzmr2NA.cjs.map +1 -0
  17. package/dist/chunks/D1QsGr3A.js +15 -0
  18. package/dist/chunks/D1QsGr3A.js.map +1 -0
  19. package/dist/chunks/{CtW2aMuA.cjs → DEyigyGy.cjs} +23 -1
  20. package/dist/chunks/DEyigyGy.cjs.map +1 -0
  21. package/dist/chunks/DXrQkl1A.cjs +14 -0
  22. package/dist/chunks/DXrQkl1A.cjs.map +1 -0
  23. package/dist/createClient.cjs +4 -3
  24. package/dist/createClient.cjs.map +1 -1
  25. package/dist/createClient.d.ts +8 -6
  26. package/dist/createClient.js +4 -4
  27. package/dist/createClient.js.map +1 -1
  28. package/dist/createService.cjs +3 -3
  29. package/dist/createService.cjs.map +1 -1
  30. package/dist/createService.d.ts +2 -2
  31. package/dist/createService.js +4 -4
  32. package/dist/createService.js.map +1 -1
  33. package/dist/index.cjs +5 -5
  34. package/dist/index.d.ts +2 -2
  35. package/dist/index.js +5 -5
  36. package/dist/openapi.cjs +13 -3
  37. package/dist/openapi.cjs.map +1 -1
  38. package/dist/openapi.d.ts +45 -4
  39. package/dist/openapi.js +11 -1
  40. package/dist/openapi.js.map +1 -1
  41. package/dist/utils.cjs +15 -3
  42. package/dist/utils.cjs.map +1 -1
  43. package/dist/utils.d.ts +114 -8
  44. package/dist/utils.js +21 -8
  45. package/dist/utils.js.map +1 -1
  46. package/dist/websocket.cjs +2 -2
  47. package/dist/websocket.js +2 -2
  48. package/package.json +4 -4
  49. package/dist/chunks/0ZzUT3m_.js.map +0 -1
  50. package/dist/chunks/BUeqbyph.js +0 -114
  51. package/dist/chunks/BUeqbyph.js.map +0 -1
  52. package/dist/chunks/Biic1J5b.js.map +0 -1
  53. package/dist/chunks/CYmaYL5B.cjs.map +0 -1
  54. package/dist/chunks/Cayg8606.cjs +0 -112
  55. package/dist/chunks/Cayg8606.cjs.map +0 -1
  56. package/dist/chunks/CtW2aMuA.cjs.map +0 -1
  57. package/dist/chunks/DJJsADWD.js +0 -9
  58. package/dist/chunks/DJJsADWD.js.map +0 -1
  59. package/dist/chunks/Du_W5H6e.cjs +0 -8
  60. package/dist/chunks/Du_W5H6e.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"createClient.js","sources":["../createClient.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions'\nimport type { Result } from '@unshared/functions/attempt'\nimport type { ServiceOptions } from './createService'\nimport type { OpenAPILike, OpenAPIOptionsMap } from './openapi'\nimport type { RequestOptions } from './utils'\nimport type { ConnectOptions, WebSocketChannel } from './websocket'\nimport { attempt } from '@unshared/functions/attempt'\nimport { fetch } from './utils/fetch'\nimport { request } from './utils/request'\nimport { connect } from './websocket/connect'\n\ntype Data<T extends RequestOptions> = T extends RequestOptions<any, any, any, any, any, any, infer R, any> ? R : unknown\ntype Routes = Record<string, RequestOptions>\ntype Channels = Record<string, ConnectOptions>\n\nexport class Client<T extends Routes = Routes, U extends Channels = Channels> {\n\n /**\n * Create a new client for the application.\n *\n * @param options The options to pass to the client.\n * @example new Client({ baseUrl: 'https://api.example.com' })\n */\n constructor(public options: RequestOptions = {}) {}\n\n /**\n * Fetch a route from the API and return the `Response` object. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\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 */\n public fetch<K extends keyof T & string, V extends T[K]>(route: K, options?: V): Promise<Response> {\n return fetch(route, { ...this.options, ...options })\n }\n\n /**\n * Fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The data from the API.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const data = request('GET /api/product/:id', { data: { id: '1' } })\n */\n public request<K extends keyof T & string, V extends T[K]>(route: K, options?: V): Promise<Data<V>> {\n return request(route, { ...this.options, ...options }) as Promise<Data<V>>\n }\n\n /**\n * Attempt to fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns A result object with either the data or an error.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const { data, error } = requestAttempt('GET /api/product/:id', { data: { id: '1' } })\n * if (error) console.error(error)\n * else console.log(data)\n */\n public requestAttempt<K extends keyof T & string, V extends T[K]>(route: K, options?: V): Promise<Result<Data<V>>> {\n return attempt(() => this.request(route, options))\n }\n\n /**\n * Create a new WebSocket connection to the server with the given path. The connection will\n * automatically reconnect if the connection is closed unexpectedly.\n *\n * @param channel The path to connect to.\n * @param options The options to pass to the connection.\n * @returns The WebSocket connection.\n */\n public connect<P extends keyof U & string, V extends U[P]>(channel: P, options?: V): Awaitable<WebSocketChannel<V>, WebSocketChannel<V>> {\n return connect(channel, { baseUrl: this.options.baseUrl, ...options }) as Awaitable<WebSocketChannel<V>, WebSocketChannel<V>>\n }\n}\n\n/**\n * Create a new type-safe client for the application. The client can be used to fetch data from\n * the API and connect to the server using WebSockets with the given path.\n *\n * @param options The options to pass to the client.\n * @returns The client object with the request method.\n * @example\n * // Create a type-safe client for the application.\n * const client = createClient<[ModuleUser]>()\n *\n * // Fetch the data from the API.\n * const data = await client.request('GET /api/user/:id', { id: '1' })\n *\n * // Use the data from the API.\n * console.log(data) // { id: '1', name: 'John Doe' }\n */\nexport function createClient<T extends OpenAPILike>(options?: ServiceOptions<T>): Client<OpenAPIOptionsMap<T>>\n\n/**\n * Create a new type-safe client for the application. The client can be used to fetch data from\n * the API and connect to the server using WebSockets with the given path.\n *\n * @param options The options to pass to the client.\n * @returns The client object with the request method.\n * @example\n * // Create a type-safe client for the application.\n * const client = createClient<[ModuleUser]>()\n *\n * // Fetch the data from the API.\n * const data = await client.request('GET /api/user/:id', { id: '1' })\n *\n * // Use the data from the API.\n * console.log(data) // { id: '1', name: 'John Doe' }\n */\nexport function createClient<T extends Routes = Routes, V extends Channels = Channels>(options?: RequestOptions): Client<T, V>\nexport function createClient(options?: RequestOptions): Client {\n return new Client(options)\n}\n"],"names":[],"mappings":";;;;;;;AAeO,MAAM,OAAiE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ5E,YAAmB,UAA0B,IAAI;AAA9B,SAAA,UAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWZ,MAAkD,OAAU,SAAgC;AAC1F,WAAA,MAAM,OAAO,EAAE,GAAG,KAAK,SAAS,GAAG,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqB9C,QAAoD,OAAU,SAA+B;AAC3F,WAAA,QAAQ,OAAO,EAAE,GAAG,KAAK,SAAS,GAAG,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAuBhD,eAA2D,OAAU,SAAuC;AACjH,WAAO,QAAQ,MAAM,KAAK,QAAQ,OAAO,OAAO,CAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAW5C,QAAoD,SAAY,SAAkE;AAChI,WAAA,QAAQ,SAAS,EAAE,SAAS,KAAK,QAAQ,SAAS,GAAG,SAAS;AAAA,EAAA;AAEzE;AAqCO,SAAS,aAAa,SAAkC;AACtD,SAAA,IAAI,OAAO,OAAO;AAC3B;"}
1
+ {"version":3,"file":"createClient.js","sources":["../createClient.ts"],"sourcesContent":["import type { Awaitable } from '@unshared/functions'\nimport type { Result } from '@unshared/functions/attempt'\nimport type { ServiceOptions } from './createService'\nimport type { OpenAPILike, OpenAPIOptionsMap } from './openapi'\nimport type { RequestOptions } from './utils'\nimport type { ConnectOptions, WebSocketChannel } from './websocket'\nimport { attempt } from '@unshared/functions/attempt'\nimport { fetch } from './utils/fetch'\nimport { request } from './utils/request'\nimport { connect } from './websocket/connect'\n\ntype Data<T extends RequestOptions> = T extends RequestOptions<any, any, any, any, any, any, infer R, any> ? R : unknown\ntype Routes = Record<string, RequestOptions>\ntype Channels = Record<string, ConnectOptions>\n\nexport class Client<T extends Routes = Routes, U extends Channels = Channels> {\n\n /**\n * Create a new client for the application.\n *\n * @param options The options to pass to the client.\n * @example new Client({ baseUrl: 'https://api.example.com' })\n */\n constructor(public options: RequestOptions = {}) {}\n\n /**\n * Fetch a route from the API and return the `Response` object. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\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 */\n public fetch<K extends keyof T & string>(route: K, options?: T[K]): Promise<Response & { json: () => Promise<Data<T[K]>> }> {\n return fetch(route, { ...this.options, ...options })\n }\n\n /**\n * Fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The data from the API.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const data = request('GET /api/product/:id', { data: { id: '1' } })\n */\n public request<K extends keyof T & string>(route: K, options?: T[K]): Promise<Data<T[K]>> {\n return request(route, { ...this.options, ...options }) as Promise<Data<T[K]>>\n }\n\n /**\n * Attempt to fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns A result object with either the data or an error.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const { data, error } = requestAttempt('GET /api/product/:id', { data: { id: '1' } })\n * if (error) console.error(error)\n * else console.log(data)\n */\n public requestAttempt<K extends keyof T & string>(route: K, options?: T[K]): Promise<Result<Data<T[K]>>> {\n return attempt(() => this.request(route, options))\n }\n\n /**\n * Create a new WebSocket connection to the server with the given path. The connection will\n * automatically reconnect if the connection is closed unexpectedly.\n *\n * @param channel The path to connect to.\n * @param options The options to pass to the connection.\n * @returns The WebSocket connection.\n */\n public connect<P extends keyof U & string>(channel: P, options?: U[P]): Awaitable<WebSocketChannel<U[P]>, WebSocketChannel<U[P]>> {\n return connect(channel, { baseUrl: this.options.baseUrl, ...options }) as Awaitable<WebSocketChannel<U[P]>, WebSocketChannel<U[P]>>\n }\n}\n\n/**\n * Create a new type-safe client for the application. The client can be used to fetch data from\n * the API and connect to the server using WebSockets with the given path.\n *\n * @param options The options to pass to the client.\n * @returns The client object with the request method.\n * @example\n * // Create a type-safe client for the application.\n * const client = createClient<[ModuleUser]>()\n *\n * // Fetch the data from the API.\n * const data = await client.request('GET /api/user/:id', { id: '1' })\n *\n * // Use the data from the API.\n * console.log(data) // { id: '1', name: 'John Doe' }\n */\nexport function createClient<T extends OpenAPILike>(options?: ServiceOptions<T>): Client<OpenAPIOptionsMap<T>>\n\n/**\n * Create a new type-safe client for the application. The client can be used to fetch data from\n * the API and connect to the server using WebSockets with the given path.\n *\n * @param options The options to pass to the client.\n * @returns The client object with the request method.\n * @example\n * // Create a type-safe client for the application.\n * const client = createClient<[ModuleUser]>()\n *\n * // Fetch the data from the API.\n * const data = await client.request('GET /api/user/:id', { id: '1' })\n *\n * // Use the data from the API.\n * console.log(data) // { id: '1', name: 'John Doe' }\n */\nexport function createClient<T extends Routes = Routes, V extends Channels = Channels>(options?: RequestOptions): Client<T, V>\nexport function createClient(options?: RequestOptions): Client {\n return new Client(options)\n}\n"],"names":[],"mappings":";;;;;;;AAeO,MAAM,OAAiE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ5E,YAAmB,UAA0B,IAAI;AAA9B,SAAA,UAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWZ,MAAkC,OAAU,SAAyE;AACnH,WAAA,MAAM,OAAO,EAAE,GAAG,KAAK,SAAS,GAAG,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqB9C,QAAoC,OAAU,SAAqC;AACjF,WAAA,QAAQ,OAAO,EAAE,GAAG,KAAK,SAAS,GAAG,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAuBhD,eAA2C,OAAU,SAA6C;AACvG,WAAO,QAAQ,MAAM,KAAK,QAAQ,OAAO,OAAO,CAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAW5C,QAAoC,SAAY,SAA2E;AACzH,WAAA,QAAQ,SAAS,EAAE,SAAS,KAAK,QAAQ,SAAS,GAAG,SAAS;AAAA,EAAA;AAEzE;AAqCO,SAAS,aAAa,SAAkC;AACtD,SAAA,IAAI,OAAO,OAAO;AAC3B;"}
@@ -1,12 +1,12 @@
1
1
  "use strict";
2
- var resolveOperation = require("./chunks/CtW2aMuA.cjs"), handleResponse = require("./chunks/Cayg8606.cjs");
3
- require("./chunks/CYmaYL5B.cjs");
2
+ var resolveOperationTokenOptions = require("./chunks/DEyigyGy.cjs"), handleResponse = require("./chunks/CVzmr2NA.cjs");
3
+ require("./chunks/BDxlAULu.cjs");
4
4
  require("@unshared/functions/awaitable");
5
5
  function createService(document, initialOptions) {
6
6
  return new Proxy({}, {
7
7
  get(_, id) {
8
8
  return async (data, options) => {
9
- const baseUrl = resolveOperation.getServerUrl(document), operation = resolveOperation.resolveOperation(document, id), { method, path, responses = {} } = operation, response = await handleResponse.fetch(path, { method, baseUrl, data, ...initialOptions, ...options });
9
+ const baseUrl = resolveOperationTokenOptions.getServerUrl(document), operation = resolveOperationTokenOptions.resolveOperation(document, id), tokenOptions = resolveOperationTokenOptions.resolveOperationTokenOptions(document, operation), { method, path, responses = {} } = operation, { url, init } = handleResponse.parseRequest(path, { method, baseUrl, data, ...tokenOptions, ...initialOptions, ...options }), response = await globalThis.fetch(url, init);
10
10
  if (response.ok) return handleResponse.handleResponse(response, { ...initialOptions, ...options });
11
11
  const status = response.status.toString();
12
12
  throw status in responses && typeof responses[status] == "object" && responses[status] !== null && "description" in responses[status] && typeof responses[status].description == "string" ? new Error(responses[status].description) : new Error(response.statusText);
@@ -1 +1 @@
1
- {"version":3,"file":"createService.cjs","sources":["../createService.ts"],"sourcesContent":["import type { MaybeLiteral } from '@unshared/types'\nimport type { OpenAPIV3, Operation, OperationById, OperationId, OperationOptions, OperationResult, ServerUrl } from './openapi'\nimport type { RequestOptions } from './utils/request'\nimport { getServerUrl } from './openapi/getServerUrl'\nimport { resolveOperation } from './openapi/resolveOperation'\nimport { fetch } from './utils/fetch'\nimport { handleResponse } from './utils/handleResponse'\n\n/** A service instance for the given OpenAPI specification. */\nexport type Service<T> = {\n [K in OperationId<T>]:\n OperationById<T, K> extends infer U extends OperationById<T, K>\n ? (data: OperationOptions<T, U>['data'], options?: OperationOptions<T, U>) => Promise<OperationResult<T, U>>\n : never\n}\n\n/** The options to pass to the service client. */\nexport interface ServiceOptions<T = any> extends RequestOptions {\n baseUrl?: MaybeLiteral<ServerUrl<T>>\n headers?: T extends { openapi: string } ? OpenAPIV3.ServerHeaders<T> : never\n}\n\n/**\n * Create a new client instance for the given OpenAPI specification.\n *\n * @param document The OpenAPI specification document.\n * @param initialOptions The initial options to use for every request.\n * @returns The client instance.\n * @example\n *\n * // Import the Giphy OpenAPI specification.\n * import Giphy from './giphy.openapi.json'\n *\n * // Create a new service instance for the Giphy API.\n * const service = createService(Giphy, { headers: { 'Bearer' } })\n *\n * // Request the \"searchGifs\" operation from the Giphy API.\n * await service.getGifs({ limit: 10, offset: 0, q: 'cats' }) // => { data: [...] }\n */\nexport function createService<T extends object>(document: Readonly<T>, initialOptions?: ServiceOptions<T>): Service<T> {\n return new Proxy({}, {\n get(_, id: OperationId<T>) {\n return async(data: object, options: RequestOptions) => {\n\n // --- Find the operation in the OpenAPI specification.\n const baseUrl = getServerUrl(document)\n const operation = resolveOperation(document, id) as Operation\n\n // --- Fetch the relevant resource from the server.\n const { method, path, responses = {} } = operation\n const response = await fetch(path, { method, baseUrl, data, ...initialOptions, ...options })\n if (response.ok) return handleResponse(response, { ...initialOptions, ...options })\n\n // --- Throw an error if the response was not successful.\n const status = response.status.toString()\n if (status in responses\n && typeof responses[status] === 'object'\n && responses[status] !== null\n && 'description' in responses[status]\n && typeof responses[status].description === 'string')\n throw new Error(responses[status].description)\n\n // --- Throw a generic error if the response was not successful.\n throw new Error(response.statusText)\n }\n },\n }) as Service<T>\n}\n"],"names":["getServerUrl","resolveOperation","fetch","handleResponse"],"mappings":";;;;AAuCgB,SAAA,cAAgC,UAAuB,gBAAgD;AAC9G,SAAA,IAAI,MAAM,IAAI;AAAA,IACnB,IAAI,GAAG,IAAoB;AAClB,aAAA,OAAM,MAAc,YAA4B;AAGrD,cAAM,UAAUA,iBAAAA,aAAa,QAAQ,GAC/B,YAAYC,iBAAAA,iBAAiB,UAAU,EAAE,GAGzC,EAAE,QAAQ,MAAM,YAAY,GAAG,IAAI,WACnC,WAAW,MAAMC,eAAAA,MAAM,MAAM,EAAE,QAAQ,SAAS,MAAM,GAAG,gBAAgB,GAAG,SAAS;AACvF,YAAA,SAAS,GAAI,QAAOC,eAAe,eAAA,UAAU,EAAE,GAAG,gBAAgB,GAAG,SAAS;AAG5E,cAAA,SAAS,SAAS,OAAO,SAAS;AACxC,cAAI,UAAU,aACT,OAAO,UAAU,MAAM,KAAM,YAC7B,UAAU,MAAM,MAAM,QACtB,iBAAiB,UAAU,MAAM,KACjC,OAAO,UAAU,MAAM,EAAE,eAAgB,WACtC,IAAI,MAAM,UAAU,MAAM,EAAE,WAAW,IAGzC,IAAI,MAAM,SAAS,UAAU;AAAA,MACrC;AAAA,IAAA;AAAA,EACF,CACD;AACH;;"}
1
+ {"version":3,"file":"createService.cjs","sources":["../createService.ts"],"sourcesContent":["import type { MaybeLiteral } from '@unshared/types'\nimport type { OpenAPIV3, Operation, OperationById, OperationId, OperationOptions, OperationResult, ServerUrl } from './openapi'\nimport type { RequestOptions } from './utils/request'\nimport { getServerUrl } from './openapi/getServerUrl'\nimport { resolveOperation } from './openapi/resolveOperation'\nimport { resolveOperationTokenOptions } from './openapi/resolveOperationTokenOptions'\nimport { handleResponse } from './utils/handleResponse'\nimport { parseRequest } from './utils/parseRequest'\n\n/** A service instance for the given OpenAPI specification. */\nexport type Service<T> = {\n [K in OperationId<T>]:\n OperationById<T, K> extends infer U extends OperationById<T, K>\n ? (data: OperationOptions<T, U>['data'], options?: OperationOptions<T, U>) => Promise<OperationResult<T, U>>\n : never\n}\n\n/** The options to pass to the service client. */\nexport interface ServiceOptions<T = any> extends RequestOptions {\n baseUrl?: MaybeLiteral<ServerUrl<T>>\n headers?: T extends { openapi: string } ? OpenAPIV3.ServerHeaders<T> : never\n}\n\n/**\n * Create a new client instance for the given OpenAPI specification.\n *\n * @param document The OpenAPI specification document.\n * @param initialOptions The initial options to use for every request.\n * @returns The client instance.\n * @example\n *\n * // Import the Giphy OpenAPI specification.\n * import Giphy from './giphy.openapi.json'\n *\n * // Create a new service instance for the Giphy API.\n * const service = createService(Giphy, { headers: { 'Bearer' } })\n *\n * // Request the \"searchGifs\" operation from the Giphy API.\n * await service.getGifs({ limit: 10, offset: 0, q: 'cats' }) // => { data: [...] }\n */\nexport function createService<T extends object>(document: Readonly<T>, initialOptions?: ServiceOptions<T>): Service<T> {\n return new Proxy({}, {\n get(_, id: OperationId<T>) {\n return async(data: object, options: RequestOptions) => {\n\n // --- Find the operation in the OpenAPI specification.\n const baseUrl = getServerUrl(document)\n const operation = resolveOperation(document, id) as Operation\n const tokenOptions = resolveOperationTokenOptions(document, operation)\n\n // --- Fetch the relevant resource from the server.\n const { method, path, responses = {} } = operation\n const { url, init } = parseRequest(path, { method, baseUrl, data, ...tokenOptions, ...initialOptions, ...options })\n const response = await globalThis.fetch(url, init)\n if (response.ok) return handleResponse(response, { ...initialOptions, ...options })\n\n // --- Throw an error if the response was not successful.\n const status = response.status.toString()\n if (status in responses\n && typeof responses[status] === 'object'\n && responses[status] !== null\n && 'description' in responses[status]\n && typeof responses[status].description === 'string')\n throw new Error(responses[status].description)\n\n // --- Throw a generic error if the response was not successful.\n throw new Error(response.statusText)\n }\n },\n }) as Service<T>\n}\n"],"names":["getServerUrl","resolveOperation","resolveOperationTokenOptions","parseRequest","handleResponse"],"mappings":";;;;AAwCgB,SAAA,cAAgC,UAAuB,gBAAgD;AAC9G,SAAA,IAAI,MAAM,IAAI;AAAA,IACnB,IAAI,GAAG,IAAoB;AAClB,aAAA,OAAM,MAAc,YAA4B;AAG/C,cAAA,UAAUA,0CAAa,QAAQ,GAC/B,YAAYC,8CAAiB,UAAU,EAAE,GACzC,eAAeC,6BAAAA,6BAA6B,UAAU,SAAS,GAG/D,EAAE,QAAQ,MAAM,YAAY,OAAO,WACnC,EAAE,KAAK,KAAA,IAASC,eAAAA,aAAa,MAAM,EAAE,QAAQ,SAAS,MAAM,GAAG,cAAc,GAAG,gBAAgB,GAAG,QAAS,CAAA,GAC5G,WAAW,MAAM,WAAW,MAAM,KAAK,IAAI;AAC7C,YAAA,SAAS,GAAI,QAAOC,eAAe,eAAA,UAAU,EAAE,GAAG,gBAAgB,GAAG,SAAS;AAG5E,cAAA,SAAS,SAAS,OAAO,SAAS;AACxC,cAAI,UAAU,aACT,OAAO,UAAU,MAAM,KAAM,YAC7B,UAAU,MAAM,MAAM,QACtB,iBAAiB,UAAU,MAAM,KACjC,OAAO,UAAU,MAAM,EAAE,eAAgB,WACtC,IAAI,MAAM,UAAU,MAAM,EAAE,WAAW,IAGzC,IAAI,MAAM,SAAS,UAAU;AAAA,MACrC;AAAA,IAAA;AAAA,EACF,CACD;AACH;;"}
@@ -1,6 +1,6 @@
1
1
  import { MaybeLiteral } from '@unshared/types';
2
- import { b as OperationId, c as OperationById, d as OperationOptions, e as OperationResult, S as ServerUrl, f as OpenAPIV3 } from './chunks/mHfUAX_g.js';
3
- import { R as RequestOptions } from './chunks/CO11DuYE.js';
2
+ import { b as OperationId, c as OperationById, d as OperationOptions, e as OperationResult, S as ServerUrl, f as OpenAPIV3 } from './chunks/Bs2VarsP.js';
3
+ import { R as RequestOptions } from './chunks/BZ5qrH6f.js';
4
4
  import 'openapi-types';
5
5
  import './HttpHeaders.js';
6
6
  import './HttpMethods.js';
@@ -1,12 +1,12 @@
1
- import { g as getServerUrl, r as resolveOperation } from "./chunks/Biic1J5b.js";
2
- import { f as fetch, h as handleResponse } from "./chunks/BUeqbyph.js";
3
- import "./chunks/0ZzUT3m_.js";
1
+ import { g as getServerUrl, r as resolveOperation, a as resolveOperationTokenOptions } from "./chunks/B_Gz6Yz8.js";
2
+ import { p as parseRequest, h as handleResponse } from "./chunks/CS5r-m4U.js";
3
+ import "./chunks/B6pUErTM.js";
4
4
  import "@unshared/functions/awaitable";
5
5
  function createService(document, initialOptions) {
6
6
  return new Proxy({}, {
7
7
  get(_, id) {
8
8
  return async (data, options) => {
9
- const baseUrl = getServerUrl(document), operation = resolveOperation(document, id), { method, path, responses = {} } = operation, response = await fetch(path, { method, baseUrl, data, ...initialOptions, ...options });
9
+ const baseUrl = getServerUrl(document), operation = resolveOperation(document, id), tokenOptions = resolveOperationTokenOptions(document, operation), { method, path, responses = {} } = operation, { url, init } = parseRequest(path, { method, baseUrl, data, ...tokenOptions, ...initialOptions, ...options }), response = await globalThis.fetch(url, init);
10
10
  if (response.ok) return handleResponse(response, { ...initialOptions, ...options });
11
11
  const status = response.status.toString();
12
12
  throw status in responses && typeof responses[status] == "object" && responses[status] !== null && "description" in responses[status] && typeof responses[status].description == "string" ? new Error(responses[status].description) : new Error(response.statusText);
@@ -1 +1 @@
1
- {"version":3,"file":"createService.js","sources":["../createService.ts"],"sourcesContent":["import type { MaybeLiteral } from '@unshared/types'\nimport type { OpenAPIV3, Operation, OperationById, OperationId, OperationOptions, OperationResult, ServerUrl } from './openapi'\nimport type { RequestOptions } from './utils/request'\nimport { getServerUrl } from './openapi/getServerUrl'\nimport { resolveOperation } from './openapi/resolveOperation'\nimport { fetch } from './utils/fetch'\nimport { handleResponse } from './utils/handleResponse'\n\n/** A service instance for the given OpenAPI specification. */\nexport type Service<T> = {\n [K in OperationId<T>]:\n OperationById<T, K> extends infer U extends OperationById<T, K>\n ? (data: OperationOptions<T, U>['data'], options?: OperationOptions<T, U>) => Promise<OperationResult<T, U>>\n : never\n}\n\n/** The options to pass to the service client. */\nexport interface ServiceOptions<T = any> extends RequestOptions {\n baseUrl?: MaybeLiteral<ServerUrl<T>>\n headers?: T extends { openapi: string } ? OpenAPIV3.ServerHeaders<T> : never\n}\n\n/**\n * Create a new client instance for the given OpenAPI specification.\n *\n * @param document The OpenAPI specification document.\n * @param initialOptions The initial options to use for every request.\n * @returns The client instance.\n * @example\n *\n * // Import the Giphy OpenAPI specification.\n * import Giphy from './giphy.openapi.json'\n *\n * // Create a new service instance for the Giphy API.\n * const service = createService(Giphy, { headers: { 'Bearer' } })\n *\n * // Request the \"searchGifs\" operation from the Giphy API.\n * await service.getGifs({ limit: 10, offset: 0, q: 'cats' }) // => { data: [...] }\n */\nexport function createService<T extends object>(document: Readonly<T>, initialOptions?: ServiceOptions<T>): Service<T> {\n return new Proxy({}, {\n get(_, id: OperationId<T>) {\n return async(data: object, options: RequestOptions) => {\n\n // --- Find the operation in the OpenAPI specification.\n const baseUrl = getServerUrl(document)\n const operation = resolveOperation(document, id) as Operation\n\n // --- Fetch the relevant resource from the server.\n const { method, path, responses = {} } = operation\n const response = await fetch(path, { method, baseUrl, data, ...initialOptions, ...options })\n if (response.ok) return handleResponse(response, { ...initialOptions, ...options })\n\n // --- Throw an error if the response was not successful.\n const status = response.status.toString()\n if (status in responses\n && typeof responses[status] === 'object'\n && responses[status] !== null\n && 'description' in responses[status]\n && typeof responses[status].description === 'string')\n throw new Error(responses[status].description)\n\n // --- Throw a generic error if the response was not successful.\n throw new Error(response.statusText)\n }\n },\n }) as Service<T>\n}\n"],"names":[],"mappings":";;;;AAuCgB,SAAA,cAAgC,UAAuB,gBAAgD;AAC9G,SAAA,IAAI,MAAM,IAAI;AAAA,IACnB,IAAI,GAAG,IAAoB;AAClB,aAAA,OAAM,MAAc,YAA4B;AAGrD,cAAM,UAAU,aAAa,QAAQ,GAC/B,YAAY,iBAAiB,UAAU,EAAE,GAGzC,EAAE,QAAQ,MAAM,YAAY,GAAG,IAAI,WACnC,WAAW,MAAM,MAAM,MAAM,EAAE,QAAQ,SAAS,MAAM,GAAG,gBAAgB,GAAG,SAAS;AACvF,YAAA,SAAS,GAAI,QAAO,eAAe,UAAU,EAAE,GAAG,gBAAgB,GAAG,SAAS;AAG5E,cAAA,SAAS,SAAS,OAAO,SAAS;AACxC,cAAI,UAAU,aACT,OAAO,UAAU,MAAM,KAAM,YAC7B,UAAU,MAAM,MAAM,QACtB,iBAAiB,UAAU,MAAM,KACjC,OAAO,UAAU,MAAM,EAAE,eAAgB,WACtC,IAAI,MAAM,UAAU,MAAM,EAAE,WAAW,IAGzC,IAAI,MAAM,SAAS,UAAU;AAAA,MACrC;AAAA,IAAA;AAAA,EACF,CACD;AACH;"}
1
+ {"version":3,"file":"createService.js","sources":["../createService.ts"],"sourcesContent":["import type { MaybeLiteral } from '@unshared/types'\nimport type { OpenAPIV3, Operation, OperationById, OperationId, OperationOptions, OperationResult, ServerUrl } from './openapi'\nimport type { RequestOptions } from './utils/request'\nimport { getServerUrl } from './openapi/getServerUrl'\nimport { resolveOperation } from './openapi/resolveOperation'\nimport { resolveOperationTokenOptions } from './openapi/resolveOperationTokenOptions'\nimport { handleResponse } from './utils/handleResponse'\nimport { parseRequest } from './utils/parseRequest'\n\n/** A service instance for the given OpenAPI specification. */\nexport type Service<T> = {\n [K in OperationId<T>]:\n OperationById<T, K> extends infer U extends OperationById<T, K>\n ? (data: OperationOptions<T, U>['data'], options?: OperationOptions<T, U>) => Promise<OperationResult<T, U>>\n : never\n}\n\n/** The options to pass to the service client. */\nexport interface ServiceOptions<T = any> extends RequestOptions {\n baseUrl?: MaybeLiteral<ServerUrl<T>>\n headers?: T extends { openapi: string } ? OpenAPIV3.ServerHeaders<T> : never\n}\n\n/**\n * Create a new client instance for the given OpenAPI specification.\n *\n * @param document The OpenAPI specification document.\n * @param initialOptions The initial options to use for every request.\n * @returns The client instance.\n * @example\n *\n * // Import the Giphy OpenAPI specification.\n * import Giphy from './giphy.openapi.json'\n *\n * // Create a new service instance for the Giphy API.\n * const service = createService(Giphy, { headers: { 'Bearer' } })\n *\n * // Request the \"searchGifs\" operation from the Giphy API.\n * await service.getGifs({ limit: 10, offset: 0, q: 'cats' }) // => { data: [...] }\n */\nexport function createService<T extends object>(document: Readonly<T>, initialOptions?: ServiceOptions<T>): Service<T> {\n return new Proxy({}, {\n get(_, id: OperationId<T>) {\n return async(data: object, options: RequestOptions) => {\n\n // --- Find the operation in the OpenAPI specification.\n const baseUrl = getServerUrl(document)\n const operation = resolveOperation(document, id) as Operation\n const tokenOptions = resolveOperationTokenOptions(document, operation)\n\n // --- Fetch the relevant resource from the server.\n const { method, path, responses = {} } = operation\n const { url, init } = parseRequest(path, { method, baseUrl, data, ...tokenOptions, ...initialOptions, ...options })\n const response = await globalThis.fetch(url, init)\n if (response.ok) return handleResponse(response, { ...initialOptions, ...options })\n\n // --- Throw an error if the response was not successful.\n const status = response.status.toString()\n if (status in responses\n && typeof responses[status] === 'object'\n && responses[status] !== null\n && 'description' in responses[status]\n && typeof responses[status].description === 'string')\n throw new Error(responses[status].description)\n\n // --- Throw a generic error if the response was not successful.\n throw new Error(response.statusText)\n }\n },\n }) as Service<T>\n}\n"],"names":[],"mappings":";;;;AAwCgB,SAAA,cAAgC,UAAuB,gBAAgD;AAC9G,SAAA,IAAI,MAAM,IAAI;AAAA,IACnB,IAAI,GAAG,IAAoB;AAClB,aAAA,OAAM,MAAc,YAA4B;AAG/C,cAAA,UAAU,aAAa,QAAQ,GAC/B,YAAY,iBAAiB,UAAU,EAAE,GACzC,eAAe,6BAA6B,UAAU,SAAS,GAG/D,EAAE,QAAQ,MAAM,YAAY,OAAO,WACnC,EAAE,KAAK,KAAA,IAAS,aAAa,MAAM,EAAE,QAAQ,SAAS,MAAM,GAAG,cAAc,GAAG,gBAAgB,GAAG,QAAS,CAAA,GAC5G,WAAW,MAAM,WAAW,MAAM,KAAK,IAAI;AAC7C,YAAA,SAAS,GAAI,QAAO,eAAe,UAAU,EAAE,GAAG,gBAAgB,GAAG,SAAS;AAG5E,cAAA,SAAS,SAAS,OAAO,SAAS;AACxC,cAAI,UAAU,aACT,OAAO,UAAU,MAAM,KAAM,YAC7B,UAAU,MAAM,MAAM,QACtB,iBAAiB,UAAU,MAAM,KACjC,OAAO,UAAU,MAAM,EAAE,eAAgB,WACtC,IAAI,MAAM,UAAU,MAAM,EAAE,WAAW,IAGzC,IAAI,MAAM,SAAS,UAAU;AAAA,MACrC;AAAA,IAAA;AAAA,EACF,CACD;AACH;"}
package/dist/index.cjs CHANGED
@@ -1,13 +1,13 @@
1
1
  "use strict";
2
2
  var createClient = require("./createClient.cjs"), createService = require("./createService.cjs"), HttpHeaders = require("./HttpHeaders.cjs"), HttpMethods = require("./HttpMethods.cjs"), HttpStatusCodes = require("./HttpStatusCodes.cjs");
3
3
  require("@unshared/functions/attempt");
4
- require("./chunks/Cayg8606.cjs");
5
- require("./chunks/CYmaYL5B.cjs");
4
+ require("./chunks/DXrQkl1A.cjs");
5
+ require("./chunks/CVzmr2NA.cjs");
6
+ require("./chunks/BDxlAULu.cjs");
6
7
  require("@unshared/functions/awaitable");
7
- require("./chunks/Du_W5H6e.cjs");
8
- require("./chunks/BMbsYNBd.cjs");
8
+ require("./chunks/BdFNzMcu.cjs");
9
9
  require("@unshared/functions");
10
- require("./chunks/CtW2aMuA.cjs");
10
+ require("./chunks/DEyigyGy.cjs");
11
11
  exports.Client = createClient.Client;
12
12
  exports.createClient = createClient.createClient;
13
13
  exports.createService = createService.createService;
package/dist/index.d.ts CHANGED
@@ -5,8 +5,8 @@ export { HttpMethod } from './HttpMethods.js';
5
5
  export { HttpStatusCode } from './HttpStatusCodes.js';
6
6
  import '@unshared/functions';
7
7
  import '@unshared/functions/attempt';
8
- import './chunks/mHfUAX_g.js';
8
+ import './chunks/Bs2VarsP.js';
9
9
  import '@unshared/types';
10
- import './chunks/CO11DuYE.js';
10
+ import './chunks/BZ5qrH6f.js';
11
11
  import 'openapi-types';
12
12
  import './websocket.js';
package/dist/index.js CHANGED
@@ -4,13 +4,13 @@ import { HttpHeader } from "./HttpHeaders.js";
4
4
  import { HttpMethod } from "./HttpMethods.js";
5
5
  import { HttpStatusCode } from "./HttpStatusCodes.js";
6
6
  import "@unshared/functions/attempt";
7
- import "./chunks/BUeqbyph.js";
8
- import "./chunks/0ZzUT3m_.js";
7
+ import "./chunks/D1QsGr3A.js";
8
+ import "./chunks/CS5r-m4U.js";
9
+ import "./chunks/B6pUErTM.js";
9
10
  import "@unshared/functions/awaitable";
10
- import "./chunks/DJJsADWD.js";
11
- import "./chunks/6IxvRpmY.js";
11
+ import "./chunks/Bys4-xE2.js";
12
12
  import "@unshared/functions";
13
- import "./chunks/Biic1J5b.js";
13
+ import "./chunks/B_Gz6Yz8.js";
14
14
  export {
15
15
  Client,
16
16
  HttpHeader,
package/dist/openapi.cjs CHANGED
@@ -1,5 +1,11 @@
1
1
  "use strict";
2
- var resolveOperation = require("./chunks/CtW2aMuA.cjs");
2
+ var resolveOperationTokenOptions = require("./chunks/DEyigyGy.cjs");
3
+ function isOpenAPIV2(value) {
4
+ return typeof value == "object" && value !== null && "swagger" in value && value.swagger === "2.0";
5
+ }
6
+ function isOpenAPIV3_1(value) {
7
+ return typeof value == "object" && value !== null && "openapi" in value && value.openapi === "3.1.0";
8
+ }
3
9
  function isReferenceObject(value) {
4
10
  return typeof value == "object" && value !== null && "$ref" in value && typeof value.$ref == "string";
5
11
  }
@@ -27,8 +33,12 @@ function resolveDocument(value, document = value) {
27
33
  }
28
34
  });
29
35
  }
30
- exports.getServerUrl = resolveOperation.getServerUrl;
31
- exports.resolveOperation = resolveOperation.resolveOperation;
36
+ exports.getServerUrl = resolveOperationTokenOptions.getServerUrl;
37
+ exports.isOpenAPIV3 = resolveOperationTokenOptions.isOpenAPIV3;
38
+ exports.resolveOperation = resolveOperationTokenOptions.resolveOperation;
39
+ exports.resolveOperationTokenOptions = resolveOperationTokenOptions.resolveOperationTokenOptions;
40
+ exports.isOpenAPIV2 = isOpenAPIV2;
41
+ exports.isOpenAPIV3_1 = isOpenAPIV3_1;
32
42
  exports.isReferenceObject = isReferenceObject;
33
43
  exports.resolveDocument = resolveDocument;
34
44
  exports.resolveReference = resolveReference;
@@ -1 +1 @@
1
- {"version":3,"file":"openapi.cjs","sources":["../openapi/isReferenceObject.ts","../openapi/resolveReference.ts","../openapi/resolveDocument.ts"],"sourcesContent":["import type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'\n\nexport type OpenAPIReference =\n | OpenAPIV2.ReferenceObject\n | OpenAPIV3.ReferenceObject\n | OpenAPIV3_1.ReferenceObject\n\n/**\n * Check if a value is an {@linkcode OpenAPIReference}.\n *\n * @param value The value to check.\n * @returns `true` if the value is a reference object.\n * @example isReferenceObject({ $ref: '#/components/schemas/MySchema' }) // true\n */\nexport function isReferenceObject<T extends OpenAPIReference>(value: unknown): value is T {\n return typeof value === 'object'\n && value !== null\n && '$ref' in value\n && typeof value.$ref === 'string'\n}\n","import type { StringJoin, StringReplace, WriteableDeep } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport { isReferenceObject } from './isReferenceObject'\n\n/**\n * Decode an OpenAPI reference path by replacing the encoded characters with\n * their original values. This function will replace `~0` with `~` and `~1`\n * with `/`.\n *\n * @example DecodeReference<'#/foo~1bar~0baz'> // '#/foo/bar~baz'\n */\nexport type OpenAPIReferenceDecoded<T extends string> =\n StringReplace<StringReplace<T, '~0', '~'>, '~1', '/'>\n\n/**\n * Extract the parts of a reference path as a tuple.\n *\n * @example OpenAPIV3ReferencePath<'#/paths/~1users~1{username}'> // ['paths', '/users/{username}']\n */\nexport type OpenAPIReferencePath<T extends string> =\n T extends `#/${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `#/${infer P}` ? [P]\n : T extends `${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `${infer P}` ? [P]\n : []\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The result type.\n * @example Resolved<{ $ref: '#/info' }, { info: { title: string } }> // { title: string }\n */\nexport type OpenAPIReferenceResolved<\n T extends OpenAPIReference,\n D extends object,\n> =\n D extends object\n ? T extends { $ref: infer R extends string }\n\n // --- Match last part of the reference.\n ? OpenAPIReferencePath<R> extends [infer P extends string]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? WriteableDeep<Omit<D[OpenAPIReferenceDecoded<P>], keyof T>>\n : never\n : never\n\n // --- Match middle part of the reference.\n : OpenAPIReferencePath<R> extends [infer P extends string, ...infer Rest extends string[]]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? OpenAPIReferenceResolved<{ $ref: StringJoin<Rest, '/'> }, D[OpenAPIReferenceDecoded<P>]>\n : never\n : never\n : never\n : never\n : never\n\n/**\n * Resolve an OpenAPI `ReferenceObject` to the component it references. If the\n * source is not a reference, the source will be returned.\n *\n * @private\n * @param reference The reference object to resolve.\n * @param document The OpenAPI document to resolve the reference from.\n * @returns The result component.\n * @example resolveReference({ $ref: '#/components/schemas/User' }, document)\n */\nexport function resolveReference<\n T extends OpenAPIReference,\n D extends object,\n>(reference: Readonly<T>, document: Readonly<D>): OpenAPIReferenceResolved<T, D> {\n\n // --- Return the source if it is not a reference.\n if (!isReferenceObject(reference))\n throw new TypeError('Expected value to be an OpenAPI reference object.')\n\n // --- Assert that the parameters are valid.\n if (typeof document !== 'object' || document === null)\n throw new TypeError('Expected OpenAPI specification to be an object.')\n\n // --- Resolve the component with it's reference path.\n const referenceParts = reference.$ref.replace(/^#\\//, '').split('/')\n let result = document\n for (const part of referenceParts) {\n if (result === undefined) break\n if (typeof result !== 'object' || result === null) break\n const key = part.replaceAll('~1', '/').replaceAll('~0', '~')\n // @ts-expect-error: assume the part is a key of the object.\n result = result[key] as unknown\n }\n\n // --- Throw an error if the component could not be result.\n if (result === undefined)\n throw new Error(`Could not resolve OpenAPI component: ${reference.$ref}`)\n\n // --- Return the result component.\n return result as OpenAPIReferenceResolved<T, D>\n}\n","import type { ObjectLike, Substract } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport type { OpenAPIReferenceResolved } from './resolveReference'\nimport { isReferenceObject } from './isReferenceObject'\nimport { resolveReference as resolveReference } from './resolveReference'\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The resolved type.\n * @example\n * type Resolved = OpenAPIResolved<{\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' }\n * }\n * }\n * }>\n */\nexport type OpenAPIResolved<T, D = T, N extends number = 8> =\n N extends 0 ? T\n : T extends OpenAPIReference\n ? D extends object ? OpenAPIResolved<OpenAPIReferenceResolved<T, D>, D, Substract<N, 1>> : never\n : T extends object ? { -readonly [K in keyof T]: OpenAPIResolved<T[K], D, N> } : T\n\n/**\n * Recursively resolve all references in an OpenAPI specification. This function\n * will return a `Proxy` object that will resolve references on the fly.\n *\n * @param value The OpenAPI specification.\n * @returns The resolved OpenAPI specification.\n * @example\n * const resolved = resolveReferences({\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' },\n * },\n * },\n * })\n */\nexport function resolveDocument<T extends object>(value: Readonly<T>): OpenAPIResolved<T>\nexport function resolveDocument<T extends object, D>(value: Readonly<T>, document: Readonly<D>): OpenAPIResolved<T, D>\nexport function resolveDocument(value: Readonly<ObjectLike>, document = value): unknown {\n return new Proxy(value, {\n get(target, property: string) {\n let value = target[property]\n\n // --- Abort if no document is provided.\n if (!document) return value\n\n // --- Resolve the reference if it is a reference object.\n if (isReferenceObject(value))\n value = resolveReference(value, document)\n\n // --- Recursively resolve references in objects.\n if (typeof value === 'object' && value !== null)\n return resolveDocument(value as ObjectLike, document)\n\n // --- Return the value as is.\n return value\n },\n })\n}\n"],"names":["value"],"mappings":";;AAcO,SAAS,kBAA8C,OAA4B;AACjF,SAAA,OAAO,SAAU,YACnB,UAAU,QACV,UAAU,SACV,OAAO,MAAM,QAAS;AAC7B;ACmDgB,SAAA,iBAGd,WAAwB,UAAuD;AAG3E,MAAA,CAAC,kBAAkB,SAAS;AACxB,UAAA,IAAI,UAAU,mDAAmD;AAGrE,MAAA,OAAO,YAAa,YAAY,aAAa;AACzC,UAAA,IAAI,UAAU,iDAAiD;AAGjE,QAAA,iBAAiB,UAAU,KAAK,QAAQ,QAAQ,EAAE,EAAE,MAAM,GAAG;AACnE,MAAI,SAAS;AACb,aAAW,QAAQ,gBAAgB;AAEjC,QADI,WAAW,UACX,OAAO,UAAW,YAAY,WAAW,KAAM;AAC7C,UAAA,MAAM,KAAK,WAAW,MAAM,GAAG,EAAE,WAAW,MAAM,GAAG;AAE3D,aAAS,OAAO,GAAG;AAAA,EAAA;AAIrB,MAAI,WAAW;AACb,UAAM,IAAI,MAAM,wCAAwC,UAAU,IAAI,EAAE;AAGnE,SAAA;AACT;ACtDgB,SAAA,gBAAgB,OAA6B,WAAW,OAAgB;AAC/E,SAAA,IAAI,MAAM,OAAO;AAAA,IACtB,IAAI,QAAQ,UAAkB;AACxBA,UAAAA,SAAQ,OAAO,QAAQ;AAG3B,aAAK,YAGD,kBAAkBA,MAAK,MACzBA,SAAQ,iBAAiBA,QAAO,QAAQ,IAGtC,OAAOA,UAAU,YAAYA,WAAU,OAClC,gBAAgBA,QAAqB,QAAQ,IAG/CA,UAXeA;AAAAA,IAAA;AAAA,EAYxB,CACD;AACH;;;;;;"}
1
+ {"version":3,"file":"openapi.cjs","sources":["../openapi/isOpenAPIV2.ts","../openapi/isOpenAPIV3_1.ts","../openapi/isReferenceObject.ts","../openapi/resolveReference.ts","../openapi/resolveDocument.ts"],"sourcesContent":["/* eslint-disable unicorn/filename-case */\nimport type { OpenAPIV2 } from 'openapi-types'\n\n/**\n * Check if the given document is an OpenAPI v2 specification.\n *\n * @param value The document to check.\n * @returns `true` if the document is an OpenAPI v2 specification, `false` otherwise.\n * @example isOpenAPIV2({ swagger: '2.0', info: { title: 'Test API', version: '1.0.0' } }) // => true\n */\nexport function isOpenAPIV2(value: unknown): value is OpenAPIV2.Document {\n return typeof value === 'object'\n && value !== null\n && 'swagger' in value\n && value.swagger === '2.0'\n}\n","/* eslint-disable unicorn/filename-case */\nimport type { OpenAPIV3_1 } from 'openapi-types'\n\n/**\n * Check if the given document is an OpenAPI v3.1 specification.\n *\n * @param value The document to check.\n * @returns `true` if the document is an OpenAPI v3.1 specification, `false` otherwise.\n * @example isOpenAPIV3_1({ openapi: '3.1.0', info: { title: 'Test API', version: '1.0.0' } }) // => true\n */\nexport function isOpenAPIV3_1(value: unknown): value is OpenAPIV3_1.Document {\n return typeof value === 'object'\n && value !== null\n && 'openapi' in value\n && value.openapi === '3.1.0'\n}\n","import type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'\n\nexport type OpenAPIReference =\n | OpenAPIV2.ReferenceObject\n | OpenAPIV3.ReferenceObject\n | OpenAPIV3_1.ReferenceObject\n\n/**\n * Check if a value is an {@linkcode OpenAPIReference}.\n *\n * @param value The value to check.\n * @returns `true` if the value is a reference object.\n * @example isReferenceObject({ $ref: '#/components/schemas/MySchema' }) // true\n */\nexport function isReferenceObject<T extends OpenAPIReference>(value: unknown): value is T {\n return typeof value === 'object'\n && value !== null\n && '$ref' in value\n && typeof value.$ref === 'string'\n}\n","import type { StringJoin, StringReplace, WriteableDeep } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport { isReferenceObject } from './isReferenceObject'\n\n/**\n * Decode an OpenAPI reference path by replacing the encoded characters with\n * their original values. This function will replace `~0` with `~` and `~1`\n * with `/`.\n *\n * @example DecodeReference<'#/foo~1bar~0baz'> // '#/foo/bar~baz'\n */\nexport type OpenAPIReferenceDecoded<T extends string> =\n StringReplace<StringReplace<T, '~0', '~'>, '~1', '/'>\n\n/**\n * Extract the parts of a reference path as a tuple.\n *\n * @example OpenAPIV3ReferencePath<'#/paths/~1users~1{username}'> // ['paths', '/users/{username}']\n */\nexport type OpenAPIReferencePath<T extends string> =\n T extends `#/${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `#/${infer P}` ? [P]\n : T extends `${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `${infer P}` ? [P]\n : []\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The result type.\n * @example Resolved<{ $ref: '#/info' }, { info: { title: string } }> // { title: string }\n */\nexport type OpenAPIReferenceResolved<\n T extends OpenAPIReference,\n D extends object,\n> =\n D extends object\n ? T extends { $ref: infer R extends string }\n\n // --- Match last part of the reference.\n ? OpenAPIReferencePath<R> extends [infer P extends string]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? WriteableDeep<Omit<D[OpenAPIReferenceDecoded<P>], keyof T>>\n : never\n : never\n\n // --- Match middle part of the reference.\n : OpenAPIReferencePath<R> extends [infer P extends string, ...infer Rest extends string[]]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? OpenAPIReferenceResolved<{ $ref: StringJoin<Rest, '/'> }, D[OpenAPIReferenceDecoded<P>]>\n : never\n : never\n : never\n : never\n : never\n\n/**\n * Resolve an OpenAPI `ReferenceObject` to the component it references. If the\n * source is not a reference, the source will be returned.\n *\n * @private\n * @param reference The reference object to resolve.\n * @param document The OpenAPI document to resolve the reference from.\n * @returns The result component.\n * @example resolveReference({ $ref: '#/components/schemas/User' }, document)\n */\nexport function resolveReference<\n T extends OpenAPIReference,\n D extends object,\n>(reference: Readonly<T>, document: Readonly<D>): OpenAPIReferenceResolved<T, D> {\n\n // --- Return the source if it is not a reference.\n if (!isReferenceObject(reference))\n throw new TypeError('Expected value to be an OpenAPI reference object.')\n\n // --- Assert that the parameters are valid.\n if (typeof document !== 'object' || document === null)\n throw new TypeError('Expected OpenAPI specification to be an object.')\n\n // --- Resolve the component with it's reference path.\n const referenceParts = reference.$ref.replace(/^#\\//, '').split('/')\n let result = document\n for (const part of referenceParts) {\n if (result === undefined) break\n if (typeof result !== 'object' || result === null) break\n const key = part.replaceAll('~1', '/').replaceAll('~0', '~')\n // @ts-expect-error: assume the part is a key of the object.\n result = result[key] as unknown\n }\n\n // --- Throw an error if the component could not be result.\n if (result === undefined)\n throw new Error(`Could not resolve OpenAPI component: ${reference.$ref}`)\n\n // --- Return the result component.\n return result as OpenAPIReferenceResolved<T, D>\n}\n","import type { ObjectLike, Substract } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport type { OpenAPIReferenceResolved } from './resolveReference'\nimport { isReferenceObject } from './isReferenceObject'\nimport { resolveReference as resolveReference } from './resolveReference'\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The resolved type.\n * @example\n * type Resolved = OpenAPIResolved<{\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' }\n * }\n * }\n * }>\n */\nexport type OpenAPIResolved<T, D = T, N extends number = 8> =\n N extends 0 ? T\n : T extends OpenAPIReference\n ? D extends object ? OpenAPIResolved<OpenAPIReferenceResolved<T, D>, D, Substract<N, 1>> : never\n : T extends object ? { -readonly [K in keyof T]: OpenAPIResolved<T[K], D, N> } : T\n\n/**\n * Recursively resolve all references in an OpenAPI specification. This function\n * will return a `Proxy` object that will resolve references on the fly.\n *\n * @param value The OpenAPI specification.\n * @returns The resolved OpenAPI specification.\n * @example\n * const resolved = resolveReferences({\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' },\n * },\n * },\n * })\n */\nexport function resolveDocument<T extends object>(value: Readonly<T>): OpenAPIResolved<T>\nexport function resolveDocument<T extends object, D>(value: Readonly<T>, document: Readonly<D>): OpenAPIResolved<T, D>\nexport function resolveDocument(value: Readonly<ObjectLike>, document = value): unknown {\n return new Proxy(value, {\n get(target, property: string) {\n let value = target[property]\n\n // --- Abort if no document is provided.\n if (!document) return value\n\n // --- Resolve the reference if it is a reference object.\n if (isReferenceObject(value))\n value = resolveReference(value, document)\n\n // --- Recursively resolve references in objects.\n if (typeof value === 'object' && value !== null)\n return resolveDocument(value as ObjectLike, document)\n\n // --- Return the value as is.\n return value\n },\n })\n}\n"],"names":["value"],"mappings":";;AAUO,SAAS,YAAY,OAA6C;AAChE,SAAA,OAAO,SAAU,YACnB,UAAU,QACV,aAAa,SACb,MAAM,YAAY;AACzB;ACLO,SAAS,cAAc,OAA+C;AACpE,SAAA,OAAO,SAAU,YACnB,UAAU,QACV,aAAa,SACb,MAAM,YAAY;AACzB;ACDO,SAAS,kBAA8C,OAA4B;AACjF,SAAA,OAAO,SAAU,YACnB,UAAU,QACV,UAAU,SACV,OAAO,MAAM,QAAS;AAC7B;ACmDgB,SAAA,iBAGd,WAAwB,UAAuD;AAG3E,MAAA,CAAC,kBAAkB,SAAS;AACxB,UAAA,IAAI,UAAU,mDAAmD;AAGrE,MAAA,OAAO,YAAa,YAAY,aAAa;AACzC,UAAA,IAAI,UAAU,iDAAiD;AAGjE,QAAA,iBAAiB,UAAU,KAAK,QAAQ,QAAQ,EAAE,EAAE,MAAM,GAAG;AACnE,MAAI,SAAS;AACb,aAAW,QAAQ,gBAAgB;AAEjC,QADI,WAAW,UACX,OAAO,UAAW,YAAY,WAAW,KAAM;AAC7C,UAAA,MAAM,KAAK,WAAW,MAAM,GAAG,EAAE,WAAW,MAAM,GAAG;AAE3D,aAAS,OAAO,GAAG;AAAA,EAAA;AAIrB,MAAI,WAAW;AACb,UAAM,IAAI,MAAM,wCAAwC,UAAU,IAAI,EAAE;AAGnE,SAAA;AACT;ACtDgB,SAAA,gBAAgB,OAA6B,WAAW,OAAgB;AAC/E,SAAA,IAAI,MAAM,OAAO;AAAA,IACtB,IAAI,QAAQ,UAAkB;AACxBA,UAAAA,SAAQ,OAAO,QAAQ;AAG3B,aAAK,YAGD,kBAAkBA,MAAK,MACzBA,SAAQ,iBAAiBA,QAAO,QAAQ,IAGtC,OAAOA,UAAU,YAAYA,WAAU,OAClC,gBAAgBA,QAAqB,QAAQ,IAG/CA,UAXeA;AAAAA,IAAA;AAAA,EAYxB,CACD;AACH;;;;;;;;;;"}
package/dist/openapi.d.ts CHANGED
@@ -1,10 +1,37 @@
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/mHfUAX_g.js';
2
- import { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';
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/Bs2VarsP.js';
2
+ import { OpenAPIV2, OpenAPIV3, OpenAPIV3_1, OpenAPI } from 'openapi-types';
3
3
  import { StringReplace, WriteableDeep, StringJoin, Substract } from '@unshared/types';
4
- import './chunks/CO11DuYE.js';
4
+ import './chunks/BZ5qrH6f.js';
5
5
  import './HttpHeaders.js';
6
6
  import './HttpMethods.js';
7
7
 
8
+ /**
9
+ * Check if the given document is an OpenAPI v2 specification.
10
+ *
11
+ * @param value The document to check.
12
+ * @returns `true` if the document is an OpenAPI v2 specification, `false` otherwise.
13
+ * @example isOpenAPIV2({ swagger: '2.0', info: { title: 'Test API', version: '1.0.0' } }) // => true
14
+ */
15
+ declare function isOpenAPIV2(value: unknown): value is OpenAPIV2.Document;
16
+
17
+ /**
18
+ * Check if the given document is an OpenAPI v3.0 specification.
19
+ *
20
+ * @param value The document to check.
21
+ * @returns `true` if the document is an OpenAPI v3.0 specification, `false` otherwise.
22
+ * @example isOpenAPIV3({ openapi: '3.0.0', info: { title: 'Test API', version: '1.0.0' } }) // => true
23
+ */
24
+ declare function isOpenAPIV3(value: unknown): value is OpenAPIV3.Document;
25
+
26
+ /**
27
+ * Check if the given document is an OpenAPI v3.1 specification.
28
+ *
29
+ * @param value The document to check.
30
+ * @returns `true` if the document is an OpenAPI v3.1 specification, `false` otherwise.
31
+ * @example isOpenAPIV3_1({ openapi: '3.1.0', info: { title: 'Test API', version: '1.0.0' } }) // => true
32
+ */
33
+ declare function isOpenAPIV3_1(value: unknown): value is OpenAPIV3_1.Document;
34
+
8
35
  type OpenAPIReference = OpenAPIV2.ReferenceObject | OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject;
9
36
  /**
10
37
  * Check if a value is an {@linkcode OpenAPIReference}.
@@ -92,4 +119,18 @@ type OpenAPIResolved<T, D = T, N extends number = 8> = N extends 0 ? T : T exten
92
119
  declare function resolveDocument<T extends object>(value: Readonly<T>): OpenAPIResolved<T>;
93
120
  declare function resolveDocument<T extends object, D>(value: Readonly<T>, document: Readonly<D>): OpenAPIResolved<T, D>;
94
121
 
95
- export { type OpenAPIReference, type OpenAPIReferenceDecoded, type OpenAPIReferencePath, type OpenAPIReferenceResolved, type OpenAPIResolved, isReferenceObject, resolveDocument, resolveReference };
122
+ interface TokenOptions {
123
+ tokenLocation?: 'cookie' | 'header' | 'query';
124
+ tokenProperty?: string;
125
+ }
126
+ /**
127
+ * Resolve the location of the apiKey token based on the OpenAPI specification.
128
+ *
129
+ * @param document The OpenAPI specification document.
130
+ * @param operation The OpenAPI operation object.
131
+ * @returns The location of the apiKey token ('query' | 'cookie' | 'header').
132
+ * @example resolveOperationTokenOptions(document, operation) // => { tokenLocation: 'header', tokenProperty: 'X-API-Key' }
133
+ */
134
+ declare function resolveOperationTokenOptions(document: object, operation: OpenAPI.Operation): TokenOptions;
135
+
136
+ export { type OpenAPIReference, type OpenAPIReferenceDecoded, type OpenAPIReferencePath, type OpenAPIReferenceResolved, type OpenAPIResolved, type TokenOptions, isOpenAPIV2, isOpenAPIV3, isOpenAPIV3_1, isReferenceObject, resolveDocument, resolveOperationTokenOptions, resolveReference };
package/dist/openapi.js CHANGED
@@ -1,4 +1,10 @@
1
- import { g, r } from "./chunks/Biic1J5b.js";
1
+ import { g, i, r, a } from "./chunks/B_Gz6Yz8.js";
2
+ function isOpenAPIV2(value) {
3
+ return typeof value == "object" && value !== null && "swagger" in value && value.swagger === "2.0";
4
+ }
5
+ function isOpenAPIV3_1(value) {
6
+ return typeof value == "object" && value !== null && "openapi" in value && value.openapi === "3.1.0";
7
+ }
2
8
  function isReferenceObject(value) {
3
9
  return typeof value == "object" && value !== null && "$ref" in value && typeof value.$ref == "string";
4
10
  }
@@ -28,9 +34,13 @@ function resolveDocument(value, document = value) {
28
34
  }
29
35
  export {
30
36
  g as getServerUrl,
37
+ isOpenAPIV2,
38
+ i as isOpenAPIV3,
39
+ isOpenAPIV3_1,
31
40
  isReferenceObject,
32
41
  resolveDocument,
33
42
  r as resolveOperation,
43
+ a as resolveOperationTokenOptions,
34
44
  resolveReference
35
45
  };
36
46
  //# sourceMappingURL=openapi.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"openapi.js","sources":["../openapi/isReferenceObject.ts","../openapi/resolveReference.ts","../openapi/resolveDocument.ts"],"sourcesContent":["import type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'\n\nexport type OpenAPIReference =\n | OpenAPIV2.ReferenceObject\n | OpenAPIV3.ReferenceObject\n | OpenAPIV3_1.ReferenceObject\n\n/**\n * Check if a value is an {@linkcode OpenAPIReference}.\n *\n * @param value The value to check.\n * @returns `true` if the value is a reference object.\n * @example isReferenceObject({ $ref: '#/components/schemas/MySchema' }) // true\n */\nexport function isReferenceObject<T extends OpenAPIReference>(value: unknown): value is T {\n return typeof value === 'object'\n && value !== null\n && '$ref' in value\n && typeof value.$ref === 'string'\n}\n","import type { StringJoin, StringReplace, WriteableDeep } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport { isReferenceObject } from './isReferenceObject'\n\n/**\n * Decode an OpenAPI reference path by replacing the encoded characters with\n * their original values. This function will replace `~0` with `~` and `~1`\n * with `/`.\n *\n * @example DecodeReference<'#/foo~1bar~0baz'> // '#/foo/bar~baz'\n */\nexport type OpenAPIReferenceDecoded<T extends string> =\n StringReplace<StringReplace<T, '~0', '~'>, '~1', '/'>\n\n/**\n * Extract the parts of a reference path as a tuple.\n *\n * @example OpenAPIV3ReferencePath<'#/paths/~1users~1{username}'> // ['paths', '/users/{username}']\n */\nexport type OpenAPIReferencePath<T extends string> =\n T extends `#/${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `#/${infer P}` ? [P]\n : T extends `${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `${infer P}` ? [P]\n : []\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The result type.\n * @example Resolved<{ $ref: '#/info' }, { info: { title: string } }> // { title: string }\n */\nexport type OpenAPIReferenceResolved<\n T extends OpenAPIReference,\n D extends object,\n> =\n D extends object\n ? T extends { $ref: infer R extends string }\n\n // --- Match last part of the reference.\n ? OpenAPIReferencePath<R> extends [infer P extends string]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? WriteableDeep<Omit<D[OpenAPIReferenceDecoded<P>], keyof T>>\n : never\n : never\n\n // --- Match middle part of the reference.\n : OpenAPIReferencePath<R> extends [infer P extends string, ...infer Rest extends string[]]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? OpenAPIReferenceResolved<{ $ref: StringJoin<Rest, '/'> }, D[OpenAPIReferenceDecoded<P>]>\n : never\n : never\n : never\n : never\n : never\n\n/**\n * Resolve an OpenAPI `ReferenceObject` to the component it references. If the\n * source is not a reference, the source will be returned.\n *\n * @private\n * @param reference The reference object to resolve.\n * @param document The OpenAPI document to resolve the reference from.\n * @returns The result component.\n * @example resolveReference({ $ref: '#/components/schemas/User' }, document)\n */\nexport function resolveReference<\n T extends OpenAPIReference,\n D extends object,\n>(reference: Readonly<T>, document: Readonly<D>): OpenAPIReferenceResolved<T, D> {\n\n // --- Return the source if it is not a reference.\n if (!isReferenceObject(reference))\n throw new TypeError('Expected value to be an OpenAPI reference object.')\n\n // --- Assert that the parameters are valid.\n if (typeof document !== 'object' || document === null)\n throw new TypeError('Expected OpenAPI specification to be an object.')\n\n // --- Resolve the component with it's reference path.\n const referenceParts = reference.$ref.replace(/^#\\//, '').split('/')\n let result = document\n for (const part of referenceParts) {\n if (result === undefined) break\n if (typeof result !== 'object' || result === null) break\n const key = part.replaceAll('~1', '/').replaceAll('~0', '~')\n // @ts-expect-error: assume the part is a key of the object.\n result = result[key] as unknown\n }\n\n // --- Throw an error if the component could not be result.\n if (result === undefined)\n throw new Error(`Could not resolve OpenAPI component: ${reference.$ref}`)\n\n // --- Return the result component.\n return result as OpenAPIReferenceResolved<T, D>\n}\n","import type { ObjectLike, Substract } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport type { OpenAPIReferenceResolved } from './resolveReference'\nimport { isReferenceObject } from './isReferenceObject'\nimport { resolveReference as resolveReference } from './resolveReference'\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The resolved type.\n * @example\n * type Resolved = OpenAPIResolved<{\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' }\n * }\n * }\n * }>\n */\nexport type OpenAPIResolved<T, D = T, N extends number = 8> =\n N extends 0 ? T\n : T extends OpenAPIReference\n ? D extends object ? OpenAPIResolved<OpenAPIReferenceResolved<T, D>, D, Substract<N, 1>> : never\n : T extends object ? { -readonly [K in keyof T]: OpenAPIResolved<T[K], D, N> } : T\n\n/**\n * Recursively resolve all references in an OpenAPI specification. This function\n * will return a `Proxy` object that will resolve references on the fly.\n *\n * @param value The OpenAPI specification.\n * @returns The resolved OpenAPI specification.\n * @example\n * const resolved = resolveReferences({\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' },\n * },\n * },\n * })\n */\nexport function resolveDocument<T extends object>(value: Readonly<T>): OpenAPIResolved<T>\nexport function resolveDocument<T extends object, D>(value: Readonly<T>, document: Readonly<D>): OpenAPIResolved<T, D>\nexport function resolveDocument(value: Readonly<ObjectLike>, document = value): unknown {\n return new Proxy(value, {\n get(target, property: string) {\n let value = target[property]\n\n // --- Abort if no document is provided.\n if (!document) return value\n\n // --- Resolve the reference if it is a reference object.\n if (isReferenceObject(value))\n value = resolveReference(value, document)\n\n // --- Recursively resolve references in objects.\n if (typeof value === 'object' && value !== null)\n return resolveDocument(value as ObjectLike, document)\n\n // --- Return the value as is.\n return value\n },\n })\n}\n"],"names":["value"],"mappings":";AAcO,SAAS,kBAA8C,OAA4B;AACjF,SAAA,OAAO,SAAU,YACnB,UAAU,QACV,UAAU,SACV,OAAO,MAAM,QAAS;AAC7B;ACmDgB,SAAA,iBAGd,WAAwB,UAAuD;AAG3E,MAAA,CAAC,kBAAkB,SAAS;AACxB,UAAA,IAAI,UAAU,mDAAmD;AAGrE,MAAA,OAAO,YAAa,YAAY,aAAa;AACzC,UAAA,IAAI,UAAU,iDAAiD;AAGjE,QAAA,iBAAiB,UAAU,KAAK,QAAQ,QAAQ,EAAE,EAAE,MAAM,GAAG;AACnE,MAAI,SAAS;AACb,aAAW,QAAQ,gBAAgB;AAEjC,QADI,WAAW,UACX,OAAO,UAAW,YAAY,WAAW,KAAM;AAC7C,UAAA,MAAM,KAAK,WAAW,MAAM,GAAG,EAAE,WAAW,MAAM,GAAG;AAE3D,aAAS,OAAO,GAAG;AAAA,EAAA;AAIrB,MAAI,WAAW;AACb,UAAM,IAAI,MAAM,wCAAwC,UAAU,IAAI,EAAE;AAGnE,SAAA;AACT;ACtDgB,SAAA,gBAAgB,OAA6B,WAAW,OAAgB;AAC/E,SAAA,IAAI,MAAM,OAAO;AAAA,IACtB,IAAI,QAAQ,UAAkB;AACxBA,UAAAA,SAAQ,OAAO,QAAQ;AAG3B,aAAK,YAGD,kBAAkBA,MAAK,MACzBA,SAAQ,iBAAiBA,QAAO,QAAQ,IAGtC,OAAOA,UAAU,YAAYA,WAAU,OAClC,gBAAgBA,QAAqB,QAAQ,IAG/CA,UAXeA;AAAAA,IAAA;AAAA,EAYxB,CACD;AACH;"}
1
+ {"version":3,"file":"openapi.js","sources":["../openapi/isOpenAPIV2.ts","../openapi/isOpenAPIV3_1.ts","../openapi/isReferenceObject.ts","../openapi/resolveReference.ts","../openapi/resolveDocument.ts"],"sourcesContent":["/* eslint-disable unicorn/filename-case */\nimport type { OpenAPIV2 } from 'openapi-types'\n\n/**\n * Check if the given document is an OpenAPI v2 specification.\n *\n * @param value The document to check.\n * @returns `true` if the document is an OpenAPI v2 specification, `false` otherwise.\n * @example isOpenAPIV2({ swagger: '2.0', info: { title: 'Test API', version: '1.0.0' } }) // => true\n */\nexport function isOpenAPIV2(value: unknown): value is OpenAPIV2.Document {\n return typeof value === 'object'\n && value !== null\n && 'swagger' in value\n && value.swagger === '2.0'\n}\n","/* eslint-disable unicorn/filename-case */\nimport type { OpenAPIV3_1 } from 'openapi-types'\n\n/**\n * Check if the given document is an OpenAPI v3.1 specification.\n *\n * @param value The document to check.\n * @returns `true` if the document is an OpenAPI v3.1 specification, `false` otherwise.\n * @example isOpenAPIV3_1({ openapi: '3.1.0', info: { title: 'Test API', version: '1.0.0' } }) // => true\n */\nexport function isOpenAPIV3_1(value: unknown): value is OpenAPIV3_1.Document {\n return typeof value === 'object'\n && value !== null\n && 'openapi' in value\n && value.openapi === '3.1.0'\n}\n","import type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'\n\nexport type OpenAPIReference =\n | OpenAPIV2.ReferenceObject\n | OpenAPIV3.ReferenceObject\n | OpenAPIV3_1.ReferenceObject\n\n/**\n * Check if a value is an {@linkcode OpenAPIReference}.\n *\n * @param value The value to check.\n * @returns `true` if the value is a reference object.\n * @example isReferenceObject({ $ref: '#/components/schemas/MySchema' }) // true\n */\nexport function isReferenceObject<T extends OpenAPIReference>(value: unknown): value is T {\n return typeof value === 'object'\n && value !== null\n && '$ref' in value\n && typeof value.$ref === 'string'\n}\n","import type { StringJoin, StringReplace, WriteableDeep } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport { isReferenceObject } from './isReferenceObject'\n\n/**\n * Decode an OpenAPI reference path by replacing the encoded characters with\n * their original values. This function will replace `~0` with `~` and `~1`\n * with `/`.\n *\n * @example DecodeReference<'#/foo~1bar~0baz'> // '#/foo/bar~baz'\n */\nexport type OpenAPIReferenceDecoded<T extends string> =\n StringReplace<StringReplace<T, '~0', '~'>, '~1', '/'>\n\n/**\n * Extract the parts of a reference path as a tuple.\n *\n * @example OpenAPIV3ReferencePath<'#/paths/~1users~1{username}'> // ['paths', '/users/{username}']\n */\nexport type OpenAPIReferencePath<T extends string> =\n T extends `#/${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `#/${infer P}` ? [P]\n : T extends `${infer P}/${infer Rest}` ? [P, ...OpenAPIReferencePath<Rest>]\n : T extends `${infer P}` ? [P]\n : []\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The result type.\n * @example Resolved<{ $ref: '#/info' }, { info: { title: string } }> // { title: string }\n */\nexport type OpenAPIReferenceResolved<\n T extends OpenAPIReference,\n D extends object,\n> =\n D extends object\n ? T extends { $ref: infer R extends string }\n\n // --- Match last part of the reference.\n ? OpenAPIReferencePath<R> extends [infer P extends string]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? WriteableDeep<Omit<D[OpenAPIReferenceDecoded<P>], keyof T>>\n : never\n : never\n\n // --- Match middle part of the reference.\n : OpenAPIReferencePath<R> extends [infer P extends string, ...infer Rest extends string[]]\n ? OpenAPIReferenceDecoded<P> extends keyof D\n ? D[OpenAPIReferenceDecoded<P>] extends object\n ? OpenAPIReferenceResolved<{ $ref: StringJoin<Rest, '/'> }, D[OpenAPIReferenceDecoded<P>]>\n : never\n : never\n : never\n : never\n : never\n\n/**\n * Resolve an OpenAPI `ReferenceObject` to the component it references. If the\n * source is not a reference, the source will be returned.\n *\n * @private\n * @param reference The reference object to resolve.\n * @param document The OpenAPI document to resolve the reference from.\n * @returns The result component.\n * @example resolveReference({ $ref: '#/components/schemas/User' }, document)\n */\nexport function resolveReference<\n T extends OpenAPIReference,\n D extends object,\n>(reference: Readonly<T>, document: Readonly<D>): OpenAPIReferenceResolved<T, D> {\n\n // --- Return the source if it is not a reference.\n if (!isReferenceObject(reference))\n throw new TypeError('Expected value to be an OpenAPI reference object.')\n\n // --- Assert that the parameters are valid.\n if (typeof document !== 'object' || document === null)\n throw new TypeError('Expected OpenAPI specification to be an object.')\n\n // --- Resolve the component with it's reference path.\n const referenceParts = reference.$ref.replace(/^#\\//, '').split('/')\n let result = document\n for (const part of referenceParts) {\n if (result === undefined) break\n if (typeof result !== 'object' || result === null) break\n const key = part.replaceAll('~1', '/').replaceAll('~0', '~')\n // @ts-expect-error: assume the part is a key of the object.\n result = result[key] as unknown\n }\n\n // --- Throw an error if the component could not be result.\n if (result === undefined)\n throw new Error(`Could not resolve OpenAPI component: ${reference.$ref}`)\n\n // --- Return the result component.\n return result as OpenAPIReferenceResolved<T, D>\n}\n","import type { ObjectLike, Substract } from '@unshared/types'\nimport type { OpenAPIReference } from './isReferenceObject'\nimport type { OpenAPIReferenceResolved } from './resolveReference'\nimport { isReferenceObject } from './isReferenceObject'\nimport { resolveReference as resolveReference } from './resolveReference'\n\n/**\n * Resolve a type to the type it references. If the source is not a reference,\n * the source will be returned.\n *\n * @template T The type to resolve.\n * @returns The resolved type.\n * @example\n * type Resolved = OpenAPIResolved<{\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' }\n * }\n * }\n * }>\n */\nexport type OpenAPIResolved<T, D = T, N extends number = 8> =\n N extends 0 ? T\n : T extends OpenAPIReference\n ? D extends object ? OpenAPIResolved<OpenAPIReferenceResolved<T, D>, D, Substract<N, 1>> : never\n : T extends object ? { -readonly [K in keyof T]: OpenAPIResolved<T[K], D, N> } : T\n\n/**\n * Recursively resolve all references in an OpenAPI specification. This function\n * will return a `Proxy` object that will resolve references on the fly.\n *\n * @param value The OpenAPI specification.\n * @returns The resolved OpenAPI specification.\n * @example\n * const resolved = resolveReferences({\n * ...\n * paths: {\n * '/users': {\n * get: { $ref: '#/components/routes/getUsers' },\n * },\n * },\n * })\n */\nexport function resolveDocument<T extends object>(value: Readonly<T>): OpenAPIResolved<T>\nexport function resolveDocument<T extends object, D>(value: Readonly<T>, document: Readonly<D>): OpenAPIResolved<T, D>\nexport function resolveDocument(value: Readonly<ObjectLike>, document = value): unknown {\n return new Proxy(value, {\n get(target, property: string) {\n let value = target[property]\n\n // --- Abort if no document is provided.\n if (!document) return value\n\n // --- Resolve the reference if it is a reference object.\n if (isReferenceObject(value))\n value = resolveReference(value, document)\n\n // --- Recursively resolve references in objects.\n if (typeof value === 'object' && value !== null)\n return resolveDocument(value as ObjectLike, document)\n\n // --- Return the value as is.\n return value\n },\n })\n}\n"],"names":["value"],"mappings":";AAUO,SAAS,YAAY,OAA6C;AAChE,SAAA,OAAO,SAAU,YACnB,UAAU,QACV,aAAa,SACb,MAAM,YAAY;AACzB;ACLO,SAAS,cAAc,OAA+C;AACpE,SAAA,OAAO,SAAU,YACnB,UAAU,QACV,aAAa,SACb,MAAM,YAAY;AACzB;ACDO,SAAS,kBAA8C,OAA4B;AACjF,SAAA,OAAO,SAAU,YACnB,UAAU,QACV,UAAU,SACV,OAAO,MAAM,QAAS;AAC7B;ACmDgB,SAAA,iBAGd,WAAwB,UAAuD;AAG3E,MAAA,CAAC,kBAAkB,SAAS;AACxB,UAAA,IAAI,UAAU,mDAAmD;AAGrE,MAAA,OAAO,YAAa,YAAY,aAAa;AACzC,UAAA,IAAI,UAAU,iDAAiD;AAGjE,QAAA,iBAAiB,UAAU,KAAK,QAAQ,QAAQ,EAAE,EAAE,MAAM,GAAG;AACnE,MAAI,SAAS;AACb,aAAW,QAAQ,gBAAgB;AAEjC,QADI,WAAW,UACX,OAAO,UAAW,YAAY,WAAW,KAAM;AAC7C,UAAA,MAAM,KAAK,WAAW,MAAM,GAAG,EAAE,WAAW,MAAM,GAAG;AAE3D,aAAS,OAAO,GAAG;AAAA,EAAA;AAIrB,MAAI,WAAW;AACb,UAAM,IAAI,MAAM,wCAAwC,UAAU,IAAI,EAAE;AAGnE,SAAA;AACT;ACtDgB,SAAA,gBAAgB,OAA6B,WAAW,OAAgB;AAC/E,SAAA,IAAI,MAAM,OAAO;AAAA,IACtB,IAAI,QAAQ,UAAkB;AACxBA,UAAAA,SAAQ,OAAO,QAAQ;AAG3B,aAAK,YAGD,kBAAkBA,MAAK,MACzBA,SAAQ,iBAAiBA,QAAO,QAAQ,IAGtC,OAAOA,UAAU,YAAYA,WAAU,OAClC,gBAAgBA,QAAqB,QAAQ,IAG/CA,UAXeA;AAAAA,IAAA;AAAA,EAYxB,CACD;AACH;"}
package/dist/utils.cjs CHANGED
@@ -1,18 +1,30 @@
1
1
  "use strict";
2
- var handleResponse = require("./chunks/Cayg8606.cjs"), parseRequestQuery = require("./chunks/CYmaYL5B.cjs"), request = require("./chunks/Du_W5H6e.cjs");
2
+ var request = require("./chunks/DXrQkl1A.cjs"), handleResponse = require("./chunks/CVzmr2NA.cjs"), parseRequestQuery = require("./chunks/BDxlAULu.cjs");
3
3
  require("@unshared/functions/awaitable");
4
- exports.fetch = handleResponse.fetch;
4
+ function getCookie(headers, key) {
5
+ const cookie = handleResponse.getCookies(headers);
6
+ if (cookie)
7
+ return cookie[key];
8
+ }
9
+ exports.fetch = request.fetch;
10
+ exports.request = request.request;
11
+ exports.getCookies = handleResponse.getCookies;
12
+ exports.getHeader = handleResponse.getHeader;
5
13
  exports.handleResponse = handleResponse.handleResponse;
6
14
  exports.handleResponseStreamJson = handleResponse.handleResponseStreamJson;
7
15
  exports.isFormDataLike = handleResponse.isFormDataLike;
8
16
  exports.isObjectLike = handleResponse.isObjectLike;
9
17
  exports.parseRequest = handleResponse.parseRequest;
18
+ exports.parseRequestBasicAuth = handleResponse.parseRequestBasicAuth;
10
19
  exports.parseRequestBody = handleResponse.parseRequestBody;
11
20
  exports.parseRequestHeaders = handleResponse.parseRequestHeaders;
21
+ exports.parseRequestToken = handleResponse.parseRequestToken;
12
22
  exports.parseRequestUrl = handleResponse.parseRequestUrl;
23
+ exports.setCookie = handleResponse.setCookie;
24
+ exports.setHeader = handleResponse.setHeader;
13
25
  exports.toFormData = handleResponse.toFormData;
14
26
  exports.parseRequestParameters = parseRequestQuery.parseRequestParameters;
15
27
  exports.parseRequestQuery = parseRequestQuery.parseRequestQuery;
16
28
  exports.toSearchParams = parseRequestQuery.toSearchParams;
17
- exports.request = request.request;
29
+ exports.getCookie = getCookie;
18
30
  //# sourceMappingURL=utils.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"utils.cjs","sources":["../utils/getCookie.ts"],"sourcesContent":["import { getCookies } from './getCookies'\n\n/**\n * Get a cookie value from the `HeadersInit` object.\n *\n * @param headers The headers to get the cookie value from.\n * @param key The key of the cookie to get.\n * @returns The value of the cookie.\n * @example\n * const headers = new Headers({ Cookie: 'key1=value1; key2=value2' })\n * const value = getCookie(headers, 'key1')\n */\nexport function getCookie(headers: HeadersInit, key: string): string | undefined {\n const cookie = getCookies(headers)\n if (!cookie) return\n return cookie[key]\n}\n"],"names":["getCookies"],"mappings":";;;AAYgB,SAAA,UAAU,SAAsB,KAAiC;AACzE,QAAA,SAASA,0BAAW,OAAO;AAC5B,MAAA;AACL,WAAO,OAAO,GAAG;AACnB;;;;;;;;;;;;;;;;;;;;;;"}
package/dist/utils.d.ts CHANGED
@@ -1,5 +1,5 @@
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';
1
+ import { a as FetchOptions, R as RequestOptions, b as RequestContext } from './chunks/BZ5qrH6f.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/BZ5qrH6f.js';
3
3
  import { Awaitable } from '@unshared/functions/awaitable';
4
4
  import { ObjectLike } from '@unshared/types';
5
5
  import './HttpHeaders.js';
@@ -16,6 +16,42 @@ import './HttpMethods.js';
16
16
  */
17
17
  declare function fetch(route: string, options?: FetchOptions): Promise<Response>;
18
18
 
19
+ /**
20
+ * Get a cookie value from the `HeadersInit` object.
21
+ *
22
+ * @param headers The headers to get the cookie value from.
23
+ * @param key The key of the cookie to get.
24
+ * @returns The value of the cookie.
25
+ * @example
26
+ * const headers = new Headers({ Cookie: 'key1=value1; key2=value2' })
27
+ * const value = getCookie(headers, 'key1')
28
+ */
29
+ declare function getCookie(headers: HeadersInit, key: string): string | undefined;
30
+
31
+ /**
32
+ * Extract the cookies from the `HeadersInit` object.
33
+ *
34
+ * @param headers The headers to extract the cookies from.
35
+ * @returns An array of cookies.
36
+ * @example
37
+ * const headers = new Headers({ Cookie: 'key1=value1; key2=value2' })
38
+ * const cookies = getCookies(headers) // { key1: 'value1', key2: 'value2' }
39
+ */
40
+ declare function getCookies(headers: HeadersInit): Record<string, string>;
41
+
42
+ /**
43
+ * Get a header value from the `HeadersInit` object.
44
+ *
45
+ * @param headers The headers to get the key-value pair from.
46
+ * @param key The key of the header to get.
47
+ * @returns The value of the header.
48
+ * @example
49
+ * const headers = new Headers({ 'Content-Type': 'application/json' })
50
+ * const contentType = getHeader(headers, 'Content-Type')
51
+ * console.log(contentType) // 'application/json'
52
+ */
53
+ declare function getHeader(headers: HeadersInit, key: string): string | undefined;
54
+
19
55
  /**
20
56
  * Handle a request response. This function will parse the response based on the content type and
21
57
  * return the data. If an error occurs, the `onError` callback will be called and the function will
@@ -62,13 +98,29 @@ declare function isFormDataLike(value: unknown): value is FormDataLike;
62
98
  */
63
99
  declare function isObjectLike(value: unknown): value is ObjectLike;
64
100
 
101
+ /**
102
+ * Parse the basic authentication headers based on the provided username and password.
103
+ *
104
+ * @param context The request context.
105
+ * @param options The request options.
106
+ * @example
107
+ *
108
+ * // Append the `Authorization` header to the request.
109
+ * const context = {}
110
+ * parseRequestBasicAuth(context, { username: 'user', password: 'pass' })
111
+ *
112
+ * // Will mutate the `init` object to include the headers.
113
+ * console.log(context) // => { init: { headers: { 'Authorization': 'Basic dXNlcjpwYXNz' } } }
114
+ */
115
+ declare function parseRequestBasicAuth(context: Partial<RequestContext>, options: FetchOptions): void;
116
+
65
117
  /**
66
118
  * Parse the request body based on the provided data and options.
67
119
  *
68
120
  * @param context The request context.
69
121
  * @param options The request options.
70
122
  */
71
- declare function parseRequestBody(context: RequestContext, options: FetchOptions): void;
123
+ declare function parseRequestBody(context: Partial<RequestContext>, options: FetchOptions): void;
72
124
 
73
125
  /**
74
126
  * Parse the request headers based on the provided data and options.
@@ -84,7 +136,7 @@ declare function parseRequestBody(context: RequestContext, options: FetchOptions
84
136
  * // Will mutate the `init` object to include the headers.
85
137
  * console.log(context) // => { init: { headers: { 'Content-Type': 'application/json' } } }
86
138
  */
87
- declare function parseRequestHeaders(context: RequestContext, options: FetchOptions): void;
139
+ declare function parseRequestHeaders(context: Partial<RequestContext>, options: FetchOptions): void;
88
140
 
89
141
  /**
90
142
  * Parse the request parameters from the request data. This function will mutate the
@@ -104,7 +156,7 @@ declare function parseRequestHeaders(context: RequestContext, options: FetchOpti
104
156
  * parseRequestParameters(context, { parameters: { id: 1 } })
105
157
  * console.log(context.url.pathname) // 'https://api.example.com/users/1'
106
158
  */
107
- declare function parseRequestParameters(context: RequestContext, options: FetchOptions): void;
159
+ declare function parseRequestParameters(context: Partial<RequestContext>, options: FetchOptions): void;
108
160
 
109
161
  /**
110
162
  * Parse the query parameters from the request data. This function will append
@@ -113,7 +165,32 @@ declare function parseRequestParameters(context: RequestContext, options: FetchO
113
165
  * @param context The request context to modify.
114
166
  * @param options The options to pass to the request.
115
167
  */
116
- declare function parseRequestQuery(context: RequestContext, options: FetchOptions): void;
168
+ declare function parseRequestQuery(context: Partial<RequestContext>, options: FetchOptions): void;
169
+
170
+ /**
171
+ * Parse the token and dynamically extend either the query, headers, or cookies.
172
+ *
173
+ * @param context The request context.
174
+ * @param options The request options.
175
+ * @example
176
+ * // Append the `token` to the query parameters.
177
+ * const context = { url: new URL('https://example.com') }
178
+ * parseRequestToken(context, { token: 'my-token', tokenLocation: 'query', tokenProperty: 'token' })
179
+ * console.log(context.url.searchParams.get('token')) // 'my-token'
180
+ *
181
+ * @example
182
+ * // Append the `token` to the headers.
183
+ * const context = { init: { headers: new Headers() } }
184
+ * parseRequestToken(context, { token: 'my-token', tokenLocation: 'header', tokenProperty: 'Authorization' })
185
+ * console.log(context.init.headers.get('Authorization')) // 'Bearer my-token'
186
+ *
187
+ * @example
188
+ * // Append the `token` to the cookies.
189
+ * const context = { init: { headers: new Headers() } }
190
+ * parseRequestToken(context, { token: 'my-token', tokenLocation: 'cookie', tokenProperty: 'token' })
191
+ * console.log(context.init.headers.get('Cookie')) // 'token=my-token'
192
+ */
193
+ declare function parseRequestToken(context: Partial<RequestContext>, options: FetchOptions): void;
117
194
 
118
195
  /**
119
196
  * Parses the route name to extract the URL and method. It allows the url and method to be
@@ -124,7 +201,36 @@ declare function parseRequestQuery(context: RequestContext, options: FetchOption
124
201
  * @param options The options to pass to the request.
125
202
  * @example parseRequestUrl('GET /users', { baseUrl: 'https://api.example.com' }, context)
126
203
  */
127
- declare function parseRequestUrl(context: RequestContext, route: string, options: FetchOptions): void;
204
+ declare function parseRequestUrl(context: Partial<RequestContext>, route: string, options: FetchOptions): void;
205
+
206
+ /**
207
+ * Set a cookie in the `HeadersInit` object.
208
+ *
209
+ * @param headers The headers to set the cookie in.
210
+ * @param key The key of the cookie to set.
211
+ * @param value The value of the cookie to set.
212
+ * @example
213
+ * const headers = new Headers()
214
+ * const cookie = { key: 'key1', value: 'value1', path: '/', secure: true }
215
+ * setCookie(headers, cookie)
216
+ * console.log(headers.get('Cookie')) // 'key1=value1; Path=/; Secure'
217
+ */
218
+ declare function setCookie(headers: HeadersInit, key: string, value: string): void;
219
+
220
+ /**
221
+ * Set a header in the `HeadersInit` object whether it is a `Headers` instance, an
222
+ * array of key-value pairs, or an object. It is also case-insensitive, meaning that
223
+ * if a header with the same key but different case is found, it will be replaced.
224
+ *
225
+ * @param headers The headers to set the key-value pair in.
226
+ * @param key The key of the header to set.
227
+ * @param value The value of the header to set.
228
+ * @example
229
+ * const headers = new Headers()
230
+ * setHeader(headers, 'Content-Type', 'application/json')
231
+ * console.log(headers.get('Content-Type')) // 'application/json'
232
+ */
233
+ declare function setHeader(headers: HeadersInit, key: string, value: number | string): void;
128
234
 
129
235
  /**
130
236
  * Casts an object that may contain `Blob`, `File`, or `FileList` values to a `FormData` object.
@@ -134,4 +240,4 @@ declare function parseRequestUrl(context: RequestContext, route: string, options
134
240
  */
135
241
  declare function toFormData(object: FormDataLike): FormData;
136
242
 
137
- export { FetchOptions, type FormDataLike, RequestContext, RequestOptions, fetch, handleResponse, handleResponseStreamJson, isFormDataLike, isObjectLike, parseRequestBody, parseRequestHeaders, parseRequestParameters, parseRequestQuery, parseRequestUrl, toFormData };
243
+ export { FetchOptions, type FormDataLike, RequestContext, RequestOptions, fetch, getCookie, getCookies, getHeader, handleResponse, handleResponseStreamJson, isFormDataLike, isObjectLike, parseRequestBasicAuth, parseRequestBody, parseRequestHeaders, parseRequestParameters, parseRequestQuery, parseRequestToken, parseRequestUrl, setCookie, setHeader, toFormData };