@warp-drive/utilities 5.9.0-beta.0 → 5.9.0-beta.2

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 (158) hide show
  1. package/cjs-dist/string.cjs +448 -0
  2. package/cjs-dist/string.cjs.map +1 -0
  3. package/dist/-private.d.ts +12 -0
  4. package/dist/-private.d.ts.map +1 -0
  5. package/dist/-private.js +2 -6
  6. package/dist/active-record.d.ts +260 -0
  7. package/dist/active-record.d.ts.map +1 -0
  8. package/dist/active-record.js +254 -379
  9. package/dist/active-record.js.map +1 -0
  10. package/dist/builder-utils-BkXwUT0x.js +16 -0
  11. package/dist/builder-utils-BkXwUT0x.js.map +1 -0
  12. package/dist/derivations.d.ts +30 -0
  13. package/dist/derivations.d.ts.map +1 -0
  14. package/dist/derivations.js +26 -26
  15. package/dist/derivations.js.map +1 -0
  16. package/dist/handlers.d.ts +283 -0
  17. package/dist/handlers.d.ts.map +1 -0
  18. package/dist/handlers.js +240 -283
  19. package/dist/handlers.js.map +1 -0
  20. package/dist/index-BeMAuqgZ.d.ts +462 -0
  21. package/dist/index-BeMAuqgZ.d.ts.map +1 -0
  22. package/dist/index.d.ts +2 -0
  23. package/dist/index.js +357 -335
  24. package/dist/index.js.map +1 -0
  25. package/dist/inflections-DzBsjJqj.js +80 -0
  26. package/dist/inflections-DzBsjJqj.js.map +1 -0
  27. package/dist/json-api.d.ts +496 -0
  28. package/dist/json-api.d.ts.map +1 -0
  29. package/dist/json-api.js +470 -706
  30. package/dist/json-api.js.map +1 -0
  31. package/dist/rest.d.ts +258 -0
  32. package/dist/rest.d.ts.map +1 -0
  33. package/dist/rest.js +254 -377
  34. package/dist/rest.js.map +1 -0
  35. package/dist/string-CWmAluxh.js +290 -0
  36. package/dist/string-CWmAluxh.js.map +1 -0
  37. package/dist/string.d.ts +165 -0
  38. package/dist/string.d.ts.map +1 -0
  39. package/dist/string.js +2 -427
  40. package/dist/unpkg/dev/-private.js +2 -6
  41. package/dist/unpkg/dev/active-record.js +253 -378
  42. package/dist/unpkg/dev/active-record.js.map +1 -0
  43. package/dist/unpkg/dev/builder-utils-BkXwUT0x.js +16 -0
  44. package/dist/unpkg/dev/builder-utils-BkXwUT0x.js.map +1 -0
  45. package/dist/unpkg/dev/derivations.js +26 -26
  46. package/dist/unpkg/dev/derivations.js.map +1 -0
  47. package/dist/unpkg/dev/handlers.js +238 -282
  48. package/dist/unpkg/dev/handlers.js.map +1 -0
  49. package/dist/unpkg/dev/index.js +356 -336
  50. package/dist/unpkg/dev/index.js.map +1 -0
  51. package/dist/unpkg/dev/inflections-DzBsjJqj.js +80 -0
  52. package/dist/unpkg/dev/inflections-DzBsjJqj.js.map +1 -0
  53. package/dist/unpkg/dev/json-api.js +469 -706
  54. package/dist/unpkg/dev/json-api.js.map +1 -0
  55. package/dist/unpkg/dev/rest.js +253 -376
  56. package/dist/unpkg/dev/rest.js.map +1 -0
  57. package/dist/unpkg/dev/string-j4ur-TDs.js +289 -0
  58. package/dist/unpkg/dev/string-j4ur-TDs.js.map +1 -0
  59. package/dist/unpkg/dev/string.js +3 -1
  60. package/dist/unpkg/dev-deprecated/-private.js +2 -6
  61. package/dist/unpkg/dev-deprecated/active-record.js +253 -378
  62. package/dist/unpkg/dev-deprecated/active-record.js.map +1 -0
  63. package/dist/unpkg/dev-deprecated/builder-utils-BkXwUT0x.js +16 -0
  64. package/dist/unpkg/dev-deprecated/builder-utils-BkXwUT0x.js.map +1 -0
  65. package/dist/unpkg/dev-deprecated/derivations.js +26 -26
  66. package/dist/unpkg/dev-deprecated/derivations.js.map +1 -0
  67. package/dist/unpkg/dev-deprecated/handlers.js +238 -282
  68. package/dist/unpkg/dev-deprecated/handlers.js.map +1 -0
  69. package/dist/unpkg/dev-deprecated/index.js +356 -336
  70. package/dist/unpkg/dev-deprecated/index.js.map +1 -0
  71. package/dist/unpkg/dev-deprecated/inflections-DzBsjJqj.js +80 -0
  72. package/dist/unpkg/dev-deprecated/inflections-DzBsjJqj.js.map +1 -0
  73. package/dist/unpkg/dev-deprecated/json-api.js +469 -706
  74. package/dist/unpkg/dev-deprecated/json-api.js.map +1 -0
  75. package/dist/unpkg/dev-deprecated/rest.js +253 -376
  76. package/dist/unpkg/dev-deprecated/rest.js.map +1 -0
  77. package/dist/unpkg/dev-deprecated/string-j4ur-TDs.js +289 -0
  78. package/dist/unpkg/dev-deprecated/string-j4ur-TDs.js.map +1 -0
  79. package/dist/unpkg/dev-deprecated/string.js +3 -1
  80. package/dist/unpkg/prod/-private.js +2 -6
  81. package/dist/unpkg/prod/active-record.js +236 -351
  82. package/dist/unpkg/prod/active-record.js.map +1 -0
  83. package/dist/unpkg/prod/builder-utils-BkXwUT0x.js +16 -0
  84. package/dist/unpkg/prod/builder-utils-BkXwUT0x.js.map +1 -0
  85. package/dist/unpkg/prod/derivations.js +26 -26
  86. package/dist/unpkg/prod/derivations.js.map +1 -0
  87. package/dist/unpkg/prod/handlers.js +231 -272
  88. package/dist/unpkg/prod/handlers.js.map +1 -0
  89. package/dist/unpkg/prod/index.js +265 -215
  90. package/dist/unpkg/prod/index.js.map +1 -0
  91. package/dist/unpkg/prod/inflections-DzBsjJqj.js +80 -0
  92. package/dist/unpkg/prod/inflections-DzBsjJqj.js.map +1 -0
  93. package/dist/unpkg/prod/json-api.js +446 -669
  94. package/dist/unpkg/prod/json-api.js.map +1 -0
  95. package/dist/unpkg/prod/rest.js +236 -349
  96. package/dist/unpkg/prod/rest.js.map +1 -0
  97. package/dist/unpkg/prod/string-T1ahjLdj.js +283 -0
  98. package/dist/unpkg/prod/string-T1ahjLdj.js.map +1 -0
  99. package/dist/unpkg/prod/string.js +3 -1
  100. package/dist/unpkg/prod-deprecated/-private.js +2 -6
  101. package/dist/unpkg/prod-deprecated/active-record.js +236 -351
  102. package/dist/unpkg/prod-deprecated/active-record.js.map +1 -0
  103. package/dist/unpkg/prod-deprecated/builder-utils-BkXwUT0x.js +16 -0
  104. package/dist/unpkg/prod-deprecated/builder-utils-BkXwUT0x.js.map +1 -0
  105. package/dist/unpkg/prod-deprecated/derivations.js +26 -26
  106. package/dist/unpkg/prod-deprecated/derivations.js.map +1 -0
  107. package/dist/unpkg/prod-deprecated/handlers.js +231 -272
  108. package/dist/unpkg/prod-deprecated/handlers.js.map +1 -0
  109. package/dist/unpkg/prod-deprecated/index.js +265 -215
  110. package/dist/unpkg/prod-deprecated/index.js.map +1 -0
  111. package/dist/unpkg/prod-deprecated/inflections-DzBsjJqj.js +80 -0
  112. package/dist/unpkg/prod-deprecated/inflections-DzBsjJqj.js.map +1 -0
  113. package/dist/unpkg/prod-deprecated/json-api.js +446 -669
  114. package/dist/unpkg/prod-deprecated/json-api.js.map +1 -0
  115. package/dist/unpkg/prod-deprecated/rest.js +236 -349
  116. package/dist/unpkg/prod-deprecated/rest.js.map +1 -0
  117. package/dist/unpkg/prod-deprecated/string-T1ahjLdj.js +283 -0
  118. package/dist/unpkg/prod-deprecated/string-T1ahjLdj.js.map +1 -0
  119. package/dist/unpkg/prod-deprecated/string.js +3 -1
  120. package/package.json +20 -23
  121. package/declarations/-private/active-record/find-record.d.ts +0 -64
  122. package/declarations/-private/active-record/query.d.ts +0 -53
  123. package/declarations/-private/active-record/save-record.d.ts +0 -146
  124. package/declarations/-private/builder-utils.d.ts +0 -4
  125. package/declarations/-private/handlers/auto-compress.d.ts +0 -158
  126. package/declarations/-private/handlers/gated.d.ts +0 -19
  127. package/declarations/-private/handlers/meta-doc.d.ts +0 -47
  128. package/declarations/-private/handlers/utils.d.ts +0 -41
  129. package/declarations/-private/json-api/-utils.d.ts +0 -109
  130. package/declarations/-private/json-api/find-record.d.ts +0 -84
  131. package/declarations/-private/json-api/query.d.ts +0 -100
  132. package/declarations/-private/json-api/save-record.d.ts +0 -228
  133. package/declarations/-private/json-api/serialize.d.ts +0 -70
  134. package/declarations/-private/rest/find-record.d.ts +0 -62
  135. package/declarations/-private/rest/query.d.ts +0 -53
  136. package/declarations/-private/rest/save-record.d.ts +0 -146
  137. package/declarations/-private/string/inflect.d.ts +0 -82
  138. package/declarations/-private/string/inflections.d.ts +0 -9
  139. package/declarations/-private/string/transform.d.ts +0 -77
  140. package/declarations/-private.d.ts +0 -1
  141. package/declarations/active-record.d.ts +0 -3
  142. package/declarations/derivations.d.ts +0 -27
  143. package/declarations/handlers.d.ts +0 -10
  144. package/declarations/index.d.ts +0 -208
  145. package/declarations/json-api.d.ts +0 -5
  146. package/declarations/rest.d.ts +0 -3
  147. package/declarations/string.d.ts +0 -14
  148. package/dist/builder-utils-Donkk-BZ.js +0 -22
  149. package/dist/inflect-BSG696t-.js +0 -344
  150. package/dist/string.cjs +0 -430
  151. package/dist/unpkg/dev/builder-utils-Donkk-BZ.js +0 -22
  152. package/dist/unpkg/dev/inflect-BEv8WqY1.js +0 -343
  153. package/dist/unpkg/dev-deprecated/builder-utils-Donkk-BZ.js +0 -22
  154. package/dist/unpkg/dev-deprecated/inflect-BEv8WqY1.js +0 -343
  155. package/dist/unpkg/prod/builder-utils-Donkk-BZ.js +0 -22
  156. package/dist/unpkg/prod/inflect-Dh9dyEYx.js +0 -333
  157. package/dist/unpkg/prod-deprecated/builder-utils-Donkk-BZ.js +0 -22
  158. package/dist/unpkg/prod-deprecated/inflect-Dh9dyEYx.js +0 -333
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handlers.js","names":["isCompressibleMethod","method","SupportsRequestStreams","duplexAccessed","hasContentType","Request","body","ReadableStream","duplex","headers","has","DEFAULT_CONSTRAINTS","Blob","ArrayBuffer","TypedArray","DataView","String","Object","getPrototypeOf","Uint8Array","AutoCompress","constructor","options","opts","format","constraints","assign","allowStreaming","forceStreaming","request","next","shouldCompress","compress","canCompress","length","size","byteLength","response","Response","stream","pipeThrough","CompressionStream","Headers","set","encodingForFormat","req","resp","blob","then","type","Gate","constructor","handler","checkFn","request","context","next","FastBoot","globalThis","addEventListener","sessionStorage","setItem","getTabId","crypto","randomUUID","tabId","getItem","tabClosed","newTabId","TAB_ID","TAB_ASSIGNED","Math","floor","Date","now","addTraceHeader","headers","set","MAX_URL_LENGTH","assertInvalidUrlLength","url"],"sources":["../../../src/-private/handlers/auto-compress.ts","../../../src/-private/handlers/gated.ts","../../../src/-private/handlers/meta-doc.ts","../../../src/-private/handlers/utils.ts"],"sourcesContent":["import { assert } from '@warp-drive/core/build-config/macros';\nimport type { Future, Handler, NextFn } from '@warp-drive/core/request';\nimport type { HTTPMethod, RequestContext } from '@warp-drive/core/types/request';\n\nfunction isCompressibleMethod(method?: HTTPMethod): boolean {\n return method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'DELETE';\n}\n\n/**\n * Whether the browser supports `ReadableStream` as a request body\n * in a `POST` request.\n *\n * @group Constants\n */\nexport const SupportsRequestStreams: boolean = (() => {\n let duplexAccessed = false;\n\n const hasContentType = new Request('', {\n body: new ReadableStream(),\n method: 'POST',\n // @ts-expect-error untyped\n get duplex() {\n duplexAccessed = true;\n return 'half';\n },\n }).headers.has('Content-Type');\n\n return duplexAccessed && !hasContentType;\n})();\n\ninterface Constraints {\n /**\n * The minimum size at which to compress blobs\n *\n * @default 1000\n */\n Blob?: number;\n /**\n * The minimum size at which to compress array buffers\n *\n * @default 1000\n */\n ArrayBuffer?: number;\n /**\n * The minimum size at which to compress typed arrays\n *\n * @default 1000\n */\n TypedArray?: number;\n /**\n * The minimum size at which to compress data views\n *\n * @default 1000\n */\n DataView?: number;\n /**\n * The minimum size at which to compress strings\n *\n * @default 1000\n */\n String?: number;\n}\n\n/**\n * Options for configuring the AutoCompress handler.\n *\n */\ninterface CompressionOptions {\n /**\n * The compression format to use. Must be a valid\n * compression format supported by [CompressionStream](https://developer.mozilla.org/en-US/docs/Web/API/CompressionStream)\n *\n * The default is `gzip`.\n *\n */\n format?: CompressionFormat;\n\n /**\n * Some browsers support `ReadableStream` as a request body. This option\n * enables passing the compression stream as the request body instead of\n * the final compressed body when the browser supports doing so.\n *\n * This comes with several caveats:\n *\n * - the request will be put into `duplex: 'half'` mode. This should be\n * transparent to you, but it is worth noting.\n * - the request mode cannot be `no-cors` as requests with a `ReadableStream`\n * have no content length and thus are a new form of request that triggers\n * cors requirements and a preflight request.\n * - http/1.x is not supported.\n *\n * For additional reading about the restrictions of using `ReadableStream`\n * as a request body, see the [Chromium Documentation](https://developer.chrome.com/docs/capabilities/web-apis/fetch-streaming-requests#restrictions)\n *\n * Streaming can be enabled per-request in browsers which support it by\n * setting `request.options.allowStreaming` to `true`.\n *\n * Streaming can be forced even when the browser does not support it by setting\n * `request.options.forceStreaming` to `true`. This is useful if later handlers\n * in the chain can handle the request body as a stream.\n *\n * @default false\n */\n allowStreaming?: boolean;\n\n /**\n * If `true`, the request will be forced into streaming mode even\n * if the browser does not support it. This is useful if later handlers\n * in the chain can handle the request body as a stream.\n *\n * @default false\n */\n forceStreaming?: boolean;\n\n /**\n * The constraints for the request body. This is used to determine\n * whether to compress the request body or not.\n *\n * The defaults are:\n *\n * ```ts\n * {\n * Blob: 1000, // blob.size\n * ArrayBuffer: 1000, // buffer.byteLength\n * TypedArray: 1000, // array.byteLength\n * DataView: 1000, // view.byteLength\n * String: 1000, // string.length\n * }\n * ```\n *\n * The following body types are never compressed unless explicitly\n * configured by the request:\n * - `FormData`\n * - `URLSearchParams`\n * - `ReadableStream`\n *\n * A request.options.compress value of `false` will disable\n * compression for a request body of any type. While a value of\n * `true` will enable compression for the request.\n *\n * An undefined value will use the default, a value of `0` will\n * enable compression for all values, and a value of `-1` will\n * disable compression.\n *\n */\n constraints?: Constraints;\n}\n\nconst DEFAULT_CONSTRAINTS = {\n Blob: 1000,\n ArrayBuffer: 1000,\n TypedArray: 1000,\n DataView: 1000,\n String: 1000,\n};\nconst TypedArray = Object.getPrototypeOf(Uint8Array) as typeof Uint8Array;\n\n/**\n * A request handler that automatically compresses the request body\n * if the request body is a string, array buffer, blob, or form data.\n *\n * This uses the [CompressionStream API](https://developer.mozilla.org/en-US/docs/Web/API/CompressionStream)\n *\n * The compression format as well as the kinds of data to compress can be\n * configured using the `format` and `constraints` options.\n *\n * ```diff\n * +import { AutoCompress } from '@ember-data/request-utils/handlers';\n * import Fetch from '@ember-data/request/fetch';\n * import RequestManager from '@ember-data/request';\n * import Store from '@ember-data/store';\n *\n * class AppStore extends Store {\n * requestManager = new RequestManager()\n * .use([\n * + new AutoCompress(),\n * Fetch\n * ]);\n * }\n * ```\n *\n * @group Handlers\n * @public\n * @since 5.5.0\n */\nexport class AutoCompress implements Handler {\n /**\n * The resolved options this handler was configured with, with all\n * defaults (including `constraints` defaults) applied.\n */\n declare options: Required<CompressionOptions> & {\n /**\n * The resolved size constraints used to decide whether to compress a given request body.\n */\n constraints: Required<Constraints>;\n };\n\n constructor(options: CompressionOptions = {}) {\n const opts = {\n format: options.format ?? 'gzip',\n constraints: Object.assign({}, DEFAULT_CONSTRAINTS, options.constraints),\n allowStreaming: options.allowStreaming ?? false,\n forceStreaming: options.forceStreaming ?? false,\n };\n this.options = opts;\n }\n\n request<T>({ request }: RequestContext, next: NextFn<T>): Promise<T> | Future<T> {\n const { constraints } = this.options;\n const { body } = request;\n\n const shouldCompress =\n !!body &&\n isCompressibleMethod(request.method) &&\n request.options?.compress !== false &&\n // prettier-ignore\n (request.options?.compress ? true\n : typeof body === 'string' || body instanceof String ? canCompress('String', constraints, body.length)\n : body instanceof Blob ? canCompress('Blob', constraints, body.size)\n : body instanceof ArrayBuffer ? canCompress('ArrayBuffer', constraints, body.byteLength)\n : body instanceof DataView ? canCompress('DataView', constraints, body.byteLength)\n : body instanceof TypedArray ? canCompress('TypedArray', constraints, body.byteLength)\n : false);\n\n if (!shouldCompress) return next(request);\n\n // A convenient way to convert all of the supported body types to a readable\n // stream is to use a `Response` object body\n const response = new Response(request.body);\n const stream = response.body?.pipeThrough(new CompressionStream(this.options.format));\n const headers = new Headers(request.headers);\n headers.set('Content-Encoding', encodingForFormat(this.options.format));\n\n //\n // For browsers that support it, `fetch` can receive a `ReadableStream` as\n // the body, so all we need to do is to create a new `ReadableStream` and\n // compress it on the fly\n //\n const forceStreaming = request.options?.forceStreaming ?? this.options.forceStreaming;\n const allowStreaming = request.options?.allowStreaming ?? this.options.allowStreaming;\n if (forceStreaming || (SupportsRequestStreams && allowStreaming)) {\n const req = Object.assign({}, request, {\n body: stream,\n headers,\n });\n if (SupportsRequestStreams) {\n // @ts-expect-error untyped\n req.duplex = 'half';\n }\n\n return next(req);\n\n //\n // For non-chromium browsers, we have to \"pull\" the stream to get the final\n // bytes and supply the final byte array as the new request body.\n //\n }\n\n // we need to pull the stream to get the final bytes\n const resp = new Response(stream);\n return resp.blob().then((blob) => {\n const req = Object.assign({}, request, {\n body: blob,\n headers,\n });\n return next(req);\n }) as Promise<T>;\n }\n}\n\nfunction canCompress(type: keyof Constraints, constraints: Required<Constraints>, size: number): boolean {\n // if we have a value of 0, we can compress anything\n if (constraints[type] === 0) return true;\n if (constraints[type] === -1) return false;\n return size >= constraints[type];\n}\n\nfunction encodingForFormat(format: CompressionFormat): string {\n switch (format) {\n case 'gzip':\n case 'deflate':\n case 'deflate-raw':\n return format;\n default:\n assert(`Unsupported compression format: ${format as unknown as string}`);\n // @ts-expect-error - unreachable code is reachable in production\n return format;\n }\n}\n","import type { Future, Handler, NextFn } from '@warp-drive/core/request';\nimport type { RequestContext, StructuredDataDocument } from '@warp-drive/core/types/request';\n\n/**\n * If CheckFn returns true, the wrapped handler will be used.\n * If CheckFn returns false, the wrapped handler will be skipped.\n */\ntype CheckFn = (context: RequestContext) => boolean;\n\n/**\n *\n * @group Handlers\n * @public\n */\nexport class Gate implements Handler {\n /**\n * The wrapped handler to invoke when {@link Gate.checkFn | checkFn} returns `true`.\n */\n declare handler: Handler;\n /**\n * The predicate used to decide whether {@link Gate.handler | handler} should run for a given request.\n */\n declare checkFn: CheckFn;\n\n constructor(handler: Handler, checkFn: CheckFn) {\n this.handler = handler;\n this.checkFn = checkFn;\n }\n\n request<T = unknown>(context: RequestContext, next: NextFn<T>): Promise<T | StructuredDataDocument<T>> | Future<T> {\n if (this.checkFn(context)) {\n return this.handler.request(context, next);\n }\n return next(context.request);\n }\n}\n","import type { StoreRequestContext } from '@warp-drive/core';\nimport type { Handler, NextFn } from '@warp-drive/core/request';\nimport type { StructuredDataDocument } from '@warp-drive/core/types/request';\n\n/**\n * MetaDocHandler processes requests that are marked as meta requests.\n *\n * It treats the response body as \"entirely meta\" transforming\n *\n * ```ts\n * {\n * some: \"key\",\n * another: \"thing\"\n * }\n * ```\n *\n * into\n *\n * ```ts\n * {\n * \t meta: {\n * some: \"key\",\n * another: \"thing\"\n * }\n * }\n * ```\n *\n * To activate this handler, a request should specify\n *\n * ```ts\n * options.isMetaRequest = true\n * ```\n *\n * For instance\n *\n * ```ts\n * store.request({\n * url: '/example',\n * options: {\n * isMetaRequest: true\n * }\n * });\n * ```\n *\n * Errors are not processed by this handler, so if the request fails and the error response\n * is not in {json:api} format additional processing may be needed.\n *\n * @group Handlers\n */\nexport const MetaDocHandler: Handler = {\n request<T>(context: StoreRequestContext, next: NextFn<T>): Promise<T | StructuredDataDocument<T> | Awaited<T>> {\n if (!context.request.options?.isMetaRequest) {\n return next(context.request);\n }\n\n return next(context.request).then((response) => {\n return processResponse<T>(response);\n });\n },\n};\n\nfunction processResponse<T>(response: StructuredDataDocument<T>): T {\n return {\n meta: response.content,\n } as T;\n}\n","import { assert } from '@warp-drive/core/build-config/macros';\n\nif (typeof FastBoot === 'undefined') {\n globalThis.addEventListener('beforeunload', function () {\n sessionStorage.setItem('tab-closed', 'true');\n });\n}\n\nfunction getTabId() {\n if (typeof sessionStorage === 'undefined') {\n return crypto.randomUUID();\n }\n\n const tabId = sessionStorage.getItem('tab-id');\n if (tabId) {\n const tabClosed = sessionStorage.getItem('tab-closed');\n if (tabClosed === 'true') {\n return tabId;\n }\n\n // fall through to generate a new tab id\n }\n\n const newTabId = crypto.randomUUID();\n sessionStorage.setItem('tab-id', newTabId);\n return newTabId;\n}\n\n/**\n * A unique identifier for the current browser tab\n * useful for observability/tracing and deduping\n * across multiple tabs.\n *\n * @group Constants\n */\nexport const TAB_ID: string = getTabId();\n/**\n * The epoch seconds at which the tab id was generated\n *\n * @group Constants\n */\nexport const TAB_ASSIGNED: number = Math.floor(Date.now() / 1000);\n\n/**\n * Adds the `X-Amzn-Trace-Id` header to support observability\n * tooling around request routing.\n *\n * This makes use of the {@link TAB_ID} and {@link TAB_ASSIGNED}\n * to enable tracking the browser tab of origin across multiple requests.\n *\n * Follows the template: `Root=1-${now}-${uuidv4};TabId=1-${epochSeconds}-${tab-uuid}`\n *\n * @group Utility Functions\n */\nexport function addTraceHeader(headers: Headers): Headers {\n const now = Math.floor(Date.now() / 1000);\n headers.set('X-Amzn-Trace-Id', `Root=1-${now}-${crypto.randomUUID()};TabId=1-${TAB_ASSIGNED}-${TAB_ID}`);\n\n return headers;\n}\n\n/**\n * Source: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html\n * As of 2024-12-05 the maximum URL length is 8192 bytes.\n *\n * @group Constants\n */\nexport const MAX_URL_LENGTH = 8192;\n\n/**\n * This assertion takes a URL and throws an error if the URL is longer than the maximum URL length.\n *\n * See also {@link MAX_URL_LENGTH}\n *\n * @group Utility Functions\n */\nexport function assertInvalidUrlLength(url: string | undefined): void {\n assert(\n `URL length ${url?.length} exceeds the maximum URL length of ${MAX_URL_LENGTH} bytes.\\n\\nConsider converting this request query a \\`/query\\` endpoint instead of a GET, or upgrade the current endpoint to be able to receive a POST request directly (ideally specifying the header HTTP-Method-Override: QUERY)\\n\\nThe Invalid URL is:\\n\\n${url}`,\n !url || url.length <= MAX_URL_LENGTH\n );\n}\n"],"mappings":";AAIA,SAASA,qBAAqBC,QAA8B;CAC1D,OAAOA,WAAW,UAAUA,WAAW,SAASA,WAAW,WAAWA,WAAW;AACnF;;;;;;;AAQA,MAAaC,gCAAyC;CACpD,IAAIC,iBAAiB;CAErB,MAAMC,iBAAiB,IAAIC,QAAQ,IAAI;EACrCC,MAAM,IAAIC,eAAe;EACzBN,QAAQ;EAER,IAA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 import { getOrSetGlobal } from "@warp-drive/core/types/-private";
2
2
 
3
+ //#region src/index.ts
3
4
  /**
4
- * @module
5
- * @mergeModuleWith <project>
6
- */
7
-
8
- // prevents the final constructed object from needing to add
9
- // host and namespace which are provided by the final consuming
10
- // class to the prototype which can result in overwrite errors
11
-
12
- const CONFIG = getOrSetGlobal('CONFIG', {
13
- host: '',
14
- namespace: ''
5
+ * @module
6
+ * @mergeModuleWith <project>
7
+ */
8
+ /**
9
+ * The global configuration used by {@link buildBaseURL} when a call does
10
+ * not provide its own `host`/`namespace`. Set via {@link setBuildURLConfig}.
11
+ *
12
+ * @public
13
+ */
14
+ const CONFIG = getOrSetGlobal("CONFIG", {
15
+ host: "",
16
+ namespace: ""
15
17
  });
16
-
17
18
  /**
18
- * Sets the global configuration for `buildBaseURL`
19
- * for host and namespace values for the application.
20
- *
21
- * These values may still be overridden by passing
22
- * them to buildBaseURL directly.
23
- *
24
- * This method may be called as many times as needed.
25
- * host values of `''` or `'/'` are equivalent.
26
- *
27
- * Except for the value of `/` as host, host should not
28
- * end with `/`.
29
- *
30
- * namespace should not start or end with a `/`.
31
- *
32
- * ```ts
33
- * type BuildURLConfig = {
34
- * host: string;
35
- * namespace: string'
36
- * }
37
- * ```
38
- *
39
- * Example:
40
- *
41
- * ```ts
42
- * import { setBuildURLConfig } from '@ember-data/request-utils';
43
- *
44
- * setBuildURLConfig({
45
- * host: 'https://api.example.com',
46
- * namespace: 'api/v1'
47
- * });
48
- * ```
49
- *
50
- * @public
51
- */
19
+ * Sets the global configuration for `buildBaseURL`
20
+ * for host and namespace values for the application.
21
+ *
22
+ * These values may still be overridden by passing
23
+ * them to buildBaseURL directly.
24
+ *
25
+ * This method may be called as many times as needed.
26
+ * host values of `''` or `'/'` are equivalent.
27
+ *
28
+ * Except for the value of `/` as host, host should not
29
+ * end with `/`.
30
+ *
31
+ * namespace should not start or end with a `/`.
32
+ *
33
+ * ```ts
34
+ * type BuildURLConfig = {
35
+ * host: string;
36
+ * namespace: string'
37
+ * }
38
+ * ```
39
+ *
40
+ * Example:
41
+ *
42
+ * ```ts
43
+ * import { setBuildURLConfig } from '@warp-drive/utilities';
44
+ *
45
+ * setBuildURLConfig({
46
+ * host: 'https://api.example.com',
47
+ * namespace: 'api/v1'
48
+ * });
49
+ * ```
50
+ *
51
+ * @public
52
+ */
52
53
  function setBuildURLConfig(config) {
53
- CONFIG.host = config.host || '';
54
- CONFIG.namespace = config.namespace || '';
54
+ CONFIG.host = config.host || "";
55
+ CONFIG.namespace = config.namespace || "";
55
56
  }
56
- const OPERATIONS_WITH_PRIMARY_RECORDS = new Set(['findRecord', 'findRelatedRecord', 'findRelatedCollection', 'updateRecord', 'deleteRecord']);
57
+ /**
58
+ * {@link buildBaseURL} options for a `findRecord` request.
59
+ *
60
+ * @public
61
+ */
62
+ /**
63
+ * {@link buildBaseURL} options for a `query` request.
64
+ *
65
+ * @public
66
+ */
67
+ /**
68
+ * {@link buildBaseURL} options for a `findMany` request.
69
+ *
70
+ * @public
71
+ */
72
+ /**
73
+ * {@link buildBaseURL} options for a `findRelatedCollection` request.
74
+ *
75
+ * @public
76
+ */
77
+ /**
78
+ * {@link buildBaseURL} options for a `findRelatedRecord` request.
79
+ *
80
+ * @public
81
+ */
82
+ /**
83
+ * {@link buildBaseURL} options for a `createRecord` request.
84
+ *
85
+ * @public
86
+ */
87
+ /**
88
+ * {@link buildBaseURL} options for an `updateRecord` request.
89
+ *
90
+ * @public
91
+ */
92
+ /**
93
+ * {@link buildBaseURL} options for a `deleteRecord` request.
94
+ *
95
+ * @public
96
+ */
97
+ /**
98
+ * {@link buildBaseURL} options for building a URL directly from a `resourcePath`
99
+ * without an associated request operation.
100
+ *
101
+ * @public
102
+ */
103
+ /**
104
+ * The union of all `op`-specific option shapes accepted by {@link buildBaseURL}, one of:
105
+ *
106
+ * - {@link FindRecordUrlOptions}
107
+ * - {@link QueryUrlOptions}
108
+ * - {@link FindManyUrlOptions}
109
+ * - {@link FindRelatedCollectionUrlOptions}
110
+ * - {@link FindRelatedResourceUrlOptions}
111
+ * - {@link CreateRecordUrlOptions}
112
+ * - {@link UpdateRecordUrlOptions}
113
+ * - {@link DeleteRecordUrlOptions}
114
+ * - {@link GenericUrlOptions}
115
+ *
116
+ * @public
117
+ */
118
+ const OPERATIONS_WITH_PRIMARY_RECORDS = /* @__PURE__ */ new Set([
119
+ "findRecord",
120
+ "findRelatedRecord",
121
+ "findRelatedCollection",
122
+ "updateRecord",
123
+ "deleteRecord"
124
+ ]);
57
125
  function isOperationWithPrimaryRecord(options) {
58
- return 'op' in options && OPERATIONS_WITH_PRIMARY_RECORDS.has(options.op);
126
+ return "op" in options && OPERATIONS_WITH_PRIMARY_RECORDS.has(options.op);
59
127
  }
60
128
  function resourcePathForType(options) {
61
- return options.op === 'findMany' ? options.identifiers[0].type : options.identifier.type;
129
+ return options.op === "findMany" ? options.identifiers[0].type : options.identifier.type;
62
130
  }
63
-
64
131
  /**
65
- * Builds a URL for a request based on the provided options.
66
- * Does not include support for building query params (see `buildQueryParams`)
67
- * so that it may be composed cleanly with other query-params strategies.
68
- *
69
- * Usage:
70
- *
71
- * ```ts
72
- * import { buildBaseURL } from '@ember-data/request-utils';
73
- *
74
- * const url = buildBaseURL({
75
- * host: 'https://api.example.com',
76
- * namespace: 'api/v1',
77
- * resourcePath: 'emberDevelopers',
78
- * op: 'query',
79
- * identifier: { type: 'ember-developer' }
80
- * });
81
- *
82
- * // => 'https://api.example.com/api/v1/emberDevelopers'
83
- * ```
84
- *
85
- * On the surface this may seem like a lot of work to do something simple, but
86
- * it is designed to be composable with other utilities and interfaces that the
87
- * average product engineer will never need to see or use.
88
- *
89
- * A few notes:
90
- *
91
- * - `resourcePath` is optional, but if it is not provided, `identifier.type` will be used.
92
- * - `host` and `namespace` are optional, but if they are not provided, the values globally
93
- * configured via `setBuildURLConfig` will be used.
94
- * - `op` is required and must be one of the following:
95
- * - 'findRecord' 'query' 'findMany' 'findRelatedCollection' 'findRelatedRecord'` 'createRecord' 'updateRecord' 'deleteRecord'
96
- * - Depending on the value of `op`, `identifier` or `identifiers` will be required.
97
- *
98
- * @public
99
- */
132
+ * Builds a URL for a request based on the provided options.
133
+ * Does not include support for building query params (see `buildQueryParams`)
134
+ * so that it may be composed cleanly with other query-params strategies.
135
+ *
136
+ * Usage:
137
+ *
138
+ * ```ts
139
+ * import { buildBaseURL } from '@warp-drive/utilities';
140
+ *
141
+ * const url = buildBaseURL({
142
+ * host: 'https://api.example.com',
143
+ * namespace: 'api/v1',
144
+ * resourcePath: 'emberDevelopers',
145
+ * op: 'query',
146
+ * identifier: { type: 'ember-developer' }
147
+ * });
148
+ *
149
+ * // => 'https://api.example.com/api/v1/emberDevelopers'
150
+ * ```
151
+ *
152
+ * On the surface this may seem like a lot of work to do something simple, but
153
+ * it is designed to be composable with other utilities and interfaces that the
154
+ * average product engineer will never need to see or use.
155
+ *
156
+ * A few notes:
157
+ *
158
+ * - `resourcePath` is optional, but if it is not provided, `identifier.type` will be used.
159
+ * - `host` and `namespace` are optional, but if they are not provided, the values globally
160
+ * configured via `setBuildURLConfig` will be used.
161
+ * - `op` is required and must be one of the following:
162
+ * - 'findRecord' 'query' 'findMany' 'findRelatedCollection' 'findRelatedRecord'` 'createRecord' 'updateRecord' 'deleteRecord'
163
+ * - Depending on the value of `op`, `identifier` or `identifiers` will be required.
164
+ *
165
+ * @public
166
+ */
100
167
  function buildBaseURL(urlOptions) {
101
- const options = Object.assign({
102
- host: CONFIG.host,
103
- namespace: CONFIG.namespace
104
- }, urlOptions);
105
-
106
- // prettier-ignore
107
- const idPath = isOperationWithPrimaryRecord(options) ? encodeURIComponent(options.identifier.id) : '';
108
- const resourcePath = options.resourcePath || resourcePathForType(options);
109
- const {
110
- host,
111
- namespace
112
- } = options;
113
- const fieldPath = 'fieldPath' in options ? options.fieldPath : '';
114
- const hasHost = host !== '' && host !== '/';
115
- const url = [hasHost ? host : '', namespace, resourcePath, idPath, fieldPath].filter(Boolean).join('/');
116
- return hasHost ? url : `/${url}`;
168
+ const options = Object.assign({
169
+ host: CONFIG.host,
170
+ namespace: CONFIG.namespace
171
+ }, urlOptions);
172
+ const idPath = isOperationWithPrimaryRecord(options) ? encodeURIComponent(options.identifier.id) : "";
173
+ const resourcePath = options.resourcePath || resourcePathForType(options);
174
+ const { host, namespace } = options;
175
+ const fieldPath = "fieldPath" in options ? options.fieldPath : "";
176
+ const hasHost = host !== "" && host !== "/";
177
+ const url = [
178
+ hasHost ? host : "",
179
+ namespace,
180
+ resourcePath,
181
+ idPath,
182
+ fieldPath
183
+ ].filter(Boolean).join("/");
184
+ return hasHost ? url : `/${url}`;
117
185
  }
118
- const DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS = {
119
- arrayFormat: 'comma'
120
- };
186
+ const DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS = { arrayFormat: "comma" };
121
187
  function handleInclude(include) {
122
- return typeof include === 'string' ? include.split(',') : include;
188
+ return typeof include === "string" ? include.split(",") : include;
123
189
  }
124
-
125
190
  /**
126
- * filter out keys of an object that have falsy values or point to empty arrays
127
- * returning a new object with only those keys that have truthy values / non-empty arrays
128
- *
129
- * @public
130
- * @param source object to filter keys with empty values from
131
- * @return A new object with the keys that contained empty values removed
132
- */
191
+ * filter out keys of an object that have falsy values or point to empty arrays
192
+ * returning a new object with only those keys that have truthy values / non-empty arrays
193
+ *
194
+ * @public
195
+ * @param source object to filter keys with empty values from
196
+ * @return A new object with the keys that contained empty values removed
197
+ */
133
198
  function filterEmpty(source) {
134
- const result = {};
135
- for (const key in source) {
136
- const value = source[key];
137
- // Allow `0` and `false` but filter falsy values that indicate "empty"
138
- if (value !== undefined && value !== null && value !== '') {
139
- if (!Array.isArray(value) || value.length > 0) {
140
- result[key] = source[key];
141
- }
142
- }
143
- }
144
- return result;
199
+ const result = {};
200
+ for (const key in source) {
201
+ const value = source[key];
202
+ if (value !== void 0 && value !== null && value !== "") {
203
+ if (!Array.isArray(value) || value.length > 0) result[key] = source[key];
204
+ }
205
+ }
206
+ return result;
145
207
  }
146
-
147
208
  /**
148
- * Sorts query params by both key and value returning a new URLSearchParams
149
- * object with the keys inserted in sorted order.
150
- *
151
- * Treats `included` specially, splicing it into an array if it is a string and sorting the array.
152
- *
153
- * Options:
154
- * - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'
155
- *
156
- * 'bracket': appends [] to the key for every value e.g. `&ids[]=1&ids[]=2`
157
- * 'indices': appends [i] to the key for every value e.g. `&ids[0]=1&ids[1]=2`
158
- * 'repeat': appends the key for every value e.g. `&ids=1&ids=2`
159
- * 'comma' (default): appends the key once with a comma separated list of values e.g. `&ids=1,2`
160
- *
161
- * @public
162
- * @return A {@link URLSearchParams} with keys inserted in sorted order
163
- */
209
+ * Sorts query params by both key and value returning a new URLSearchParams
210
+ * object with the keys inserted in sorted order.
211
+ *
212
+ * Treats `included` specially, splicing it into an array if it is a string and sorting the array.
213
+ *
214
+ * Options:
215
+ * - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'
216
+ *
217
+ * 'bracket': appends [] to the key for every value e.g. `&ids[]=1&ids[]=2`
218
+ * 'indices': appends [i] to the key for every value e.g. `&ids[0]=1&ids[1]=2`
219
+ * 'repeat': appends the key for every value e.g. `&ids=1&ids=2`
220
+ * 'comma' (default): appends the key once with a comma separated list of values e.g. `&ids=1,2`
221
+ *
222
+ * @public
223
+ * @return A {@link URLSearchParams} with keys inserted in sorted order
224
+ */
164
225
  function sortQueryParams(params, options) {
165
- const opts = Object.assign({}, DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS, options);
166
- const paramsIsObject = !(params instanceof URLSearchParams);
167
- const urlParams = new URLSearchParams();
168
- const dictionaryParams = paramsIsObject ? params : {};
169
- if (!paramsIsObject) {
170
- params.forEach((value, key) => {
171
- const hasExisting = key in dictionaryParams;
172
- if (!hasExisting) {
173
- dictionaryParams[key] = value;
174
- } else {
175
- const existingValue = dictionaryParams[key];
176
- if (Array.isArray(existingValue)) {
177
- existingValue.push(value);
178
- } else {
179
- dictionaryParams[key] = [existingValue, value];
180
- }
181
- }
182
- });
183
- }
184
- if ('include' in dictionaryParams) {
185
- dictionaryParams.include = handleInclude(dictionaryParams.include);
186
- }
187
- const sortedKeys = Object.keys(dictionaryParams).sort();
188
- sortedKeys.forEach(key => {
189
- const value = dictionaryParams[key];
190
- if (Array.isArray(value)) {
191
- value.sort();
192
- switch (opts.arrayFormat) {
193
- case 'indices':
194
- value.forEach((v, i) => {
195
- urlParams.append(`${key}[${i}]`, String(v));
196
- });
197
- return;
198
- case 'bracket':
199
- value.forEach(v => {
200
- urlParams.append(`${key}[]`, String(v));
201
- });
202
- return;
203
- case 'repeat':
204
- value.forEach(v => {
205
- urlParams.append(key, String(v));
206
- });
207
- return;
208
- case 'comma':
209
- default:
210
- urlParams.append(key, value.join(','));
211
- return;
212
- }
213
- } else {
214
- urlParams.append(key, String(value));
215
- }
216
- });
217
- return urlParams;
226
+ const opts = Object.assign({}, DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS, options);
227
+ const paramsIsObject = !(params instanceof URLSearchParams);
228
+ const urlParams = new URLSearchParams();
229
+ const dictionaryParams = paramsIsObject ? params : {};
230
+ if (!paramsIsObject) params.forEach((value, key) => {
231
+ if (!(key in dictionaryParams)) dictionaryParams[key] = value;
232
+ else {
233
+ const existingValue = dictionaryParams[key];
234
+ if (Array.isArray(existingValue)) existingValue.push(value);
235
+ else dictionaryParams[key] = [existingValue, value];
236
+ }
237
+ });
238
+ if ("include" in dictionaryParams) dictionaryParams.include = handleInclude(dictionaryParams.include);
239
+ Object.keys(dictionaryParams).sort().forEach((key) => {
240
+ const value = dictionaryParams[key];
241
+ if (Array.isArray(value)) {
242
+ value.sort();
243
+ switch (opts.arrayFormat) {
244
+ case "indices":
245
+ value.forEach((v, i) => {
246
+ urlParams.append(`${key}[${i}]`, String(v));
247
+ });
248
+ return;
249
+ case "bracket":
250
+ value.forEach((v) => {
251
+ urlParams.append(`${key}[]`, String(v));
252
+ });
253
+ return;
254
+ case "repeat":
255
+ value.forEach((v) => {
256
+ urlParams.append(key, String(v));
257
+ });
258
+ return;
259
+ default:
260
+ urlParams.append(key, value.join(","));
261
+ return;
262
+ }
263
+ } else urlParams.append(key, String(value));
264
+ });
265
+ return urlParams;
218
266
  }
219
-
220
267
  /**
221
- * Sorts query params by both key and value, returning a query params string
222
- *
223
- * Treats `included` specially, splicing it into an array if it is a string and sorting the array.
224
- *
225
- * Options:
226
- * - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'
227
- *
228
- * 'bracket': appends [] to the key for every value e.g. `ids[]=1&ids[]=2`
229
- * 'indices': appends [i] to the key for every value e.g. `ids[0]=1&ids[1]=2`
230
- * 'repeat': appends the key for every value e.g. `ids=1&ids=2`
231
- * 'comma' (default): appends the key once with a comma separated list of values e.g. `ids=1,2`
232
- *
233
- * @public
234
- * @return A sorted query params string without the leading `?`
235
- */
268
+ * Sorts query params by both key and value, returning a query params string
269
+ *
270
+ * Treats `included` specially, splicing it into an array if it is a string and sorting the array.
271
+ *
272
+ * Options:
273
+ * - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'
274
+ *
275
+ * 'bracket': appends [] to the key for every value e.g. `ids[]=1&ids[]=2`
276
+ * 'indices': appends [i] to the key for every value e.g. `ids[0]=1&ids[1]=2`
277
+ * 'repeat': appends the key for every value e.g. `ids=1&ids=2`
278
+ * 'comma' (default): appends the key once with a comma separated list of values e.g. `ids=1,2`
279
+ *
280
+ * @public
281
+ * @return A sorted query params string without the leading `?`
282
+ */
236
283
  function buildQueryParams(params, options) {
237
- return sortQueryParams(params, options).toString();
284
+ return sortQueryParams(params, options).toString();
238
285
  }
239
- export { buildBaseURL, buildQueryParams, filterEmpty, setBuildURLConfig, sortQueryParams };
286
+
287
+ //#endregion
288
+ export { buildBaseURL, buildQueryParams, filterEmpty, setBuildURLConfig, sortQueryParams };
289
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["getOrSetGlobal","CONFIG","host","namespace","setBuildURLConfig","config","OPERATIONS_WITH_PRIMARY_RECORDS","Set","isOperationWithPrimaryRecord","options","has","op","hasResourcePath","resourcePath","length","resourcePathForType","identifiers","type","identifier","buildBaseURL","urlOptions","Object","assign","idPath","encodeURIComponent","id","fieldPath","hasHost","url","filter","Boolean","join","DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS","arrayFormat","handleInclude","include","split","filterEmpty","source","result","key","value","undefined","Array","isArray","sortQueryParams","params","opts","paramsIsObject","URLSearchParams","urlParams","dictionaryParams","forEach","hasExisting","existingValue","push","sortedKeys","keys","sort","v","i","append","String","buildQueryParams","toString"],"sources":["../../../src/index.ts"],"sourcesContent":["/**\n * @module\n * @mergeModuleWith <project>\n */\n\nimport { assert } from '@warp-drive/core/build-config/macros';\nimport { getOrSetGlobal } from '@warp-drive/core/types/-private';\nimport type { QueryParamsSerializationOptions, QueryParamsSource, Serializable } from '@warp-drive/core/types/params';\n\n// prevents the final constructed object from needing to add\n// host and namespace which are provided by the final consuming\n// class to the prototype which can result in overwrite errors\n\n/**\n * The global configuration used by {@link buildBaseURL} when a call does\n * not provide its own `host`/`namespace`. Set via {@link setBuildURLConfig}.\n *\n * @public\n */\nexport interface BuildURLConfig {\n /**\n * The scheme, domain and port (if any) to prefix built URLs with, e.g. `'https://api.example.com'`.\n */\n host: string | null;\n /**\n * The path segment to insert between `host` and the resource path, e.g. `'api/v1'`.\n */\n namespace: string | null;\n}\n\nconst CONFIG: BuildURLConfig = getOrSetGlobal('CONFIG', {\n host: '',\n namespace: '',\n});\n\n/**\n * Sets the global configuration for `buildBaseURL`\n * for host and namespace values for the application.\n *\n * These values may still be overridden by passing\n * them to buildBaseURL directly.\n *\n * This method may be called as many times as needed.\n * host values of `''` or `'/'` are equivalent.\n *\n * Except for the value of `/` as host, host should not\n * end with `/`.\n *\n * namespace should not start or end with a `/`.\n *\n * ```ts\n * type BuildURLConfig = {\n * host: string;\n * namespace: string'\n * }\n * ```\n *\n * Example:\n *\n * ```ts\n * import { setBuildURLConfig } from '@warp-drive/utilities';\n *\n * setBuildURLConfig({\n * host: 'https://api.example.com',\n * namespace: 'api/v1'\n * });\n * ```\n *\n * @public\n */\nexport function setBuildURLConfig(config: BuildURLConfig): void {\n assert(`setBuildURLConfig: You must pass a config object`, config);\n assert(\n `setBuildURLConfig: You must pass a config object with a 'host' or 'namespace' property`,\n 'host' in config || 'namespace' in config\n );\n\n CONFIG.host = config.host || '';\n CONFIG.namespace = config.namespace || '';\n\n assert(\n `buildBaseURL: host must NOT end with '/', received '${CONFIG.host}'`,\n CONFIG.host === '/' || !CONFIG.host.endsWith('/')\n );\n assert(\n `buildBaseURL: namespace must NOT start with '/', received '${CONFIG.namespace}'`,\n !CONFIG.namespace.startsWith('/')\n );\n assert(\n `buildBaseURL: namespace must NOT end with '/', received '${CONFIG.namespace}'`,\n !CONFIG.namespace.endsWith('/')\n );\n}\n\n/**\n * {@link buildBaseURL} options for a `findRecord` request.\n *\n * @public\n */\nexport interface FindRecordUrlOptions {\n /**\n * The request operation this URL is for.\n */\n op: 'findRecord';\n /**\n * The type and id of the record to find.\n */\n identifier: {\n /**\n * The resource type.\n */\n type: string;\n /**\n * The resource id.\n */\n id: string;\n };\n /**\n * The path segment for the resource, defaults to `identifier.type` if not provided.\n */\n resourcePath?: string;\n /**\n * Overrides the globally configured host for this call only.\n */\n host?: string;\n /**\n * Overrides the globally configured namespace for this call only.\n */\n namespace?: string;\n}\n\n/**\n * {@link buildBaseURL} options for a `query` request.\n *\n * @public\n */\nexport interface QueryUrlOptions {\n /**\n * The request operation this URL is for.\n */\n op: 'query';\n /**\n * The type of the records to query.\n */\n identifier: {\n /**\n * The resource type.\n */\n type: string;\n };\n /**\n * The path segment for the resource, defaults to `identifier.type` if not provided.\n */\n resourcePath?: string;\n /**\n * Overrides the globally configured host for this call only.\n */\n host?: string;\n /**\n * Overrides the globally configured namespace for this call only.\n */\n namespace?: string;\n}\n\n/**\n * {@link buildBaseURL} options for a `findMany` request.\n *\n * @public\n */\nexport interface FindManyUrlOptions {\n /**\n * The request operation this URL is for.\n */\n op: 'findMany';\n /**\n * The type and id of each record to find.\n */\n identifiers: {\n /**\n * The resource type.\n */\n type: string;\n /**\n * The resource id.\n */\n id: string;\n }[];\n /**\n * The path segment for the resource, defaults to the first identifier's `type` if not provided.\n */\n resourcePath?: string;\n /**\n * Overrides the globally configured host for this call only.\n */\n host?: string;\n /**\n * Overrides the globally configured namespace for this call only.\n */\n namespace?: string;\n}\n/**\n * {@link buildBaseURL} options for a `findRelatedCollection` request.\n *\n * @public\n */\nexport interface FindRelatedCollectionUrlOptions {\n /**\n * The request operation this URL is for.\n */\n op: 'findRelatedCollection';\n /**\n * The type and id of the record whose relationship is being fetched.\n */\n identifier: {\n /**\n * The resource type.\n */\n type: string;\n /**\n * The resource id.\n */\n id: string;\n };\n /**\n * The relationship field name, appended to the resource path.\n */\n fieldPath: string;\n /**\n * The path segment for the resource, defaults to `identifier.type` if not provided.\n */\n resourcePath?: string;\n /**\n * Overrides the globally configured host for this call only.\n */\n host?: string;\n /**\n * Overrides the globally configured namespace for this call only.\n */\n namespace?: string;\n}\n\n/**\n * {@link buildBaseURL} options for a `findRelatedRecord` request.\n *\n * @public\n */\nexport interface FindRelatedResourceUrlOptions {\n /**\n * The request operation this URL is for.\n */\n op: 'findRelatedRecord';\n /**\n * The type and id of the record whose relationship is being fetched.\n */\n identifier: {\n /**\n * The resource type.\n */\n type: string;\n /**\n * The resource id.\n */\n id: string;\n };\n /**\n * The relationship field name, appended to the resource path.\n */\n fieldPath: string;\n /**\n * The path segment for the resource, defaults to `identifier.type` if not provided.\n */\n resourcePath?: string;\n /**\n * Overrides the globally configured host for this call only.\n */\n host?: string;\n /**\n * Overrides the globally configured namespace for this call only.\n */\n namespace?: string;\n}\n\n/**\n * {@link buildBaseURL} options for a `createRecord` request.\n *\n * @public\n */\nexport interface CreateRecordUrlOptions {\n /**\n * The request operation this URL is for.\n */\n op: 'createRecord';\n /**\n * The type of the record being created.\n */\n identifier: {\n /**\n * The resource type.\n */\n type: string;\n };\n /**\n * The path segment for the resource, defaults to `identifier.type` if not provided.\n */\n resourcePath?: string;\n /**\n * Overrides the globally configured host for this call only.\n */\n host?: string;\n /**\n * Overrides the globally configured namespace for this call only.\n */\n namespace?: string;\n}\n\n/**\n * {@link buildBaseURL} options for an `updateRecord` request.\n *\n * @public\n */\nexport interface UpdateRecordUrlOptions {\n /**\n * The request operation this URL is for.\n */\n op: 'updateRecord';\n /**\n * The type and id of the record being updated.\n */\n identifier: {\n /**\n * The resource type.\n */\n type: string;\n /**\n * The resource id.\n */\n id: string;\n };\n /**\n * The path segment for the resource, defaults to `identifier.type` if not provided.\n */\n resourcePath?: string;\n /**\n * Overrides the globally configured host for this call only.\n */\n host?: string;\n /**\n * Overrides the globally configured namespace for this call only.\n */\n namespace?: string;\n}\n\n/**\n * {@link buildBaseURL} options for a `deleteRecord` request.\n *\n * @public\n */\nexport interface DeleteRecordUrlOptions {\n /**\n * The request operation this URL is for.\n */\n op: 'deleteRecord';\n /**\n * The type and id of the record being deleted.\n */\n identifier: {\n /**\n * The resource type.\n */\n type: string;\n /**\n * The resource id.\n */\n id: string;\n };\n /**\n * The path segment for the resource, defaults to `identifier.type` if not provided.\n */\n resourcePath?: string;\n /**\n * Overrides the globally configured host for this call only.\n */\n host?: string;\n /**\n * Overrides the globally configured namespace for this call only.\n */\n namespace?: string;\n}\n\n/**\n * {@link buildBaseURL} options for building a URL directly from a `resourcePath`\n * without an associated request operation.\n *\n * @public\n */\nexport interface GenericUrlOptions {\n /**\n * The path segment for the resource.\n */\n resourcePath: string;\n /**\n * Overrides the globally configured host for this call only.\n */\n host?: string;\n /**\n * Overrides the globally configured namespace for this call only.\n */\n namespace?: string;\n}\n\n/**\n * The union of all `op`-specific option shapes accepted by {@link buildBaseURL}, one of:\n *\n * - {@link FindRecordUrlOptions}\n * - {@link QueryUrlOptions}\n * - {@link FindManyUrlOptions}\n * - {@link FindRelatedCollectionUrlOptions}\n * - {@link FindRelatedResourceUrlOptions}\n * - {@link CreateRecordUrlOptions}\n * - {@link UpdateRecordUrlOptions}\n * - {@link DeleteRecordUrlOptions}\n * - {@link GenericUrlOptions}\n *\n * @public\n */\nexport type UrlOptions =\n | FindRecordUrlOptions\n | QueryUrlOptions\n | FindManyUrlOptions\n | FindRelatedCollectionUrlOptions\n | FindRelatedResourceUrlOptions\n | CreateRecordUrlOptions\n | UpdateRecordUrlOptions\n | DeleteRecordUrlOptions\n | GenericUrlOptions;\n\nconst OPERATIONS_WITH_PRIMARY_RECORDS = new Set([\n 'findRecord',\n 'findRelatedRecord',\n 'findRelatedCollection',\n 'updateRecord',\n 'deleteRecord',\n]);\n\nfunction isOperationWithPrimaryRecord(\n options: UrlOptions\n): options is\n | FindRecordUrlOptions\n | FindRelatedCollectionUrlOptions\n | FindRelatedResourceUrlOptions\n | UpdateRecordUrlOptions\n | DeleteRecordUrlOptions {\n return 'op' in options && OPERATIONS_WITH_PRIMARY_RECORDS.has(options.op);\n}\n\nfunction hasResourcePath(options: UrlOptions): options is GenericUrlOptions {\n return 'resourcePath' in options && typeof options.resourcePath === 'string' && options.resourcePath.length > 0;\n}\n\nfunction resourcePathForType(options: UrlOptions): string {\n assert(\n `resourcePathForType: You must pass a valid op as part of options`,\n 'op' in options && typeof options.op === 'string'\n );\n return options.op === 'findMany' ? options.identifiers[0].type : options.identifier.type;\n}\n\n/**\n * Builds a URL for a request based on the provided options.\n * Does not include support for building query params (see `buildQueryParams`)\n * so that it may be composed cleanly with other query-params strategies.\n *\n * Usage:\n *\n * ```ts\n * import { buildBaseURL } from '@warp-drive/utilities';\n *\n * const url = buildBaseURL({\n * host: 'https://api.example.com',\n * namespace: 'api/v1',\n * resourcePath: 'emberDevelopers',\n * op: 'query',\n * identifier: { type: 'ember-developer' }\n * });\n *\n * // => 'https://api.example.com/api/v1/emberDevelopers'\n * ```\n *\n * On the surface this may seem like a lot of work to do something simple, but\n * it is designed to be composable with other utilities and interfaces that the\n * average product engineer will never need to see or use.\n *\n * A few notes:\n *\n * - `resourcePath` is optional, but if it is not provided, `identifier.type` will be used.\n * - `host` and `namespace` are optional, but if they are not provided, the values globally\n * configured via `setBuildURLConfig` will be used.\n * - `op` is required and must be one of the following:\n * - 'findRecord' 'query' 'findMany' 'findRelatedCollection' 'findRelatedRecord'` 'createRecord' 'updateRecord' 'deleteRecord'\n * - Depending on the value of `op`, `identifier` or `identifiers` will be required.\n *\n * @public\n */\nexport function buildBaseURL(urlOptions: UrlOptions): string {\n const options = Object.assign(\n {\n host: CONFIG.host,\n namespace: CONFIG.namespace,\n },\n urlOptions\n );\n assert(\n `buildBaseURL: You must pass \\`op\\` as part of options`,\n hasResourcePath(options) || (typeof options.op === 'string' && options.op.length > 0)\n );\n assert(\n `buildBaseURL: You must pass \\`identifier\\` as part of options`,\n hasResourcePath(options) ||\n options.op === 'findMany' ||\n (options.identifier && typeof options.identifier === 'object')\n );\n assert(\n `buildBaseURL: You must pass \\`identifiers\\` as part of options`,\n hasResourcePath(options) ||\n options.op !== 'findMany' ||\n (options.identifiers &&\n Array.isArray(options.identifiers) &&\n options.identifiers.length > 0 &&\n options.identifiers.every((i) => i && typeof i === 'object'))\n );\n assert(\n `buildBaseURL: You must pass valid \\`identifier\\` as part of options, expected 'id'`,\n hasResourcePath(options) ||\n !isOperationWithPrimaryRecord(options) ||\n (typeof options.identifier.id === 'string' && options.identifier.id.length > 0)\n );\n assert(\n `buildBaseURL: You must pass \\`identifiers\\` as part of options`,\n hasResourcePath(options) ||\n options.op !== 'findMany' ||\n options.identifiers.every((i) => typeof i.id === 'string' && i.id.length > 0)\n );\n assert(\n `buildBaseURL: You must pass valid \\`identifier\\` as part of options, expected 'type'`,\n hasResourcePath(options) ||\n options.op === 'findMany' ||\n (typeof options.identifier.type === 'string' && options.identifier.type.length > 0)\n );\n assert(\n `buildBaseURL: You must pass valid \\`identifiers\\` as part of options, expected 'type'`,\n hasResourcePath(options) ||\n options.op !== 'findMany' ||\n (typeof options.identifiers[0].type === 'string' && options.identifiers[0].type.length > 0)\n );\n\n // prettier-ignore\n const idPath: string =\n isOperationWithPrimaryRecord(options) ? encodeURIComponent(options.identifier.id)\n : '';\n const resourcePath = options.resourcePath || resourcePathForType(options);\n const { host, namespace } = options;\n const fieldPath = 'fieldPath' in options ? options.fieldPath : '';\n\n assert(\n `buildBaseURL: You tried to build a url for a ${String(\n 'op' in options ? options.op + ' ' : ''\n )}request to ${resourcePath} but resourcePath must be set or op must be one of \"${[\n 'findRecord',\n 'findRelatedRecord',\n 'findRelatedCollection',\n 'updateRecord',\n 'deleteRecord',\n 'createRecord',\n 'query',\n 'findMany',\n ].join('\",\"')}\".`,\n hasResourcePath(options) ||\n [\n 'findRecord',\n 'query',\n 'findMany',\n 'findRelatedCollection',\n 'findRelatedRecord',\n 'createRecord',\n 'updateRecord',\n 'deleteRecord',\n ].includes(options.op)\n );\n\n assert(`buildBaseURL: host must NOT end with '/', received '${host}'`, host === '/' || !host.endsWith('/'));\n assert(`buildBaseURL: namespace must NOT start with '/', received '${namespace}'`, !namespace.startsWith('/'));\n assert(`buildBaseURL: namespace must NOT end with '/', received '${namespace}'`, !namespace.endsWith('/'));\n assert(\n `buildBaseURL: resourcePath must NOT start with '/', received '${resourcePath}'`,\n !resourcePath.startsWith('/')\n );\n assert(`buildBaseURL: resourcePath must NOT end with '/', received '${resourcePath}'`, !resourcePath.endsWith('/'));\n assert(`buildBaseURL: fieldPath must NOT start with '/', received '${fieldPath}'`, !fieldPath.startsWith('/'));\n assert(`buildBaseURL: fieldPath must NOT end with '/', received '${fieldPath}'`, !fieldPath.endsWith('/'));\n assert(`buildBaseURL: idPath must NOT start with '/', received '${idPath}'`, !idPath.startsWith('/'));\n assert(`buildBaseURL: idPath must NOT end with '/', received '${idPath}'`, !idPath.endsWith('/'));\n\n const hasHost = host !== '' && host !== '/';\n const url = [hasHost ? host : '', namespace, resourcePath, idPath, fieldPath].filter(Boolean).join('/');\n return hasHost ? url : `/${url}`;\n}\n\nconst DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS: QueryParamsSerializationOptions = {\n arrayFormat: 'comma',\n};\n\nfunction handleInclude(include: string | string[]): string[] {\n assert(\n `Expected include to be a string or array, got ${typeof include}`,\n typeof include === 'string' || Array.isArray(include)\n );\n return typeof include === 'string' ? include.split(',') : include;\n}\n\n/**\n * filter out keys of an object that have falsy values or point to empty arrays\n * returning a new object with only those keys that have truthy values / non-empty arrays\n *\n * @public\n * @param source object to filter keys with empty values from\n * @return A new object with the keys that contained empty values removed\n */\nexport function filterEmpty(source: Record<string, Serializable>): Record<string, Serializable> {\n const result: Record<string, Serializable> = {};\n for (const key in source) {\n const value = source[key];\n // Allow `0` and `false` but filter falsy values that indicate \"empty\"\n if (value !== undefined && value !== null && value !== '') {\n if (!Array.isArray(value) || value.length > 0) {\n result[key] = source[key];\n }\n }\n }\n return result;\n}\n\n/**\n * Sorts query params by both key and value returning a new URLSearchParams\n * object with the keys inserted in sorted order.\n *\n * Treats `included` specially, splicing it into an array if it is a string and sorting the array.\n *\n * Options:\n * - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'\n *\n * 'bracket': appends [] to the key for every value e.g. `&ids[]=1&ids[]=2`\n * 'indices': appends [i] to the key for every value e.g. `&ids[0]=1&ids[1]=2`\n * 'repeat': appends the key for every value e.g. `&ids=1&ids=2`\n * 'comma' (default): appends the key once with a comma separated list of values e.g. `&ids=1,2`\n *\n * @public\n * @return A {@link URLSearchParams} with keys inserted in sorted order\n */\nexport function sortQueryParams(params: QueryParamsSource, options?: QueryParamsSerializationOptions): URLSearchParams {\n const opts = Object.assign({}, DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS, options);\n const paramsIsObject = !(params instanceof URLSearchParams);\n const urlParams = new URLSearchParams();\n const dictionaryParams: Record<string, Serializable> = paramsIsObject ? params : {};\n\n if (!paramsIsObject) {\n params.forEach((value, key) => {\n const hasExisting = key in dictionaryParams;\n if (!hasExisting) {\n dictionaryParams[key] = value;\n } else {\n const existingValue = dictionaryParams[key];\n if (Array.isArray(existingValue)) {\n existingValue.push(value);\n } else {\n dictionaryParams[key] = [existingValue, value];\n }\n }\n });\n }\n\n if ('include' in dictionaryParams) {\n dictionaryParams.include = handleInclude(dictionaryParams.include as string | string[]);\n }\n\n const sortedKeys = Object.keys(dictionaryParams).sort();\n sortedKeys.forEach((key) => {\n const value = dictionaryParams[key];\n if (Array.isArray(value)) {\n value.sort();\n switch (opts.arrayFormat) {\n case 'indices':\n value.forEach((v, i) => {\n urlParams.append(`${key}[${i}]`, String(v));\n });\n return;\n case 'bracket':\n value.forEach((v) => {\n urlParams.append(`${key}[]`, String(v));\n });\n return;\n case 'repeat':\n value.forEach((v) => {\n urlParams.append(key, String(v));\n });\n return;\n case 'comma':\n default:\n urlParams.append(key, value.join(','));\n return;\n }\n } else {\n urlParams.append(key, String(value));\n }\n });\n\n return urlParams;\n}\n\n/**\n * Sorts query params by both key and value, returning a query params string\n *\n * Treats `included` specially, splicing it into an array if it is a string and sorting the array.\n *\n * Options:\n * - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'\n *\n * 'bracket': appends [] to the key for every value e.g. `ids[]=1&ids[]=2`\n * 'indices': appends [i] to the key for every value e.g. `ids[0]=1&ids[1]=2`\n * 'repeat': appends the key for every value e.g. `ids=1&ids=2`\n * 'comma' (default): appends the key once with a comma separated list of values e.g. `ids=1,2`\n *\n * @public\n * @return A sorted query params string without the leading `?`\n */\nexport function buildQueryParams(params: QueryParamsSource, options?: QueryParamsSerializationOptions): string {\n return sortQueryParams(params, options).toString();\n}\n"],"mappings":";;;;;;;;;;;;;AA8BA,MAAMC,SAAyBD,eAAe,UAAU;CACtDE,MAAM;CACNC,WAAW;AACb,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCD,SAAgBC,kBAAkBC,QAA8B;CAO9DJ,OAAOC,OAAOG,OAAOH,QAAQ;CAC7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