@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.
- package/cjs-dist/string.cjs +448 -0
- package/cjs-dist/string.cjs.map +1 -0
- package/dist/-private.d.ts +12 -0
- package/dist/-private.d.ts.map +1 -0
- package/dist/-private.js +2 -6
- package/dist/active-record.d.ts +260 -0
- package/dist/active-record.d.ts.map +1 -0
- package/dist/active-record.js +254 -379
- package/dist/active-record.js.map +1 -0
- package/dist/builder-utils-BkXwUT0x.js +16 -0
- package/dist/builder-utils-BkXwUT0x.js.map +1 -0
- package/dist/derivations.d.ts +30 -0
- package/dist/derivations.d.ts.map +1 -0
- package/dist/derivations.js +26 -26
- package/dist/derivations.js.map +1 -0
- package/dist/handlers.d.ts +283 -0
- package/dist/handlers.d.ts.map +1 -0
- package/dist/handlers.js +240 -283
- package/dist/handlers.js.map +1 -0
- package/dist/index-BeMAuqgZ.d.ts +462 -0
- package/dist/index-BeMAuqgZ.d.ts.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +357 -335
- package/dist/index.js.map +1 -0
- package/dist/inflections-DzBsjJqj.js +80 -0
- package/dist/inflections-DzBsjJqj.js.map +1 -0
- package/dist/json-api.d.ts +496 -0
- package/dist/json-api.d.ts.map +1 -0
- package/dist/json-api.js +470 -706
- package/dist/json-api.js.map +1 -0
- package/dist/rest.d.ts +258 -0
- package/dist/rest.d.ts.map +1 -0
- package/dist/rest.js +254 -377
- package/dist/rest.js.map +1 -0
- package/dist/string-CWmAluxh.js +290 -0
- package/dist/string-CWmAluxh.js.map +1 -0
- package/dist/string.d.ts +165 -0
- package/dist/string.d.ts.map +1 -0
- package/dist/string.js +2 -427
- package/dist/unpkg/dev/-private.js +2 -6
- package/dist/unpkg/dev/active-record.js +253 -378
- package/dist/unpkg/dev/active-record.js.map +1 -0
- package/dist/unpkg/dev/builder-utils-BkXwUT0x.js +16 -0
- package/dist/unpkg/dev/builder-utils-BkXwUT0x.js.map +1 -0
- package/dist/unpkg/dev/derivations.js +26 -26
- package/dist/unpkg/dev/derivations.js.map +1 -0
- package/dist/unpkg/dev/handlers.js +238 -282
- package/dist/unpkg/dev/handlers.js.map +1 -0
- package/dist/unpkg/dev/index.js +356 -336
- package/dist/unpkg/dev/index.js.map +1 -0
- package/dist/unpkg/dev/inflections-DzBsjJqj.js +80 -0
- package/dist/unpkg/dev/inflections-DzBsjJqj.js.map +1 -0
- package/dist/unpkg/dev/json-api.js +469 -706
- package/dist/unpkg/dev/json-api.js.map +1 -0
- package/dist/unpkg/dev/rest.js +253 -376
- package/dist/unpkg/dev/rest.js.map +1 -0
- package/dist/unpkg/dev/string-j4ur-TDs.js +289 -0
- package/dist/unpkg/dev/string-j4ur-TDs.js.map +1 -0
- package/dist/unpkg/dev/string.js +3 -1
- package/dist/unpkg/dev-deprecated/-private.js +2 -6
- package/dist/unpkg/dev-deprecated/active-record.js +253 -378
- package/dist/unpkg/dev-deprecated/active-record.js.map +1 -0
- package/dist/unpkg/dev-deprecated/builder-utils-BkXwUT0x.js +16 -0
- package/dist/unpkg/dev-deprecated/builder-utils-BkXwUT0x.js.map +1 -0
- package/dist/unpkg/dev-deprecated/derivations.js +26 -26
- package/dist/unpkg/dev-deprecated/derivations.js.map +1 -0
- package/dist/unpkg/dev-deprecated/handlers.js +238 -282
- package/dist/unpkg/dev-deprecated/handlers.js.map +1 -0
- package/dist/unpkg/dev-deprecated/index.js +356 -336
- package/dist/unpkg/dev-deprecated/index.js.map +1 -0
- package/dist/unpkg/dev-deprecated/inflections-DzBsjJqj.js +80 -0
- package/dist/unpkg/dev-deprecated/inflections-DzBsjJqj.js.map +1 -0
- package/dist/unpkg/dev-deprecated/json-api.js +469 -706
- package/dist/unpkg/dev-deprecated/json-api.js.map +1 -0
- package/dist/unpkg/dev-deprecated/rest.js +253 -376
- package/dist/unpkg/dev-deprecated/rest.js.map +1 -0
- package/dist/unpkg/dev-deprecated/string-j4ur-TDs.js +289 -0
- package/dist/unpkg/dev-deprecated/string-j4ur-TDs.js.map +1 -0
- package/dist/unpkg/dev-deprecated/string.js +3 -1
- package/dist/unpkg/prod/-private.js +2 -6
- package/dist/unpkg/prod/active-record.js +236 -351
- package/dist/unpkg/prod/active-record.js.map +1 -0
- package/dist/unpkg/prod/builder-utils-BkXwUT0x.js +16 -0
- package/dist/unpkg/prod/builder-utils-BkXwUT0x.js.map +1 -0
- package/dist/unpkg/prod/derivations.js +26 -26
- package/dist/unpkg/prod/derivations.js.map +1 -0
- package/dist/unpkg/prod/handlers.js +231 -272
- package/dist/unpkg/prod/handlers.js.map +1 -0
- package/dist/unpkg/prod/index.js +265 -215
- package/dist/unpkg/prod/index.js.map +1 -0
- package/dist/unpkg/prod/inflections-DzBsjJqj.js +80 -0
- package/dist/unpkg/prod/inflections-DzBsjJqj.js.map +1 -0
- package/dist/unpkg/prod/json-api.js +446 -669
- package/dist/unpkg/prod/json-api.js.map +1 -0
- package/dist/unpkg/prod/rest.js +236 -349
- package/dist/unpkg/prod/rest.js.map +1 -0
- package/dist/unpkg/prod/string-T1ahjLdj.js +283 -0
- package/dist/unpkg/prod/string-T1ahjLdj.js.map +1 -0
- package/dist/unpkg/prod/string.js +3 -1
- package/dist/unpkg/prod-deprecated/-private.js +2 -6
- package/dist/unpkg/prod-deprecated/active-record.js +236 -351
- package/dist/unpkg/prod-deprecated/active-record.js.map +1 -0
- package/dist/unpkg/prod-deprecated/builder-utils-BkXwUT0x.js +16 -0
- package/dist/unpkg/prod-deprecated/builder-utils-BkXwUT0x.js.map +1 -0
- package/dist/unpkg/prod-deprecated/derivations.js +26 -26
- package/dist/unpkg/prod-deprecated/derivations.js.map +1 -0
- package/dist/unpkg/prod-deprecated/handlers.js +231 -272
- package/dist/unpkg/prod-deprecated/handlers.js.map +1 -0
- package/dist/unpkg/prod-deprecated/index.js +265 -215
- package/dist/unpkg/prod-deprecated/index.js.map +1 -0
- package/dist/unpkg/prod-deprecated/inflections-DzBsjJqj.js +80 -0
- package/dist/unpkg/prod-deprecated/inflections-DzBsjJqj.js.map +1 -0
- package/dist/unpkg/prod-deprecated/json-api.js +446 -669
- package/dist/unpkg/prod-deprecated/json-api.js.map +1 -0
- package/dist/unpkg/prod-deprecated/rest.js +236 -349
- package/dist/unpkg/prod-deprecated/rest.js.map +1 -0
- package/dist/unpkg/prod-deprecated/string-T1ahjLdj.js +283 -0
- package/dist/unpkg/prod-deprecated/string-T1ahjLdj.js.map +1 -0
- package/dist/unpkg/prod-deprecated/string.js +3 -1
- package/package.json +20 -23
- package/declarations/-private/active-record/find-record.d.ts +0 -64
- package/declarations/-private/active-record/query.d.ts +0 -53
- package/declarations/-private/active-record/save-record.d.ts +0 -146
- package/declarations/-private/builder-utils.d.ts +0 -4
- package/declarations/-private/handlers/auto-compress.d.ts +0 -158
- package/declarations/-private/handlers/gated.d.ts +0 -19
- package/declarations/-private/handlers/meta-doc.d.ts +0 -47
- package/declarations/-private/handlers/utils.d.ts +0 -41
- package/declarations/-private/json-api/-utils.d.ts +0 -109
- package/declarations/-private/json-api/find-record.d.ts +0 -84
- package/declarations/-private/json-api/query.d.ts +0 -100
- package/declarations/-private/json-api/save-record.d.ts +0 -228
- package/declarations/-private/json-api/serialize.d.ts +0 -70
- package/declarations/-private/rest/find-record.d.ts +0 -62
- package/declarations/-private/rest/query.d.ts +0 -53
- package/declarations/-private/rest/save-record.d.ts +0 -146
- package/declarations/-private/string/inflect.d.ts +0 -82
- package/declarations/-private/string/inflections.d.ts +0 -9
- package/declarations/-private/string/transform.d.ts +0 -77
- package/declarations/-private.d.ts +0 -1
- package/declarations/active-record.d.ts +0 -3
- package/declarations/derivations.d.ts +0 -27
- package/declarations/handlers.d.ts +0 -10
- package/declarations/index.d.ts +0 -208
- package/declarations/json-api.d.ts +0 -5
- package/declarations/rest.d.ts +0 -3
- package/declarations/string.d.ts +0 -14
- package/dist/builder-utils-Donkk-BZ.js +0 -22
- package/dist/inflect-BSG696t-.js +0 -344
- package/dist/string.cjs +0 -430
- package/dist/unpkg/dev/builder-utils-Donkk-BZ.js +0 -22
- package/dist/unpkg/dev/inflect-BEv8WqY1.js +0 -343
- package/dist/unpkg/dev-deprecated/builder-utils-Donkk-BZ.js +0 -22
- package/dist/unpkg/dev-deprecated/inflect-BEv8WqY1.js +0 -343
- package/dist/unpkg/prod/builder-utils-Donkk-BZ.js +0 -22
- package/dist/unpkg/prod/inflect-Dh9dyEYx.js +0 -333
- package/dist/unpkg/prod-deprecated/builder-utils-Donkk-BZ.js +0 -22
- 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,IAAIO,SAAS;GACXL,iBAAiB;GACjB,OAAO;EACT;CACF,CAAC,CAAC,CAACM,QAAQC,IAAI,cAAc;CAE7B,OAAOP,kBAAkB,CAACC;AAC5B,EAAC,CAAE;;;;;AAwHH,MAAMO,sBAAsB;CAC1BC,MAAM;CACNC,aAAa;CACbC,YAAY;CACZC,UAAU;CACVC,QAAQ;AACV;AACA,MAAMF,aAAaG,OAAOC,eAAeC,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BnD,IAAaC,eAAb,MAA6C;;;;;CAY3CC,YAAYC,UAA8B,CAAC,GAAG;EAC5C,MAAM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AC/DA,IAAI,OAAOG,aAAa,aACtBC,WAAWC,iBAAiB,gBAAgB,WAAY;CACtDC,eAAeC,QAAQ,cAAc,MAAM;AAC7C,CAAC;AAGH,SAASC,WAAW;CAClB,IAAI,OAAOF,mBAAmB,aAC5B,OAAOG,OAAOC,WAAW;CAG3B,MAAMC,QAAQL,eAAeM,QAAQ,QAAQ;CAC7C,IAAID,OAEF;MADkBL,eAAeM,QAAQ,YACrCC,MAAc,QAChB,OAAOF;CACT;CAKF,MAAMG,WAAWL,OAAOC,WAAW;CACnCJ,eAAeC,QAAQ,UAAUO,QAAQ;CACzC,OAAOA;AACT;;;;;;;;AASA,MAAaC,SAAiBP,SAAS;;;;;;AAMvC,MAAaQ,eAAuBC,KAAKC,MAAMC,KAAKC,IAAI,IAAI,GAAI;;;;;;;;;;;;AAahE,SAAgBC,eAAeC,SAA2B;CACxD,MAAMF,MAAMH,KAAKC,MAAMC,KAAKC,IAAI,IAAI,GAAI;CACxCE,QAAQC,IAAI,mBAAmB,UAAUH,IAAG,GAAIX,OAAOC,WAAW,EAAC,WAAYM,aAAY,GAAID,QAAQ;CAEvG,OAAOO;AACT;;;;;;;AAQA,MAAaE,iBAAiB;;;;;;;;AAS9B,SAAgBC,uBAAuBC,KAA+B,CAKtE"}
|
package/dist/unpkg/prod/index.js
CHANGED
|
@@ -1,239 +1,289 @@
|
|
|
1
|
-
import { getOrSetGlobal } from
|
|
1
|
+
import { getOrSetGlobal } from "@warp-drive/core/types/-private";
|
|
2
2
|
|
|
3
|
+
//#region src/index.ts
|
|
3
4
|
/**
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
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
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
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
|
-
|
|
54
|
-
|
|
54
|
+
CONFIG.host = config.host || "";
|
|
55
|
+
CONFIG.namespace = config.namespace || "";
|
|
55
56
|
}
|
|
56
|
-
|
|
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
|
-
|
|
126
|
+
return "op" in options && OPERATIONS_WITH_PRIMARY_RECORDS.has(options.op);
|
|
59
127
|
}
|
|
60
128
|
function resourcePathForType(options) {
|
|
61
|
-
|
|
129
|
+
return options.op === "findMany" ? options.identifiers[0].type : options.identifier.type;
|
|
62
130
|
}
|
|
63
|
-
|
|
64
131
|
/**
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
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
|
-
|
|
188
|
+
return typeof include === "string" ? include.split(",") : include;
|
|
123
189
|
}
|
|
124
|
-
|
|
125
190
|
/**
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
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
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
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
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
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
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
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
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
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
|
-
|
|
284
|
+
return sortQueryParams(params, options).toString();
|
|
238
285
|
}
|
|
239
|
-
|
|
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;CAC7BD,OAAOE,YAAYE,OAAOF,aAAa;AAczC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwVA,MAAMG,kDAAkC,IAAIC,IAAI;CAC9C;CACA;CACA;CACA;CACA;AAAc,CACf;AAED,SAASC,6BACPC,SAMyB;CACzB,OAAO,QAAQA,WAAWH,gCAAgCI,IAAID,QAAQE,EAAE;AAC1E;AAMA,SAASI,oBAAoBN,SAA6B;CAKxD,OAAOA,QAAQE,OAAO,aAAaF,QAAQO,YAAY,EAAE,CAACC,OAAOR,QAAQS,WAAWD;AACtF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAgBE,aAAaC,YAAgC;CAC3D,MAAMX,UAAUY,OAAOC,OACrB;EACEpB,MAAMD,OAAOC;EACbC,WAAWF,OAAOE;CACpB,GACAiB,UACF;CA8CA,MAAMG,SACFf,6BAA6BC,OAAO,IAAIe,mBAAmBf,QAAQS,WAAWO,EAAE,IAC9E;CACN,MAAMZ,eAAeJ,QAAQI,gBAAgBE,oBAAoBN,OAAO;CACxE,MAAM,EAAEP,MAAMC,cAAcM;CAC5B,MAAMiB,YAAY,eAAejB,UAAUA,QAAQiB,YAAY;CAyC/D,MAAMC,UAAUzB,SAAS,MAAMA,SAAS;CACxC,MAAM0B,MAAM;EAACD,UAAUzB,OAAO;EAAIC;EAAWU;EAAcU;EAAQG;CAAS,CAAC,CAACG,OAAOC,OAAO,CAAC,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