{"version":3,"file":"athena-request.cjs","sources":["../../src/data/athena-request.ts"],"sourcesContent":["/**\n * The SDK's authenticated transport to agora, without React. Every request:\n *\n * - presents the provider's credential: the live token from `getToken`, renewed\n *   once after a 401 (`sendWithCredentialRenewal`, the statewire transport's\n *   `staleAuth` contract), else the API key, and beside it the app's track\n *   other than Production (`X-Athena-Track`), which wins over a caller's own;\n * - goes to the provider's `backendUrl`, and only there: a path must start\n *   with `/`;\n * - waits out a 429 as agora's `Retry-After` asks, a bounded number of times;\n * - is abandoned after `timeoutMs`;\n * - fails as an `AthenaApiError`, except a request the caller cancelled, which\n *   rejects with the abort's reason as `fetch` does.\n *\n * `useAthenaFetch` binds it to the provider, and the data hooks run on it.\n */\nimport { getAthenaApiBaseUrl } from '../collab/mint';\nimport { sendWithCredentialRenewal } from '../runtime/credential-renewal';\nimport type {\n  AthenaStatewireTokenGetter,\n  StatewireAuthSource,\n} from '../runtime/statewire-auth-headers';\nimport {\n  AthenaApiError,\n  AthenaApiErrorKind,\n  graphQLErrorCode,\n  graphQLErrorEntries,\n  isAthenaApiError,\n  restErrorDetail,\n} from './athena-api-error';\nimport { ATHENA_CLIENT_HEADER, ATHENA_REACT_CLIENT } from '../version';\n\n/** Where a request goes and the credential it presents: the fields of `useAthenaConfig()` it reads. */\nexport interface AthenaRequestConfig {\n  /** The Agora API base (`useAthenaConfig().backendUrl`). */\n  backendUrl: string;\n  apiKey?: string;\n  token?: string | null;\n  getToken?: AthenaStatewireTokenGetter;\n  /**\n   * The track the app is served on (`useAthenaConfig().track`): a track other\n   * than Production rides every request as `X-Athena-Track`, beside the\n   * credential. Production, or none, sends nothing.\n   */\n  track?: string | null;\n}\n\nexport type AthenaQueryParamValue = string | number | boolean | null | undefined;\n\n/** Query-string parameters: `null` and `undefined` are left out, an array repeats its key. */\nexport type AthenaQueryParams = Readonly<\n  Record<string, AthenaQueryParamValue | readonly (string | number | boolean)[]>\n>;\n\n/** A body the SDK can send again (a 401's renewal and a 429's retry resend it): never a stream. */\nexport type AthenaRequestBody = Exclude<BodyInit, ReadableStream>;\n\n/** How a 429 is waited out. */\nexport interface AthenaRateLimitRetry {\n  /** How many times the request is sent again (default 2). */\n  maxRetries?: number;\n  /**\n   * The longest the SDK waits before sending again, in ms (default 60 000:\n   * the longest `Retry-After` agora answers, a full window of its per-user and\n   * per-app limiters). When agora asks for longer, the request fails at once\n   * with the 429, whose `retryAfterMs` says when to come back.\n   */\n  maxWaitMs?: number;\n}\n\nexport interface AthenaRequestOptions {\n  /** Default `GET`, or `POST` when the request has a body. */\n  method?: string;\n  params?: AthenaQueryParams;\n  /** A body sent as JSON (`Content-Type: application/json`). Not with `body`. */\n  json?: unknown;\n  /** A body sent as is (`FormData`, `Blob`, text…). Not with `json`. */\n  body?: AthenaRequestBody;\n  /**\n   * Extra headers. A request presents the provider's credential and no other:\n   * `Authorization`, `X-API-KEY`, `Cookie`, `Proxy-Authorization` and\n   * `X-Athena-View-As` are refused, in any letter case.\n   */\n  headers?: Readonly<Record<string, string>>;\n  /** Cancels the request (and a wait between its attempts); it then rejects with the abort's reason. */\n  signal?: AbortSignal;\n  /** How long one attempt may take, in ms (default 30 000); `0` waits as long as it takes. */\n  timeoutMs?: number;\n  /** How a 429 is waited out; `false` fails at once. */\n  rateLimitRetry?: AthenaRateLimitRetry | false;\n}\n\nexport const ATHENA_REQUEST_TIMEOUT_MS = 30_000;\nconst RATE_LIMIT_MAX_RETRIES = 2;\n/** Agora's longest `Retry-After`: a full 60 s window (`user_request_rate_limit.py`, `app_request_budget.py`). */\nconst RATE_LIMIT_MAX_WAIT_MS = 60_000;\n/** The first wait for a 429 that says nothing of when to come back; it doubles for each retry. */\nconst RATE_LIMIT_FIRST_BACKOFF_MS = 1_000;\n/** What agora's per-user limiter answers, before it runs anything (`user_request_rate_limit.py`). */\nconst RATE_LIMITED_CODE = 'RATE_LIMITED';\nconst SAFE_METHODS: ReadonlySet<string> = new Set(['GET', 'HEAD', 'OPTIONS']);\n/**\n * Headers that say who a request acts as, or through whose eyes\n * (`X-Athena-View-As`, agora's view-as lens): only the provider sets those.\n */\nconst IDENTITY_HEADERS: ReadonlySet<string> = new Set([\n  'authorization',\n  'proxy-authorization',\n  'cookie',\n  'x-api-key',\n  'x-athena-view-as',\n]);\n\n/** The request as sent: its method, its URL and its path for errors (no query string). */\ninterface PreparedRequest {\n  method: string;\n  url: string;\n  path: string;\n  headers: Record<string, string>;\n  body: AthenaRequestBody | undefined;\n  /** `include` only for a request the SDK itself marks (`AthenaTransportOptions`); else the browser's default. */\n  credentials: RequestCredentials | undefined;\n}\n\n/**\n * What only the SDK's own modules set on a request, never an app: these are\n * not `AthenaRequestOptions` fields, so `useAthenaFetch` and the data hooks\n * cannot reach them.\n */\nexport interface AthenaTransportOptions {\n  /**\n   * Send and keep the backend origin's cookies (`credentials: 'include'`).\n   * Only for the one request whose answer sets a cookie the backend reads\n   * again later in the same browser: `startDirectConnectorOauth` binds the\n   * connect to this browser with a `__Host-` cookie its OAuth callback\n   * checks (agora `services/direct_connectors/browser_binding.py`).\n   */\n  withBackendCookies?: boolean;\n}\n\nfunction refuse(message: string, method: string, path: string): AthenaApiError {\n  return new AthenaApiError({ kind: AthenaApiErrorKind.Request, message, method, path });\n}\n\nfunction prepare(\n  config: AthenaRequestConfig,\n  path: string,\n  options: AthenaRequestOptions,\n  transport: AthenaTransportOptions = {},\n): PreparedRequest {\n  const hasBody = options.json !== undefined || options.body !== undefined;\n  const method = (options.method ?? (hasBody ? 'POST' : 'GET')).toUpperCase();\n  const errorPath = path.split('?')[0] ?? path;\n  // A path, never a URL: a request carries the person's credential, so it goes\n  // to the provider's backend and nowhere else.\n  if (!path.startsWith('/') || path.startsWith('//')) {\n    throw refuse(\n      `A request path must start with a single \"/\" (it goes to the provider's backendUrl): ${JSON.stringify(path)}`,\n      method,\n      errorPath,\n    );\n  }\n  if (options.json !== undefined && options.body !== undefined) {\n    throw refuse('A request takes `json` or `body`, not both', method, errorPath);\n  }\n  // Header names are case-insensitive: a lowercase `authorization` would be\n  // sent beside the provider's and could act as someone else, whose answer the\n  // data hooks would then cache under the provider's identity.\n  for (const name of Object.keys(options.headers ?? {})) {\n    if (IDENTITY_HEADERS.has(name.toLowerCase())) {\n      throw refuse(\n        `A request may not set ${name}: it presents the provider's credential and no other`,\n        method,\n        errorPath,\n      );\n    }\n  }\n  const base = getAthenaApiBaseUrl(config.backendUrl);\n  let url: URL;\n  let backendOrigin: string;\n  try {\n    backendOrigin = new URL(base).origin;\n    url = new URL(`${base}${path}`);\n  } catch (error) {\n    throw new AthenaApiError({\n      kind: AthenaApiErrorKind.Request,\n      message: `The provider's backendUrl is not a URL: ${JSON.stringify(config.backendUrl)}`,\n      method,\n      path: errorPath,\n      cause: error,\n    });\n  }\n  if (url.origin !== backendOrigin) {\n    throw refuse(`A request path must stay on the provider's backendUrl: ${JSON.stringify(path)}`, method, errorPath);\n  }\n  for (const [name, value] of Object.entries(options.params ?? {})) {\n    for (const item of Array.isArray(value) ? value : [value]) {\n      if (item !== null && item !== undefined) url.searchParams.append(name, String(item));\n    }\n  }\n  // TODO(#54756): name the app on every call (the provider's `appId`) once agora\n  // records it and limits by it.\n  const headers: Record<string, string> = {\n    Accept: 'application/json',\n    [ATHENA_CLIENT_HEADER]: ATHENA_REACT_CLIENT,\n    ...(options.json !== undefined ? { 'Content-Type': 'application/json' } : {}),\n    ...options.headers,\n  };\n  return {\n    method,\n    url: url.toString(),\n    path: errorPath,\n    headers,\n    body: options.json !== undefined ? JSON.stringify(options.json) : options.body,\n    credentials: transport.withBackendCookies ? 'include' : undefined,\n  };\n}\n\n/**\n * The request's headers with the provider's own over them, by name in any\n * letter case: header names are case-insensitive, so a caller's `x-athena-track`\n * beside the provider's `X-Athena-Track` would otherwise be sent as one\n * comma-joined value agora reads as no track.\n */\nfunction withCredentialHeaders(\n  headers: Record<string, string>,\n  credentialHeaders: Record<string, string>,\n): Headers {\n  const merged = new Headers(headers);\n  for (const [name, value] of Object.entries(credentialHeaders)) merged.set(name, value);\n  return merged;\n}\n\n/** The provider's credential; a `getToken` that throws fails the request as `credential`. */\nfunction credentialSource(config: AthenaRequestConfig, request: PreparedRequest): StatewireAuthSource {\n  const getToken = config.getToken;\n  return {\n    apiKey: config.apiKey,\n    token: config.token,\n    track: config.track,\n    ...(getToken\n      ? {\n          getToken: async (options?: { force?: boolean }) => {\n            try {\n              return await getToken(options);\n            } catch (error) {\n              throw new AthenaApiError({\n                kind: AthenaApiErrorKind.Credential,\n                message: 'The provider could not resolve a credential for the request',\n                method: request.method,\n                path: request.path,\n                cause: error,\n              });\n            }\n          },\n        }\n      : {}),\n  };\n}\n\n/** One attempt's signal: the caller's cancel, and its own timeout. */\ninterface Attempt {\n  signal: AbortSignal;\n  timedOut: () => boolean;\n  /**\n   * Stops the timeout. `keepCancel` leaves the caller's signal able to cancel\n   * the body the caller still reads.\n   */\n  settle: (options?: { keepCancel?: boolean }) => void;\n}\n\nfunction startAttempt(parent: AbortSignal | undefined, timeoutMs: number): Attempt {\n  const controller = new AbortController();\n  let timedOut = false;\n  const forward = () => controller.abort(parent?.reason);\n  if (parent?.aborted) controller.abort(parent.reason);\n  else parent?.addEventListener('abort', forward, { once: true });\n  const timer =\n    timeoutMs > 0 && Number.isFinite(timeoutMs)\n      ? setTimeout(() => {\n          timedOut = true;\n          controller.abort(new DOMException(`No answer within ${timeoutMs} ms`, 'TimeoutError'));\n        }, timeoutMs)\n      : undefined;\n  return {\n    signal: controller.signal,\n    timedOut: () => timedOut,\n    settle: ({ keepCancel = false } = {}) => {\n      if (timer !== undefined) clearTimeout(timer);\n      if (!keepCancel) parent?.removeEventListener('abort', forward);\n    },\n  };\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n  return signal.reason ?? new DOMException('The request was cancelled', 'AbortError');\n}\n\n/** A fetch or a body read that threw: the caller's cancel as is, else a typed failure. */\nfunction failureOf({\n  error,\n  attempt,\n  signal,\n  request,\n  timeoutMs,\n  reading,\n}: {\n  error: unknown;\n  attempt: Attempt;\n  signal: AbortSignal | undefined;\n  request: PreparedRequest;\n  timeoutMs: number;\n  reading: boolean;\n}): unknown {\n  if (signal?.aborted) return abortReason(signal);\n  if (isAthenaApiError(error)) return error;\n  if (attempt.timedOut()) {\n    return new AthenaApiError({\n      kind: AthenaApiErrorKind.Timeout,\n      message: `Athena did not answer within ${timeoutMs} ms`,\n      method: request.method,\n      path: request.path,\n      cause: error,\n    });\n  }\n  return new AthenaApiError({\n    kind: reading ? AthenaApiErrorKind.Response : AthenaApiErrorKind.Network,\n    message: reading ? 'The answer was cut off before it was read' : 'Athena could not be reached',\n    method: request.method,\n    path: request.path,\n    cause: error,\n  });\n}\n\n/**\n * How long agora asked the caller to wait, in ms: the `Retry-After` header\n * (seconds or a date), else the `retryAfterSeconds` of a rate-limit refusal's\n * body. `null` when it said nothing it is possible to read.\n */\nexport function retryAfterMsOf(response: Response, body: unknown, now: number = Date.now()): number | null {\n  const header = response.headers.get('retry-after')?.trim();\n  if (header) {\n    if (/^\\d+$/.test(header)) return Number(header) * 1000;\n    const date = Date.parse(header);\n    if (Number.isFinite(date)) return Math.max(0, date - now);\n  }\n  for (const entry of graphQLErrorEntries(body)) {\n    const seconds = entry.extensions?.retryAfterSeconds;\n    if (typeof seconds === 'number' && Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n  }\n  const seconds = restErrorDetail(body).retryAfterSeconds;\n  return seconds !== null && seconds >= 0 ? seconds * 1000 : null;\n}\n\n/** JSON when it reads as JSON, the text otherwise; `undefined` for nothing. */\nfunction lenientBody(text: string): unknown {\n  if (text.length === 0) return undefined;\n  try {\n    return JSON.parse(text);\n  } catch {\n    return text;\n  }\n}\n\n/** How much of an error body that is not JSON (a proxy's error page) an error keeps. */\nconst TEXT_DETAIL_LIMIT = 1_000;\n\n/**\n * The `AthenaApiError` an error status answers, its body read for agora's code\n * and message. A body the attempt's timeout cut off is a timeout (a stalled\n * 5xx must not read as a 5xx, which a read retries), and the caller's cancel\n * stays a cancel; a body that fails otherwise is left out.\n */\nasync function httpError(\n  response: Response,\n  request: PreparedRequest,\n  { signal, attempt, timeoutMs }: { signal: AbortSignal | undefined; attempt: Attempt; timeoutMs: number },\n): Promise<AthenaApiError> {\n  let body: unknown;\n  try {\n    body = lenientBody(await response.text());\n  } catch (error) {\n    if (signal?.aborted || attempt.timedOut()) {\n      throw failureOf({ error, attempt, signal, request, timeoutMs, reading: true });\n    }\n    body = undefined;\n  }\n  const statusLine = response.statusText\n    ? `${response.status} ${response.statusText}`\n    : `HTTP ${response.status}`;\n  const common = {\n    kind: AthenaApiErrorKind.Http,\n    status: response.status,\n    retryAfterMs: retryAfterMsOf(response, body),\n    method: request.method,\n    path: request.path,\n  };\n  // Not JSON: a gateway's or proxy's page, never agora's words.\n  if (typeof body === 'string') {\n    return new AthenaApiError({ ...common, message: statusLine, detail: body.slice(0, TEXT_DETAIL_LIMIT) });\n  }\n  const errors = graphQLErrorEntries(body);\n  const rest = restErrorDetail(body);\n  return new AthenaApiError({\n    ...common,\n    code: graphQLErrorCode(errors[0]) ?? rest.code,\n    message: errors[0]?.message ?? rest.message ?? statusLine,\n    errors,\n    detail: errors.length > 0 ? undefined : rest.detail,\n  });\n}\n\n/**\n * How long to wait before sending a refused request again, or `null` to fail\n * now. A write goes again only when agora's limiter refused it: that refusal\n * comes before anything runs, so the write cannot apply twice.\n */\nfunction rateLimitWaitMs({\n  error,\n  retry,\n  method,\n  policy,\n}: {\n  error: AthenaApiError;\n  retry: number;\n  method: string;\n  policy: AthenaRateLimitRetry | false | undefined;\n}): number | null {\n  if (policy === false) return null;\n  if (retry >= (policy?.maxRetries ?? RATE_LIMIT_MAX_RETRIES)) return null;\n  if (!SAFE_METHODS.has(method) && error.code !== RATE_LIMITED_CODE) return null;\n  const waitMs =\n    error.retryAfterMs ?? RATE_LIMIT_FIRST_BACKOFF_MS * 2 ** retry * (0.8 + Math.random() * 0.4);\n  return waitMs <= (policy?.maxWaitMs ?? RATE_LIMIT_MAX_WAIT_MS) ? waitMs : null;\n}\n\nfunction sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n  return new Promise((resolve, reject) => {\n    if (signal?.aborted) {\n      reject(abortReason(signal));\n      return;\n    }\n    let timer: ReturnType<typeof setTimeout> | undefined;\n    const onAbort = () => {\n      clearTimeout(timer);\n      if (signal) reject(abortReason(signal));\n    };\n    timer = setTimeout(() => {\n      signal?.removeEventListener('abort', onAbort);\n      resolve();\n    }, ms);\n    signal?.addEventListener('abort', onAbort, { once: true });\n  });\n}\n\n/**\n * Send until agora answers with something other than a 429 the SDK waits out.\n * Answers that response (any status) with the attempt that got it, whose\n * timeout still runs: the caller settles it once the body is read.\n */\nasync function exchange(\n  config: AthenaRequestConfig,\n  request: PreparedRequest,\n  options: AthenaRequestOptions,\n): Promise<{ response: Response; attempt: Attempt; timeoutMs: number }> {\n  const timeoutMs = options.timeoutMs ?? ATHENA_REQUEST_TIMEOUT_MS;\n  const source = credentialSource(config, request);\n  for (let retry = 0; ; retry += 1) {\n    const attempt = startAttempt(options.signal, timeoutMs);\n    let response: Response;\n    try {\n      response = await sendWithCredentialRenewal(source, (credentialHeaders) =>\n        fetch(request.url, {\n          method: request.method,\n          headers: withCredentialHeaders(request.headers, credentialHeaders),\n          body: request.body ?? null,\n          signal: attempt.signal,\n          ...(request.credentials ? { credentials: request.credentials } : {}),\n        }),\n      );\n    } catch (error) {\n      attempt.settle();\n      throw failureOf({ error, attempt, signal: options.signal, request, timeoutMs, reading: false });\n    }\n    if (response.status !== 429) return { response, attempt, timeoutMs };\n    let refusal: AthenaApiError;\n    try {\n      refusal = await httpError(response, request, { signal: options.signal, attempt, timeoutMs });\n    } finally {\n      attempt.settle();\n    }\n    const waitMs = rateLimitWaitMs({ error: refusal, retry, method: request.method, policy: options.rateLimitRetry });\n    if (waitMs === null) throw refusal;\n    await sleep(waitMs, options.signal);\n  }\n}\n\n/**\n * Send a request and answer its response once agora answered 2xx, for a body\n * the caller reads itself (a file, a stream). An error status throws\n * `AthenaApiError`. The timeout covers the wait for the answer, not the body.\n */\nexport async function athenaFetchResponse(\n  config: AthenaRequestConfig,\n  path: string,\n  options: AthenaRequestOptions = {},\n): Promise<Response> {\n  const request = prepare(config, path, options);\n  const { response, attempt, timeoutMs } = await exchange(config, request, options);\n  if (response.ok) {\n    attempt.settle({ keepCancel: true });\n    return response;\n  }\n  try {\n    throw await httpError(response, request, { signal: options.signal, attempt, timeoutMs });\n  } finally {\n    attempt.settle();\n  }\n}\n\n/** A 2xx answer's body: JSON when agora says it is JSON, text otherwise, `undefined` for none. */\nasync function athenaFetchBody(\n  config: AthenaRequestConfig,\n  path: string,\n  options: AthenaRequestOptions,\n  transport: AthenaTransportOptions = {},\n): Promise<{ status: number; body: unknown; request: PreparedRequest }> {\n  const request = prepare(config, path, options, transport);\n  const { response, attempt, timeoutMs } = await exchange(config, request, options);\n  try {\n    if (!response.ok) throw await httpError(response, request, { signal: options.signal, attempt, timeoutMs });\n    let text: string;\n    try {\n      text = await response.text();\n    } catch (error) {\n      throw failureOf({ error, attempt, signal: options.signal, request, timeoutMs, reading: true });\n    }\n    if (text.length === 0) return { status: response.status, body: undefined, request };\n    const contentType = response.headers.get('content-type') ?? '';\n    if (!/[/+]json\\b/i.test(contentType)) {\n      return { status: response.status, body: contentType ? text : lenientBody(text), request };\n    }\n    try {\n      return { status: response.status, body: JSON.parse(text), request };\n    } catch (error) {\n      throw new AthenaApiError({\n        kind: AthenaApiErrorKind.Response,\n        status: response.status,\n        message: 'Agora answered with JSON that could not be read',\n        method: request.method,\n        path: request.path,\n        cause: error,\n      });\n    }\n  } finally {\n    attempt.settle();\n  }\n}\n\n/**\n * Send a request and answer its body: JSON when agora says it is JSON, text\n * otherwise, `undefined` for an empty answer. `T` is the caller's word for\n * what the route answers; nothing checks it.\n */\nexport async function athenaFetchJson<T = unknown>(\n  config: AthenaRequestConfig,\n  path: string,\n  options: AthenaRequestOptions = {},\n): Promise<T> {\n  const { body } = await athenaFetchBody(config, path, options);\n  return body as T;\n}\n\nexport type AthenaGraphQLVariables = Readonly<Record<string, unknown>>;\n\n/**\n * A GraphQL document whose result and variables types travel with it, as\n * graphql-codegen's `TypedDocumentString` (its client preset with\n * `documentMode: 'string'`) carries them.\n */\nexport interface AthenaTypedDocument<TData, TVariables> {\n  toString(): string;\n  __apiType?: (variables: TVariables) => TData;\n}\n\n/** A GraphQL document: its text, or a typed document that names its result and variables. */\nexport type AthenaGraphQLDocument<TData = unknown, TVariables = AthenaGraphQLVariables> =\n  | string\n  | AthenaTypedDocument<TData, TVariables>;\n\nexport interface AthenaGraphQLRequestOptions\n  extends Pick<AthenaRequestOptions, 'headers' | 'signal' | 'timeoutMs' | 'rateLimitRetry'> {\n  /** The operation to run when the document holds several. */\n  operationName?: string;\n}\n\n/**\n * Run one GraphQL operation on agora's `/graphql` and answer its `data`. An\n * answer with errors throws `AthenaApiError` (`kind: 'graphql'`, `code` the\n * first error's `extensions.code`), as does one with no data.\n */\nexport async function athenaGraphQL<TData = unknown, TVariables extends object = AthenaGraphQLVariables>(\n  config: AthenaRequestConfig,\n  document: AthenaGraphQLDocument<TData, TVariables>,\n  variables?: TVariables,\n  options: AthenaGraphQLRequestOptions = {},\n): Promise<TData> {\n  return sendGraphQL(config, document, variables, options, {});\n}\n\n/**\n * `athenaGraphQL` with options only the SDK's own modules set\n * (`AthenaTransportOptions`). Not exported from the package's entry.\n */\nexport async function athenaGraphQLWithTransport<\n  TData = unknown,\n  TVariables extends object = AthenaGraphQLVariables,\n>(\n  config: AthenaRequestConfig,\n  document: AthenaGraphQLDocument<TData, TVariables>,\n  variables: TVariables | undefined,\n  options: AthenaGraphQLRequestOptions,\n  transport: AthenaTransportOptions,\n): Promise<TData> {\n  return sendGraphQL(config, document, variables, options, transport);\n}\n\nasync function sendGraphQL<TData, TVariables extends object>(\n  config: AthenaRequestConfig,\n  document: AthenaGraphQLDocument<TData, TVariables>,\n  variables: TVariables | undefined,\n  options: AthenaGraphQLRequestOptions,\n  transport: AthenaTransportOptions,\n): Promise<TData> {\n  const { operationName, ...requestOptions } = options;\n  // TODO(#54756): send a registered operation's id (`documentId`) instead of its\n  // text once agora allowlists each app's operations.\n  const { status, body, request } = await athenaFetchBody(\n    config,\n    '/graphql',\n    {\n      ...requestOptions,\n      method: 'POST',\n      json: {\n        query: String(document),\n        variables: variables ?? {},\n        ...(operationName ? { operationName } : {}),\n      },\n    },\n    transport,\n  );\n  const errors = graphQLErrorEntries(body);\n  const first = errors[0];\n  if (first) {\n    throw new AthenaApiError({\n      kind: AthenaApiErrorKind.GraphQL,\n      status,\n      code: graphQLErrorCode(first),\n      message: first.message,\n      errors,\n      method: request.method,\n      path: request.path,\n    });\n  }\n  const data: unknown =\n    typeof body === 'object' && body !== null ? Reflect.get(body, 'data') : undefined;\n  if (data === undefined || data === null) {\n    throw new AthenaApiError({\n      kind: AthenaApiErrorKind.GraphQL,\n      status,\n      message: 'The GraphQL answer had no data',\n      method: request.method,\n      path: request.path,\n    });\n  }\n  return data as TData;\n}\n\n/** One operation a GraphQL document defines. */\nexport interface AthenaGraphQLOperation {\n  type: 'query' | 'mutation' | 'subscription';\n  /** `null` for an anonymous operation. */\n  name: string | null;\n}\n\nconst GRAPHQL_IGNORED = /(?:[\\s,﻿]+|#[^\\n\\r]*)+/y;\nconst GRAPHQL_NAME = /[_A-Za-z][_0-9A-Za-z]*/y;\n\n/**\n * The operations a GraphQL document defines, in order, fragments left out. A\n * lexical read that skips strings, comments, variable definitions (default\n * values included), directives and selection sets; it never validates the\n * document, which agora does.\n */\nexport function graphQLOperationsOf(document: string): AthenaGraphQLOperation[] {\n  const operations: AthenaGraphQLOperation[] = [];\n  let at = 0;\n  const skipIgnored = () => {\n    GRAPHQL_IGNORED.lastIndex = at;\n    if (GRAPHQL_IGNORED.exec(document)) at = GRAPHQL_IGNORED.lastIndex;\n  };\n  const readName = (): string | null => {\n    GRAPHQL_NAME.lastIndex = at;\n    const name = GRAPHQL_NAME.exec(document)?.[0] ?? null;\n    if (name !== null) at = GRAPHQL_NAME.lastIndex;\n    return name;\n  };\n  /** Past the balanced `(…)` or `{…}` that opens at `at`, strings and comments included. */\n  const skipGroup = () => {\n    const open = document[at];\n    const close = open === '(' ? ')' : '}';\n    let depth = 0;\n    while (at < document.length) {\n      if (document.startsWith('\"\"\"', at)) {\n        const end = document.indexOf('\"\"\"', at + 3);\n        at = end === -1 ? document.length : end + 3;\n        continue;\n      }\n      const char = document[at];\n      if (char === '\"') {\n        at += 1;\n        while (at < document.length && document[at] !== '\"' && document[at] !== '\\n') {\n          at += document[at] === '\\\\' ? 2 : 1;\n        }\n        at += 1;\n        continue;\n      }\n      if (char === '#') {\n        while (at < document.length && document[at] !== '\\n') at += 1;\n        continue;\n      }\n      at += 1;\n      if (char === open) depth += 1;\n      else if (char === close) {\n        depth -= 1;\n        if (depth === 0) return;\n      }\n    }\n  };\n  /** Past a definition's header (variables, type condition, directives) and its selection set. */\n  const skipDefinition = () => {\n    while (at < document.length) {\n      skipIgnored();\n      const char = document[at];\n      if (char === '{') {\n        skipGroup();\n        return;\n      }\n      if (char === '(') skipGroup();\n      else at += 1;\n    }\n  };\n  for (;;) {\n    skipIgnored();\n    if (at >= document.length) return operations;\n    if (document[at] === '{') {\n      operations.push({ type: 'query', name: null });\n      skipGroup();\n      continue;\n    }\n    const word = readName();\n    if (word === 'query' || word === 'mutation' || word === 'subscription') {\n      skipIgnored();\n      operations.push({ type: word, name: readName() });\n    }\n    skipDefinition();\n  }\n}\n\n/**\n * The operation a request runs: the one `operationName` names, else the\n * document's only one. `null` when neither picks one (agora refuses those).\n */\nexport function selectedGraphQLOperation(\n  document: string,\n  operationName?: string | null,\n): AthenaGraphQLOperation | null {\n  const operations = graphQLOperationsOf(document);\n  if (operationName) return operations.find((operation) => operation.name === operationName) ?? null;\n  return operations.length === 1 ? (operations[0] ?? null) : null;\n}\n\n/**\n * An authenticated fetch bound to one configuration (see `useAthenaFetch`).\n * Called, it answers the route's body; `raw` answers the response itself and\n * `graphql` runs one GraphQL operation.\n */\nexport interface AthenaFetch {\n  <T = unknown>(path: string, options?: AthenaRequestOptions): Promise<T>;\n  raw(path: string, options?: AthenaRequestOptions): Promise<Response>;\n  graphql<TData = unknown, TVariables extends object = AthenaGraphQLVariables>(\n    document: AthenaGraphQLDocument<TData, TVariables>,\n    variables?: TVariables,\n    options?: AthenaGraphQLRequestOptions,\n  ): Promise<TData>;\n}\n\n/**\n * `useAthenaFetch` without React: the transport bound to `config`, read once.\n * Hosts outside a component can pass `useAthenaConfig()`'s value along.\n */\nexport function createAthenaFetch(config: AthenaRequestConfig): AthenaFetch {\n  const bound: AthenaRequestConfig = {\n    backendUrl: config.backendUrl,\n    apiKey: config.apiKey,\n    token: config.token,\n    getToken: config.getToken,\n    track: config.track,\n  };\n  return Object.assign(\n    <T = unknown>(path: string, options?: AthenaRequestOptions) =>\n      athenaFetchJson<T>(bound, path, options),\n    {\n      raw: (path: string, options?: AthenaRequestOptions) => athenaFetchResponse(bound, path, options),\n      graphql: <TData = unknown, TVariables extends object = AthenaGraphQLVariables>(\n        document: AthenaGraphQLDocument<TData, TVariables>,\n        variables?: TVariables,\n        options?: AthenaGraphQLRequestOptions,\n      ) => athenaGraphQL<TData, TVariables>(bound, document, variables, options),\n    },\n  );\n}\n"],"names":["AthenaApiError","AthenaApiErrorKind","getAthenaApiBaseUrl","ATHENA_CLIENT_HEADER","ATHENA_REACT_CLIENT","isAthenaApiError","graphQLErrorEntries","seconds","restErrorDetail","graphQLErrorCode","sendWithCredentialRenewal"],"mappings":";;;;;;AA4FO,MAAM,4BAA4B;AACzC,MAAM,yBAAyB;AAE/B,MAAM,yBAAyB;AAE/B,MAAM,8BAA8B;AAEpC,MAAM,oBAAoB;AAC1B,MAAM,eAAoC,oBAAI,IAAI,CAAC,OAAO,QAAQ,SAAS,CAAC;AAK5E,MAAM,uCAA4C,IAAI;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AA6BD,SAAS,OAAO,SAAiB,QAAgB,MAA8B;A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