{"version":3,"file":"main.mjs","names":[],"sources":["../../../typescript-common-runtime/dist/esm/request-bodies/url-search-params.mjs","../../../typescript-common-runtime/dist/esm/types.mjs","../../src/main.ts"],"sourcesContent":["//#region src/request-bodies/url-search-params.ts\nfunction getEncoding(key, encoding) {\n\treturn {\n\t\tstyle: \"form\",\n\t\texplode: true,\n\t\tallowReserved: false,\n\t\t...encoding[key]\n\t};\n}\nconst separators = {\n\tdeepObject: \",\",\n\tform: \",\",\n\tpipeDelimited: \"|\",\n\tspaceDelimited: \" \"\n};\nfunction addArrayValue(result, key, value, encoding) {\n\tif (encoding.style === \"deepObject\" && encoding.explode) return addObjectValue(result, key, value, encoding);\n\tif (encoding.explode) for (const it of value) result.append(key, String(it));\n\telse result.append(key, value.join(separators[encoding.style]));\n}\nfunction addObjectValue(result, key, value, encoding) {\n\tif (encoding.explode) if (encoding.style === \"deepObject\") for (const it of Object.entries(value)) {\n\t\tconst path = `${key}[${it[0]}]`;\n\t\tconst value = it[1];\n\t\tif (typeof value === \"object\") addObjectValue(result, path, value, encoding);\n\t\telse result.append(path, String(value));\n\t}\n\telse for (const it of Object.entries(value)) result.append(it[0], String(it[1]));\n\telse if ([\n\t\t\"form\",\n\t\t\"spaceDelimited\",\n\t\t\"pipeDelimited\"\n\t].includes(encoding.style)) {\n\t\tconst sep = separators[encoding.style];\n\t\tresult.append(key, Object.entries(value).map((entry) => [entry[0], typeof entry[1] === \"object\" ? JSON.stringify(entry[1]) : entry[1]].join(sep)).join(sep));\n\t} else result.append(key, JSON.stringify(value));\n}\n/**\n* Serializes a request body as `application/x-www-form-urlencoded` with the exact\n* semantics defined by the provided encodings, falling back to the default encoding\n* specified by the OAI specification.\n*/\nfunction requestBodyToUrlSearchParams(obj, encodings = {}) {\n\tconst result = new URLSearchParams();\n\tfor (const [key, value] of Object.entries(obj)) {\n\t\tconst encoding = getEncoding(key, encodings);\n\t\tif (value === void 0 || value === null) continue;\n\t\tif (typeof value === \"object\") if (Array.isArray(value)) addArrayValue(result, key, value, encoding);\n\t\telse addObjectValue(result, key, value, encoding);\n\t\telse result.append(key, String(value));\n\t}\n\treturn result;\n}\n//#endregion\nexport { requestBodyToUrlSearchParams };\n\n//# sourceMappingURL=url-search-params.mjs.map","//#region src/types.ts\nconst SkipResponse = Symbol.for(\"skip response processing\");\nfunction isNonEmptyArray(it) {\n\treturn Array.isArray(it) && it.length > 0;\n}\n//#endregion\nexport { SkipResponse, isNonEmptyArray };\n\n//# sourceMappingURL=types.mjs.map","import {\n  type Encoding,\n  requestBodyToUrlSearchParams,\n} from \"@nahkies/typescript-common-runtime/request-bodies/url-search-params\"\nimport {isNonEmptyArray} from \"@nahkies/typescript-common-runtime/types\"\nimport type {\n  AbstractFetchClientConfig,\n  HeaderParams,\n  HeadersInit,\n  QueryParams,\n  Res,\n  StatusCode,\n} from \"./types.ts\"\n\nexport * from \"./types.ts\"\n\nexport abstract class AbstractFetchClient {\n  protected readonly basePath: string\n  protected readonly defaultHeaders: Record<string, string>\n  protected readonly defaultTimeout: number | undefined\n\n  protected constructor(config: AbstractFetchClientConfig) {\n    this.basePath = config.basePath\n    this.defaultHeaders = config.defaultHeaders ?? {}\n    this.defaultTimeout = config.defaultTimeout\n  }\n\n  protected async _fetch<R extends Res<StatusCode, unknown>>(\n    url: string,\n    opts: RequestInit,\n    timeout: number | undefined = this.defaultTimeout,\n  ): Promise<R> {\n    // main abort controller that will be returned to the caller\n    const cancelRequest = new AbortController()\n\n    // if a timeout is provided, set a timeout signal and connect to main abort controller\n    if (timeout && timeout > 0) {\n      const timeoutSignal = AbortSignal.timeout(timeout)\n      timeoutSignal.addEventListener(\"abort\", () => {\n        cancelRequest.abort(timeoutSignal.reason)\n      })\n    }\n\n    // if we were provided a signal connect it to the main abort controller\n    const userSignal = opts.signal\n\n    if (userSignal) {\n      userSignal.addEventListener(\"abort\", () =>\n        cancelRequest.abort(userSignal.reason),\n      )\n    }\n\n    const headers = opts.headers ?? this._headers()\n\n    return fetch(url, {\n      ...opts,\n      headers,\n      signal: cancelRequest.signal,\n    }).catch((err) => {\n      // workaround bug where eg: TimeoutError gets converted to an AbortError\n      // https://stackoverflow.com/a/75973817/1445636\n      if (err?.name === \"AbortError\") {\n        cancelRequest.signal.throwIfAborted()\n      }\n      // if not aborted just throw\n      throw err\n    }) as unknown as R\n  }\n\n  protected _query(\n    params: QueryParams,\n    encodings?: Record<string, Encoding>,\n  ): string {\n    const urlSearchParams = requestBodyToUrlSearchParams(params, encodings)\n    const asString = urlSearchParams.toString()\n\n    if (!asString.length) {\n      return \"\"\n    }\n\n    return `?${asString}`\n  }\n\n  /**\n   * Combines headers for a request, with precedence\n   * 1. default headers\n   * 2. route level header parameters\n   * 3. raw request config (escape hatch)\n   *\n   * following these rules:\n   * - header values of `undefined` are skipped\n   * - header values of `null` will remove/delete any previously set headers\n   *\n   * Eg:\n   * Passing `Authorization: null` as a parameter, will clear out any\n   * default `Authorization` header.\n   *\n   * But passing `Authorization: undefined` as parameter will fallthrough\n   * to the default `Authorization` header.\n   *\n   * @param paramHeaders\n   * @param optsHeaders\n   * @protected\n   */\n  protected _headers(\n    paramHeaders: HeaderParams = {},\n    optsHeaders: HeadersInit = {},\n  ): Headers {\n    const headers = new Headers()\n\n    /*\n    This is pretty hideous, but basically we:\n    - Maintain a set of deleted headers, the nullSet\n    - Apply headers from most specific, to least\n    - Delete headers if we encounter a null value and note this in the nullSet\n\n    The primary reason is to enable the use of headers.append to support setting\n    the same header multiple times (aka `Set-Cookie`), whilst *also* allowing more\n    specific header sources to override all instances of the less specific source.\n     */\n\n    const nullSet = new Set<string>()\n\n    this.setHeaders(headers, optsHeaders, nullSet)\n    this.setHeaders(headers, paramHeaders, nullSet)\n    this.setHeaders(headers, this.defaultHeaders, nullSet)\n\n    return headers\n  }\n\n  protected _requestBodyToUrlSearchParams(\n    obj: Record<string, unknown>,\n    encoding: Record<string, Encoding> = {},\n  ): URLSearchParams {\n    return requestBodyToUrlSearchParams(obj, encoding)\n  }\n\n  private setHeaders(\n    headers: Headers,\n    headersInit: HeaderParams | HeadersInit,\n    nullSet: Set<string>,\n  ) {\n    const headersArray = this.headersAsArray(headersInit)\n\n    const filteredHeadersArray = headersArray.filter(\n      ([headerName, headerValue]) =>\n        !headers.has(headerName) &&\n        headerValue !== undefined &&\n        !nullSet.has(headerName),\n    )\n\n    for (const [headerName, headerValue] of filteredHeadersArray) {\n      if (headerValue === null) {\n        headers.delete(headerName)\n        nullSet.add(headerName)\n      } else if (headerValue !== undefined) {\n        headers.append(headerName, headerValue.toString())\n      }\n    }\n  }\n\n  private headersAsArray(\n    headers: HeaderParams | HeadersInit,\n  ): [string, string | number | boolean | undefined | null][] {\n    if (isMultiDimArray(headers)) {\n      return headers.flatMap((it) =>\n        isNonEmptyArray(it) ? headerArrayToTuples(it) : [],\n      )\n    }\n\n    if (headers instanceof Headers) {\n      const result: [string, string][] = []\n      headers.forEach((value, key) => {\n        result.push([key, value])\n      })\n      return result\n    }\n\n    if (headers && typeof headers === \"object\") {\n      const result: [string, string][] = []\n\n      for (const [headerName, values] of Object.entries(headers)) {\n        if (Array.isArray(values)) {\n          for (const value of values) {\n            result.push([headerName, value])\n          }\n        } else {\n          result.push([headerName, values])\n        }\n      }\n\n      return result\n    }\n\n    throw new Error(`couldn't process headers '${headers}'`)\n  }\n}\n\nfunction isMultiDimArray<T>(arr: unknown): arr is T[][] {\n  return Array.isArray(arr) && Array.isArray(arr[0])\n}\n\nfunction headerArrayToTuples<\n  T extends string | number | boolean | undefined | null,\n>([head, ...rest]: [string, ...T[]]): [string, T][] {\n  return rest.map((value) => [head, value] as const)\n}\n"],"mappings":";AACA,SAAS,YAAY,KAAK,UAAU;CACnC,OAAO;EACN,OAAO;EACP,SAAS;EACT,eAAe;EACf,GAAG,SAAS;CACb;AACD;AACA,MAAM,aAAa;CAClB,YAAY;CACZ,MAAM;CACN,eAAe;CACf,gBAAgB;AACjB;AACA,SAAS,cAAc,QAAQ,KAAK,OAAO,UAAU;CACpD,IAAI,SAAS,UAA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