{"version":3,"file":"index.mjs","names":[],"sources":["../src/adapter/adapter.constants.ts","../src/adapter/adapter.types.ts","../src/adapter/adapter.utils.ts","../src/adapter/http-adapter.fetch.ts","../src/adapter/adapter.ts"],"sourcesContent":["import { Time } from \"@hyper-fetch/core\";\n\nimport type { GraphQlExtraType } from \"./adapter.types\";\n\nexport const defaultTimeout = Time.SEC * 5;\n\nexport const gqlExtra: GraphQlExtraType = {\n  headers: {},\n  extensions: {},\n};\n","import type { Adapter, EmptyTypes, QueryParamsType } from \"@hyper-fetch/core\";\nimport type { DocumentNode } from \"graphql/language/ast\";\n\nexport enum GraphqlMethod {\n  POST = \"POST\",\n  GET = \"GET\",\n}\n\nexport type GraphQlExtraType = { headers: HeadersInit; extensions: Record<string, any> };\n\nexport type GraphQlEndpointType = string | DocumentNode;\n\nexport type FetchGraphqlAdapterOptionsType = Omit<RequestInit, \"method\" | \"headers\" | \"body\" | \"signal\"> & {\n  timeout?: number;\n};\n\nexport type GraphqlAdapterType = Adapter<\n  FetchGraphqlAdapterOptionsType,\n  GraphqlMethod,\n  number,\n  GraphQlExtraType,\n  QueryParamsType | string,\n  undefined,\n  GraphQlEndpointType,\n  (endpoint: GraphQlEndpointType) => string\n>;\n\n// Extract\n\ntype GqlParamType = boolean | string | number | Record<string, any> | EmptyTypes;\n\nexport type ExtractGqlRouteParams<T extends string> = string extends T\n  ? EmptyTypes\n  : T extends `${string}query ${infer Parameters} {${infer QueryRest}`\n    ? Parameters extends `${string}$${infer Param},${infer Rest}`\n      ? GqlParameter<Param, Rest> &\n          // eslint-disable-next-line @typescript-eslint/ban-types\n          (ExtractGqlRouteParams<QueryRest> extends EmptyTypes ? {} : ExtractGqlRouteParams<QueryRest>)\n      : Parameters extends `${string}$${infer Param})${infer Rest}`\n        ? GqlParameter<Param, Rest> &\n            // eslint-disable-next-line @typescript-eslint/ban-types\n            (ExtractGqlRouteParams<QueryRest> extends EmptyTypes ? {} : ExtractGqlRouteParams<QueryRest>)\n        : EmptyTypes\n    : T extends `${string}$${infer Parameters},${infer Rest}`\n      ? GqlParameter<Parameters, Rest>\n      : T extends `${string}$${infer Parameters})${infer Rest}`\n        ? GqlParameter<Parameters, Rest>\n        : EmptyTypes;\n\nexport type GqlParameter<T extends string, Rest extends string> = T extends `${infer Param}:${string}!`\n  ? { [k in Param]: GqlParamType } & (ExtractGqlRouteParams<Rest> extends EmptyTypes\n      ? // eslint-disable-next-line @typescript-eslint/ban-types\n        {}\n      : ExtractGqlRouteParams<Rest>)\n  : T extends `${infer Param}:${string}`\n    ? { [k in Param]?: GqlParamType } & (ExtractGqlRouteParams<Rest> extends EmptyTypes\n        ? // eslint-disable-next-line @typescript-eslint/ban-types\n          {}\n        : ExtractGqlRouteParams<Rest>)\n    : EmptyTypes;\n","import type { RequestInstance } from \"@hyper-fetch/core\";\nimport { HttpMethods, stringifyQueryParams } from \"@hyper-fetch/core\";\nimport type { OperationDefinitionNode } from \"graphql\";\nimport { print, parse } from \"graphql\";\n\nimport type { GraphQlEndpointType } from \"./adapter.types\";\n\nexport const getRequestValues = <R extends RequestInstance>(request: R) => {\n  const isPostRequest = request.method === HttpMethods.POST;\n\n  const query = request.endpoint;\n  const variables = request.payload;\n\n  const fullUrl = isPostRequest ? request.client.url : request.client.url + stringifyQueryParams({ query, variables });\n\n  const payload = isPostRequest\n    ? JSON.stringify({\n        query,\n        variables,\n      })\n    : null;\n\n  return { fullUrl, payload };\n};\n\nexport const gqlEndpointMapper = <E extends GraphQlEndpointType>(endpoint: E): string => {\n  if (typeof endpoint === \"string\") {\n    return endpoint;\n  }\n  return print(endpoint);\n};\n\nexport const gqlEndpointNameMapper = (endpoint: string): string => {\n  try {\n    const ast = parse(endpoint);\n    const operationDefinition = ast.definitions.find(\n      (def): def is OperationDefinitionNode => def.kind === \"OperationDefinition\",\n    );\n\n    if (operationDefinition) {\n      if (operationDefinition.name?.value) {\n        return operationDefinition.name.value;\n      }\n\n      const selection = operationDefinition.selectionSet.selections[0];\n      if (selection?.kind === \"Field\") {\n        return selection.name.value;\n      }\n      if (selection?.kind === \"InlineFragment\" && selection.typeCondition) {\n        return selection.typeCondition.name.value;\n      }\n    }\n  } catch {\n    // We can ignore this error and just return some fallback\n  }\n\n  // Fallback for invalid gql queries or something else\n  const clearedQuery = endpoint\n    .replace(/(query|mutation|subscription)/, \"\")\n    .replaceAll(/[{}().,:]/g, \" \")\n    .trim();\n  const [name] = clearedQuery.split(\" \");\n\n  return name || \"graphql-request\";\n};\n","import type { QueryParamsType } from \"@hyper-fetch/core\";\nimport { parseResponse, getErrorMessage, Adapter, stringifyKey } from \"@hyper-fetch/core\";\n\nimport { gqlExtra, defaultTimeout } from \"./adapter.constants\";\nimport type {\n  GraphqlAdapterType,\n  GraphQlExtraType,\n  GraphQlEndpointType,\n  FetchGraphqlAdapterOptionsType,\n} from \"./adapter.types\";\nimport { GraphqlMethod } from \"./adapter.types\";\nimport { getRequestValues, gqlEndpointMapper, gqlEndpointNameMapper } from \"./adapter.utils\";\n\nexport const getGqlAdapter = (): GraphqlAdapterType =>\n  new Adapter<\n    FetchGraphqlAdapterOptionsType,\n    GraphqlMethod,\n    number,\n    GraphQlExtraType,\n    QueryParamsType | string,\n    undefined,\n    GraphQlEndpointType\n  >({\n    name: \"graphql\",\n    defaultMethod: GraphqlMethod.POST,\n    defaultExtra: gqlExtra,\n    systemErrorStatus: 0,\n    systemErrorExtra: gqlExtra,\n  })\n    .onInitialize(({ client }) => {\n      client.setCacheKeyMapper((request) => {\n        return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;\n      });\n      client.setQueryKeyMapper((request) => {\n        return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;\n      });\n      client.setAbortKeyMapper((request) => {\n        return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${request.cancelable}`;\n      });\n    })\n    .setInternalErrorMapping((error) => [error])\n    .setDevtoolsEndpointGetter(gqlEndpointNameMapper)\n    .setEndpointMapper(gqlEndpointMapper)\n    .setFetcher(\n      async ({\n        request,\n        adapterOptions,\n        headers,\n        onError,\n        onResponseEnd,\n        onTimeoutError,\n        onRequestEnd,\n        createAbortListener,\n        getAbortController,\n        onResponseProgress,\n        onResponseStart,\n        onBeforeRequest,\n        onRequestStart,\n        onRequestProgress,\n        onSuccess,\n      }) => {\n        const { fullUrl, payload } = getRequestValues(request);\n\n        const controller = getAbortController();\n        const { timeout: timeoutMs = defaultTimeout, ...restOptions } = adapterOptions || {};\n\n        let timedOut = false;\n        let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n        const unmountListener = createAbortListener({\n          status: 0,\n          extra: gqlExtra,\n        });\n\n        if (timeoutMs > 0 && controller) {\n          timeoutId = setTimeout(() => {\n            timedOut = true;\n            unmountListener();\n            controller.abort();\n          }, timeoutMs);\n        }\n\n        onBeforeRequest();\n        onRequestStart();\n\n        try {\n          const init: RequestInit = {\n            method: request.method,\n            headers: headers as Record<string, string>,\n            signal: controller?.signal,\n            ...restOptions,\n          };\n\n          if (payload) {\n            init.body = payload;\n\n            if (typeof payload === \"string\") {\n              const total = new Blob([payload]).size;\n              onRequestProgress({ total, loaded: total } as ProgressEvent);\n            }\n          }\n\n          onRequestEnd();\n\n          const response = await fetch(fullUrl, init);\n\n          if (timeoutId) {\n            clearTimeout(timeoutId);\n          }\n\n          onResponseStart();\n\n          const responseHeaders: Record<string, string> = {};\n          response.headers.forEach((value, key) => {\n            responseHeaders[key] = value;\n          });\n\n          let body: string;\n\n          if (response.body && typeof response.body.getReader === \"function\") {\n            const reader = response.body.getReader();\n            const contentLength = parseInt(response.headers.get(\"content-length\") || \"0\", 10);\n            let receivedLength = 0;\n            const chunks: Uint8Array[] = [];\n\n            // eslint-disable-next-line no-constant-condition\n            while (true) {\n              // eslint-disable-next-line no-await-in-loop\n              const { done, value } = await reader.read();\n              if (done) {\n                break;\n              }\n              chunks.push(value);\n              receivedLength += value.length;\n              onResponseProgress({ total: contentLength || receivedLength, loaded: receivedLength } as ProgressEvent);\n            }\n\n            const allChunks = new Uint8Array(receivedLength);\n            let position = 0;\n            // eslint-disable-next-line no-restricted-syntax\n            for (const chunk of chunks) {\n              allChunks.set(chunk, position);\n              position += chunk.length;\n            }\n            body = new TextDecoder().decode(allChunks);\n          } else {\n            body = await response.text();\n          }\n\n          onResponseEnd();\n          unmountListener();\n\n          const { status } = response;\n          const parsed = parseResponse(body);\n          const data = parsed?.data ?? null;\n          const errors = parsed?.errors || null;\n          const extensions = parsed?.extensions || {};\n          const failure = errors || status > 399 || status === 0;\n\n          if (failure) {\n            const error = errors || [getErrorMessage()];\n            onError({ error, status, extra: { headers: responseHeaders, extensions } });\n          } else {\n            onSuccess({\n              data,\n              error: errors,\n              status,\n              extra: { headers: responseHeaders, extensions },\n            });\n          }\n        } catch (error: any) {\n          if (timeoutId) clearTimeout(timeoutId);\n          unmountListener();\n\n          if (controller?.signal?.aborted) {\n            if (timedOut) {\n              onTimeoutError({ status: 0, extra: gqlExtra });\n            }\n            return;\n          }\n\n          onError({ error: error, status: 0, extra: gqlExtra });\n        }\n      },\n    );\n","import type { GraphqlAdapterType } from \"./adapter.types\";\nimport { getGqlAdapter } from \"./http-adapter.fetch\";\n\nexport const GraphqlAdapter = (): GraphqlAdapterType => {\n  return getGqlAdapter();\n};\n"],"mappings":";;;AAIA,IAAa,iBAAiB,KAAK,MAAM;AAEzC,IAAa,WAA6B;CACxC,SAAS,EAAE;CACX,YAAY,EAAE;CACf;;;ACND,IAAY,gBAAL,yBAAA,eAAA;AACL,eAAA,UAAA;AACA,eAAA,SAAA;;KACD;;;ACCD,IAAa,oBAA+C,YAAe;CACzE,MAAM,gBAAgB,QAAQ,WAAW,YAAY;CAErD,MAAM,QAAQ,QAAQ;CACtB,MAAM,YAAY,QAAQ;AAW1B,QAAO;EAAE,SATO,gBAAgB,QAAQ,OAAO,MAAM,QAAQ,OAAO,MAAM,qBAAqB;GAAE;GAAO;G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