import { createContext, useState, useMemo, useCallback, createElement, useContext, useRef, useEffect } from 'react';
import { useSyncExternalStore } from 'use-sync-external-store/shim';

// src/gateway/use-athena-gateway.ts

// src/gateway/errors.ts
var AthenaGatewayError = class _AthenaGatewayError extends Error {
  code;
  status;
  endpoint;
  method;
  requestId;
  hint;
  causeDetail;
  constructor(input) {
    super(input.message);
    this.name = "AthenaGatewayError";
    this.code = input.code;
    this.status = input.status ?? 0;
    this.endpoint = input.endpoint;
    this.method = input.method;
    this.requestId = input.requestId;
    this.hint = input.hint;
    this.causeDetail = input.cause;
  }
  toDetails() {
    return {
      code: this.code,
      message: this.message,
      status: this.status,
      endpoint: this.endpoint,
      method: this.method,
      requestId: this.requestId,
      hint: this.hint,
      cause: this.causeDetail
    };
  }
  static fromResponse(response, fallback) {
    const details = response.errorDetails;
    if (details) {
      return new _AthenaGatewayError({
        code: details.code,
        message: details.message,
        status: details.status,
        endpoint: details.endpoint ?? fallback.endpoint,
        method: details.method ?? fallback.method,
        requestId: details.requestId ?? fallback.requestId,
        hint: details.hint,
        cause: details.cause
      });
    }
    return new _AthenaGatewayError({
      code: "HTTP_ERROR",
      message: response.error ?? "Gateway request failed",
      status: response.status,
      endpoint: fallback.endpoint,
      method: fallback.method,
      requestId: fallback.requestId
    });
  }
};
function isAthenaGatewayError(error) {
  return error instanceof AthenaGatewayError;
}

// src/gateway/client.ts
var DEFAULT_BASE_URL = "https://athena-db.com";
var DEFAULT_CLIENT = "railway_direct";
var FALLBACK_SDK_VERSION = "1.3.0";
var SDK_NAME = "xylex-group/athena";
var SDK_VERSION = typeof process !== "undefined" && process?.env?.npm_package_version ? process.env.npm_package_version : FALLBACK_SDK_VERSION;
var SDK_HEADER_VALUE = `${SDK_NAME} ${SDK_VERSION}`;
function parseResponseBody(rawText, contentType) {
  if (!rawText) {
    return { parsed: null, parseFailed: false };
  }
  const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
  const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
  if (!looksJson) {
    return { parsed: rawText, parseFailed: false };
  }
  try {
    return { parsed: JSON.parse(rawText), parseFailed: false };
  } catch {
    return { parsed: rawText, parseFailed: true };
  }
}
function normalizeHeaderValue(value) {
  return value ? value : void 0;
}
function isRecord(value) {
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function resolveRequestId(headers) {
  return headers.get("x-request-id") ?? headers.get("x-correlation-id") ?? headers.get("x-athena-request-id") ?? void 0;
}
function resolveErrorMessage(payload, fallback) {
  if (isRecord(payload)) {
    const messageCandidates = [payload.error, payload.message, payload.details];
    for (const candidate of messageCandidates) {
      if (typeof candidate === "string" && candidate.trim().length > 0) {
        return candidate.trim();
      }
    }
  }
  if (typeof payload === "string" && payload.trim().length > 0) {
    return payload.trim();
  }
  return fallback;
}
function detailsFromError(error) {
  return error.toDetails();
}
function toQueryScalar(value) {
  if (value === null || value === void 0) return "null";
  if (typeof value === "boolean") return value ? "true" : "false";
  if (typeof value === "number") return Number.isFinite(value) ? String(value) : "null";
  return String(value);
}
function toQueryArray(values) {
  return `{${values.map(toQueryScalar).join(",")}}`;
}
function toRpcArgumentQueryValue(value) {
  if (Array.isArray(value)) return toQueryArray(value);
  if (value && typeof value === "object") return JSON.stringify(value);
  return toQueryScalar(value);
}
function toRpcFilterQueryValue(filter) {
  const value = filter.value;
  switch (filter.operator) {
    case "in": {
      if (!Array.isArray(value)) {
        throw new AthenaGatewayError({
          code: "UNKNOWN_ERROR",
          message: `RPC filter "${filter.column}" with operator "in" requires an array value`,
          status: 0
        });
      }
      return `in.${toQueryArray(value)}`;
    }
    case "is":
      return `is.${toQueryScalar(value)}`;
    case "eq":
    case "neq":
    case "gt":
    case "gte":
    case "lt":
    case "lte":
    case "like":
    case "ilike":
      return `${filter.operator}.${toQueryScalar(value)}`;
  }
}
function buildRpcGetEndpoint(payload) {
  const functionName = (payload.function_name ?? payload.function).trim();
  if (!functionName) {
    throw new AthenaGatewayError({
      code: "UNKNOWN_ERROR",
      message: "rpc requires a function name",
      status: 0,
      endpoint: "/gateway/rpc",
      method: "GET"
    });
  }
  const query = new URLSearchParams();
  if (payload.schema) query.set("schema", payload.schema);
  if (payload.select) query.set("select", payload.select);
  if (payload.count) query.set("count", payload.count);
  if (payload.head) query.set("head", "true");
  if (typeof payload.limit === "number") query.set("limit", String(payload.limit));
  if (typeof payload.offset === "number") query.set("offset", String(payload.offset));
  if (payload.order?.column) {
    query.set(
      "order",
      payload.order.ascending === false ? `${payload.order.column}.desc` : payload.order.column
    );
  }
  if (payload.args) {
    for (const [key, value] of Object.entries(payload.args)) {
      query.set(key, toRpcArgumentQueryValue(value));
    }
  }
  if (payload.filters?.length) {
    for (const filter of payload.filters) {
      if (payload.args && Object.prototype.hasOwnProperty.call(payload.args, filter.column)) {
        throw new AthenaGatewayError({
          code: "UNKNOWN_ERROR",
          message: `RPC filter "${filter.column}" conflicts with RPC argument "${filter.column}" in GET mode`,
          status: 0
        });
      }
      query.set(filter.column, toRpcFilterQueryValue(filter));
    }
  }
  const endpoint = `/rpc/${encodeURIComponent(functionName)}`;
  const queryText = query.toString();
  const withQuery = queryText ? `${endpoint}?${queryText}` : endpoint;
  return withQuery;
}
function buildHeaders(config, options) {
  const mergedStripNulls = options?.stripNulls ?? true;
  const extraHeaders = {
    ...config.headers ?? {},
    ...options?.headers ?? {}
  };
  const headerClient = extraHeaders["x-athena-client"] ?? extraHeaders["X-Athena-Client"];
  const finalClient = options?.client ?? config.client ?? (typeof headerClient === "string" ? headerClient : void 0) ?? DEFAULT_CLIENT;
  const finalApiKey = options?.apiKey ?? config.apiKey;
  const finalPublishEvent = options?.publishEvent ?? config.publishEvent;
  const headers = {
    "Content-Type": "application/json",
    "X-Athena-Sdk": SDK_HEADER_VALUE
  };
  if (options?.userId ?? config.userId) {
    headers["X-User-Id"] = options?.userId ?? config.userId ?? "";
  }
  if (options?.organizationId ?? config.organizationId) {
    headers["X-Organization-Id"] = options?.organizationId ?? config.organizationId ?? "";
  }
  if (finalClient) {
    headers["X-Athena-Client"] = finalClient;
  }
  const finalBackend = options?.backend ?? config.backend;
  if (finalBackend) {
    const type = typeof finalBackend === "string" ? finalBackend : finalBackend.type;
    if (type) headers["X-Backend-Type"] = type;
  }
  if (typeof mergedStripNulls === "boolean") {
    headers["X-Strip-Nulls"] = mergedStripNulls ? "true" : "false";
  }
  if (finalPublishEvent) {
    headers["X-Publish-Event"] = finalPublishEvent;
  }
  if (finalApiKey) {
    headers["apikey"] = finalApiKey;
    headers["x-api-key"] = headers["x-api-key"] ?? finalApiKey;
  }
  const athenaClientKeys = ["x-athena-client", "X-Athena-Client"];
  Object.entries(extraHeaders).forEach(([key, value]) => {
    if (athenaClientKeys.includes(key)) return;
    const normalized = normalizeHeaderValue(value);
    if (normalized) {
      headers[key] = normalized;
    }
  });
  return headers;
}
async function callAthena(config, endpoint, method, payload, options) {
  const baseUrl = (options?.baseUrl ?? config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
  const url = `${baseUrl}${endpoint}`;
  const headers = buildHeaders(config, options);
  try {
    const requestInit = {
      method,
      headers
    };
    if (method !== "GET") {
      requestInit.body = JSON.stringify(payload);
    }
    const response = await fetch(url, requestInit);
    const rawText = await response.text();
    const requestId = resolveRequestId(response.headers);
    const parsedBody = parseResponseBody(
      rawText ?? "",
      response.headers.get("content-type")
    );
    if (parsedBody.parseFailed) {
      const invalidJsonError = new AthenaGatewayError({
        code: "INVALID_JSON",
        message: "Gateway returned malformed JSON",
        status: response.status,
        endpoint,
        method,
        requestId,
        hint: "Verify the gateway response body is valid JSON.",
        cause: rawText.slice(0, 300)
      });
      return {
        ok: false,
        status: response.status,
        data: null,
        error: invalidJsonError.message,
        errorDetails: detailsFromError(invalidJsonError),
        raw: parsedBody.parsed
      };
    }
    const parsed = parsedBody.parsed;
    const parsedPayload = isRecord(parsed) ? parsed : null;
    if (!response.ok) {
      const httpError = new AthenaGatewayError({
        code: "HTTP_ERROR",
        message: resolveErrorMessage(
          parsed,
          `Athena gateway ${method} ${endpoint} failed with status ${response.status}`
        ),
        status: response.status,
        endpoint,
        method,
        requestId
      });
      return {
        ok: false,
        status: response.status,
        data: null,
        error: httpError.message,
        errorDetails: detailsFromError(httpError),
        raw: parsed
      };
    }
    const payloadData = parsedPayload && "data" in parsedPayload ? parsedPayload.data : parsed;
    const payloadCount = parsedPayload && "count" in parsedPayload ? typeof parsedPayload.count === "number" || parsedPayload.count === null ? parsedPayload.count : void 0 : void 0;
    return {
      ok: true,
      status: response.status,
      data: payloadData ?? null,
      count: payloadCount,
      error: void 0,
      errorDetails: null,
      raw: parsed
    };
  } catch (callError) {
    const message = callError instanceof Error ? callError.message : String(callError);
    const networkError = new AthenaGatewayError({
      code: "NETWORK_ERROR",
      message: `Network error while calling ${method} ${endpoint}: ${message}`,
      endpoint,
      method,
      cause: message,
      hint: "Check gateway URL, DNS, and network reachability."
    });
    return {
      ok: false,
      status: 0,
      data: null,
      error: networkError.message,
      errorDetails: detailsFromError(networkError),
      raw: null
    };
  }
}
function createAthenaGatewayClient(config = {}) {
  return {
    baseUrl: (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, ""),
    buildHeaders(options) {
      return buildHeaders(config, options);
    },
    fetchGateway(payload, options) {
      return callAthena(config, "/gateway/fetch", "POST", payload, options);
    },
    insertGateway(payload, options) {
      return callAthena(config, "/gateway/insert", "PUT", payload, options);
    },
    updateGateway(payload, options) {
      return callAthena(config, "/gateway/update", "POST", payload, options);
    },
    deleteGateway(payload, options) {
      return callAthena(config, "/gateway/delete", "DELETE", payload, options);
    },
    rpcGateway(payload, options) {
      if (options?.get) {
        const endpoint = buildRpcGetEndpoint(payload);
        return callAthena(config, endpoint, "GET", null, options);
      }
      return callAthena(config, "/gateway/rpc", "POST", payload, options);
    },
    queryGateway(payload, options) {
      return callAthena(config, "/gateway/query", "POST", payload, options);
    }
  };
}

// src/gateway/use-athena-gateway.ts
function useAthenaGateway(config) {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const [lastRequest, setLastRequest] = useState(
    null
  );
  const [lastResponse, setLastResponse] = useState(null);
  const client = useMemo(
    () => createAthenaGatewayClient({
      client: config?.client,
      baseUrl: config?.baseUrl,
      apiKey: config?.apiKey,
      backend: config?.backend,
      publishEvent: config?.publishEvent,
      headers: config?.headers,
      userId: config?.userId,
      organizationId: config?.organizationId
    }),
    [
      config?.baseUrl,
      config?.client,
      config?.apiKey,
      config?.backend,
      config?.publishEvent,
      config?.headers,
      config?.userId,
      config?.organizationId
    ]
  );
  const callWithLifecycle = useCallback(
    async (fn, metadata) => {
      const requestLog = {
        endpoint: metadata.endpoint,
        method: metadata.method,
        payload: metadata.payload,
        headers: client.buildHeaders(metadata.options),
        timestamp: (/* @__PURE__ */ new Date()).toISOString()
      };
      setLastRequest(requestLog);
      setIsLoading(true);
      setError(null);
      let response;
      try {
        response = await fn();
        setLastResponse({ ...response, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
        if (!response.ok) {
          const failure = AthenaGatewayError.fromResponse(response, {
            endpoint: metadata.endpoint,
            method: metadata.method
          });
          setError(failure.message);
          throw failure;
        }
        return response;
      } catch (callError) {
        const message = callError instanceof Error ? callError.message : String(callError);
        const typedError = callError instanceof AthenaGatewayError ? callError : new AthenaGatewayError({
          code: "UNKNOWN_ERROR",
          message,
          endpoint: metadata.endpoint,
          method: metadata.method,
          cause: message
        });
        setError(message);
        setLastResponse({
          timestamp: (/* @__PURE__ */ new Date()).toISOString(),
          status: typedError.status || response?.status || 0,
          ok: false,
          data: null,
          raw: null,
          error: typedError.message,
          errorDetails: typedError.toDetails()
        });
        throw typedError;
      } finally {
        setIsLoading(false);
      }
    },
    [client]
  );
  const defaultStripNulls = true;
  const fetchGateway = useCallback(
    (payload, options) => {
      const normalizedPayload = {
        ...payload,
        conditions: payload.conditions ?? [],
        strip_nulls: payload.strip_nulls ?? options?.stripNulls ?? defaultStripNulls
      };
      return callWithLifecycle(
        () => client.fetchGateway(normalizedPayload, options),
        {
          endpoint: "/gateway/fetch",
          method: "POST",
          payload: normalizedPayload,
          options
        }
      );
    },
    [callWithLifecycle, client]
  );
  const insertGateway = useCallback(
    (payload, options) => callWithLifecycle(() => client.insertGateway(payload, options), {
      endpoint: "/gateway/insert",
      method: "PUT",
      payload,
      options
    }),
    [callWithLifecycle, client]
  );
  const updateGateway = useCallback(
    (payload, options) => {
      const normalizedPayload = {
        ...payload,
        conditions: payload.conditions ?? [],
        strip_nulls: payload.strip_nulls ?? options?.stripNulls ?? defaultStripNulls
      };
      return callWithLifecycle(
        () => client.updateGateway(normalizedPayload, options),
        {
          endpoint: "/gateway/update",
          method: "POST",
          payload: normalizedPayload,
          options
        }
      );
    },
    [callWithLifecycle, client]
  );
  const deleteGateway = useCallback(
    (payload, options) => {
      if (!payload.resource_id) {
        throw new Error(
          "deleteGateway requires resource_id (the unique identifier of the record to delete)"
        );
      }
      return callWithLifecycle(
        () => client.deleteGateway(payload, options),
        { endpoint: "/gateway/delete", method: "DELETE", payload, options }
      );
    },
    [callWithLifecycle, client]
  );
  const rpcGateway = useCallback(
    (payload, options) => callWithLifecycle(() => client.rpcGateway(payload, options), {
      endpoint: options?.get ? `/rpc/${payload.function}` : "/gateway/rpc",
      method: options?.get ? "GET" : "POST",
      payload,
      options
    }),
    [callWithLifecycle, client]
  );
  return {
    fetchGateway,
    insertGateway,
    updateGateway,
    deleteGateway,
    rpcGateway,
    isLoading,
    error,
    lastRequest,
    lastResponse,
    baseUrl: client.baseUrl
  };
}

// src/react/utils.ts
function isRecord2(value) {
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function isPrimitive(value) {
  return value == null || ["string", "number", "boolean"].includes(typeof value);
}
function encodePrimitive(value) {
  if (value === null) return "null:0:";
  if (value === void 0) return "undefined:0:";
  if (typeof value === "string") return `str:${value.length}:${value}`;
  if (typeof value === "number") {
    const serialized2 = Number.isFinite(value) ? String(value) : "nan";
    return `num:${serialized2.length}:${serialized2}`;
  }
  const serialized = value ? "1" : "0";
  return `bool:${serialized.length}:${serialized}`;
}
function stableSerialize(value, seen) {
  if (value === null) return "null";
  if (value === void 0) return "undefined";
  const valueType = typeof value;
  if (valueType === "string") return `"${value}"`;
  if (valueType === "number") return Number.isFinite(value) ? String(value) : "null";
  if (valueType === "boolean") return value ? "true" : "false";
  if (valueType === "bigint") return `${String(value)}n`;
  if (valueType === "symbol") return `symbol:${String(value)}`;
  if (valueType === "function") {
    const namedFunction = value;
    return `function:${namedFunction.name || "anonymous"}`;
  }
  if (value instanceof Date) return `date:${value.toISOString()}`;
  if (Array.isArray(value)) {
    return `[${value.map((item) => stableSerialize(item, seen)).join(",")}]`;
  }
  if (valueType === "object") {
    const objectValue = value;
    if (seen.has(objectValue)) return "[circular]";
    seen.add(objectValue);
    const keys = Object.keys(objectValue).sort();
    const serialized = `{${keys.map((key) => `${key}:${stableSerialize(objectValue[key], seen)}`).join(",")}}`;
    seen.delete(objectValue);
    return serialized;
  }
  return String(value);
}
function safeSerializeQueryKey(queryKey) {
  try {
    if (typeof queryKey === "string") {
      return `key:${queryKey}`;
    }
    if (Array.isArray(queryKey) && queryKey.every(isPrimitive)) {
      return `arr:${queryKey.map((item) => encodePrimitive(item)).join("|")}`;
    }
    return `ser:${stableSerialize(queryKey, /* @__PURE__ */ new WeakSet())}`;
  } catch {
    try {
      return `fallback:${String(queryKey)}`;
    } catch {
      return "fallback:[unserializable-query-key]";
    }
  }
}
function sleep(ms) {
  if (ms <= 0) return Promise.resolve();
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}
function resolveRetryCount(retry) {
  if (retry === false || retry == null) return 0;
  if (!Number.isFinite(retry)) return 0;
  return Math.max(0, Math.trunc(retry));
}
function resolveRetryDelay(retryDelay, attempt) {
  if (typeof retryDelay === "function") {
    const resolved = retryDelay(attempt);
    if (!Number.isFinite(resolved)) return 0;
    return Math.max(0, resolved);
  }
  if (typeof retryDelay === "number") {
    if (!Number.isFinite(retryDelay)) return 0;
    return Math.max(0, retryDelay);
  }
  return 0;
}
async function runWithRetry(execute, options) {
  const retries = resolveRetryCount(options?.retry);
  let attempt = 0;
  for (; ; ) {
    attempt += 1;
    try {
      return await execute(attempt);
    } catch (error) {
      if (attempt > retries) {
        throw error;
      }
      const delay = resolveRetryDelay(options?.retryDelay, attempt);
      await sleep(delay);
    }
  }
}
function errorMessageFromUnknown(error) {
  if (typeof error === "string" && error.trim()) return error.trim();
  if (error instanceof Error && error.message.trim()) return error.message.trim();
  if (isRecord2(error)) {
    const messageCandidate = error.message ?? error.error;
    if (typeof messageCandidate === "string" && messageCandidate.trim()) {
      return messageCandidate.trim();
    }
  }
  return "Athena request failed";
}
function normalizeAthenaError(error, source) {
  if (isRecord2(error) && typeof error.message === "string" && (error.status === void 0 || typeof error.status === "number") && (error.code === void 0 || typeof error.code === "string")) {
    return {
      message: error.message,
      status: typeof error.status === "number" ? error.status : void 0,
      code: typeof error.code === "string" ? error.code : void 0,
      details: error.details,
      raw: error.raw ?? source ?? error
    };
  }
  if (isAthenaGatewayError(error)) {
    const details = error.toDetails();
    return {
      message: details.message,
      status: details.status,
      code: details.code,
      details,
      raw: source ?? error
    };
  }
  if (isRecord2(source) && source.errorDetails && isRecord2(source.errorDetails)) {
    const details = source.errorDetails;
    return {
      message: errorMessageFromUnknown(error ?? source.error),
      status: typeof source.status === "number" ? source.status : void 0,
      code: typeof details.code === "string" ? details.code : void 0,
      details,
      raw: source
    };
  }
  if (isRecord2(source) && typeof source.status === "number") {
    return {
      message: errorMessageFromUnknown(error),
      status: source.status,
      details: source,
      raw: source
    };
  }
  return {
    message: errorMessageFromUnknown(error),
    raw: source ?? error
  };
}
function isAthenaResponseLike(value) {
  if (!isRecord2(value)) return false;
  if ("error" in value || "errorDetails" in value) return true;
  if ("status" in value && typeof value.status === "number") {
    return "data" in value || "raw" in value;
  }
  return "data" in value && ("raw" in value || "status" in value);
}
function normalizeAthenaResult(value, select) {
  if (isAthenaResponseLike(value)) {
    const status = typeof value.status === "number" ? value.status : value.error != null ? 500 : 200;
    if (value.error != null) {
      return {
        data: void 0,
        error: normalizeAthenaError(value.error, value),
        status,
        raw: value.raw ?? value
      };
    }
    const hasData = "data" in value;
    const sourceData2 = hasData ? value.data : void 0;
    const selectedData2 = sourceData2 === void 0 ? void 0 : sourceData2 === null ? null : select ? select(sourceData2) : sourceData2;
    return {
      data: selectedData2,
      error: null,
      status,
      raw: value.raw ?? value
    };
  }
  const sourceData = value;
  const selectedData = select ? select(sourceData) : sourceData;
  return {
    data: selectedData,
    error: null,
    status: 200,
    raw: value
  };
}

// src/react/query-client.ts
function createInitialQueryState(initialData) {
  return {
    status: initialData === void 0 ? "idle" : "success",
    isFetching: false,
    data: initialData,
    error: null,
    updatedAt: initialData === void 0 ? void 0 : Date.now()
  };
}
function createInitialMutationState() {
  return {
    status: "idle",
    data: void 0,
    error: null,
    isLoading: false,
    lastVariables: void 0,
    lastResponse: void 0,
    updatedAt: void 0
  };
}
function shouldUseMemoryCache(config) {
  return config.cache?.mode === "memory";
}
var AthenaQueryClient = class {
  queryEntries = /* @__PURE__ */ new Map();
  mutationEntries = /* @__PURE__ */ new Map();
  inflightQueries = /* @__PURE__ */ new Map();
  eventSubscribers = /* @__PURE__ */ new Set();
  adapters = /* @__PURE__ */ new Set();
  requestCounter = 0;
  config;
  defaultQueryOptions;
  defaultMutationOptions;
  constructor(config = {}) {
    this.config = {
      cache: {
        mode: config.cache?.mode ?? "none",
        staleTime: config.cache?.staleTime,
        gcTime: config.cache?.gcTime
      },
      defaultQueryOptions: config.defaultQueryOptions,
      defaultMutationOptions: config.defaultMutationOptions
    };
    this.defaultQueryOptions = {
      retry: config.defaultQueryOptions?.retry ?? 0,
      retryDelay: config.defaultQueryOptions?.retryDelay,
      refetchOnMount: config.defaultQueryOptions?.refetchOnMount ?? true,
      refetchOnWindowFocus: config.defaultQueryOptions?.refetchOnWindowFocus ?? false,
      refetchOnReconnect: config.defaultQueryOptions?.refetchOnReconnect ?? false
    };
    this.defaultMutationOptions = {
      retry: config.defaultMutationOptions?.retry ?? 0,
      retryDelay: config.defaultMutationOptions?.retryDelay
    };
  }
  getQueryKeyToken(queryKey) {
    return safeSerializeQueryKey(queryKey);
  }
  getMutationKeyToken(mutationKey) {
    if (mutationKey == null) {
      return "__mutation__default__";
    }
    return safeSerializeQueryKey(mutationKey);
  }
  getQueryState(key) {
    const entry = this.ensureQueryEntry(key);
    return entry.state;
  }
  getMutationState(key) {
    const entry = this.ensureMutationEntry(key);
    return entry.state;
  }
  subscribeQuery(key, listener) {
    const entry = this.ensureQueryEntry(key);
    if (entry.gcTimer) {
      clearTimeout(entry.gcTimer);
      entry.gcTimer = void 0;
    }
    entry.listeners.add(listener);
    return () => {
      const current = this.queryEntries.get(key);
      if (!current) return;
      current.listeners.delete(listener);
      if (current.listeners.size === 0) {
        this.scheduleQueryGc(current);
      }
    };
  }
  subscribeMutation(key, listener) {
    const entry = this.ensureMutationEntry(key);
    if (entry.gcTimer) {
      clearTimeout(entry.gcTimer);
      entry.gcTimer = void 0;
    }
    entry.listeners.add(listener);
    return () => {
      const current = this.mutationEntries.get(key);
      if (!current) return;
      current.listeners.delete(listener);
      if (current.listeners.size === 0) {
        this.scheduleMutationGc(current);
      }
    };
  }
  subscribeEvents(listener) {
    this.eventSubscribers.add(listener);
    return () => {
      this.eventSubscribers.delete(listener);
    };
  }
  attachAdapter(adapter) {
    this.adapters.add(adapter);
    return () => {
      this.adapters.delete(adapter);
    };
  }
  resetQuery(queryKey) {
    const key = this.getQueryKeyToken(queryKey);
    const entry = this.ensureQueryEntry(key);
    entry.activeRequestId = ++this.requestCounter;
    this.setQueryState(entry, createInitialQueryState(), "query_reset");
    this.inflightQueries.delete(key);
  }
  resetMutation(mutationKey) {
    const key = this.getMutationKeyToken(mutationKey);
    const entry = this.ensureMutationEntry(key);
    entry.activeRequestId = ++this.requestCounter;
    this.setMutationState(entry, createInitialMutationState(), "mutation_reset");
  }
  async executeQuery(input) {
    const entry = this.ensureQueryEntry(input.queryKeyToken);
    if (input.dedupe !== false) {
      const existing = this.inflightQueries.get(input.queryKeyToken);
      if (existing) {
        return existing;
      }
    }
    if (!input.force && shouldUseMemoryCache(this.config)) {
      const staleTime = this.config.cache?.staleTime ?? 0;
      const hasFreshData = entry.state.status === "success" && entry.state.data !== void 0 && entry.state.updatedAt !== void 0 && Date.now() - entry.state.updatedAt <= staleTime;
      if (hasFreshData) {
        return {
          data: entry.state.data,
          error: null,
          status: 200,
          raw: entry.state.lastResponse ?? entry.state.data,
          __applied: true
        };
      }
    }
    const requestId = ++this.requestCounter;
    entry.activeRequestId = requestId;
    const startRequestLog = {
      requestId,
      queryKey: input.queryKey,
      queryKeyToken: input.queryKeyToken,
      attempt: 1,
      startedAt: Date.now()
    };
    const loadingStatus = entry.state.data === void 0 ? "loading" : entry.state.status;
    this.setQueryState(
      entry,
      {
        ...entry.state,
        status: loadingStatus,
        isFetching: true,
        error: null,
        lastRequest: startRequestLog
      },
      "query_updated"
    );
    const executionPromise = runWithRetry(
      async (attempt) => {
        const attemptRequestLog = {
          ...startRequestLog,
          attempt
        };
        if (entry.activeRequestId === requestId) {
          this.setQueryState(
            entry,
            {
              ...entry.state,
              lastRequest: attemptRequestLog,
              isFetching: true
            },
            "query_updated"
          );
        }
        const rawResult = await input.queryFn();
        const normalized = normalizeAthenaResult(rawResult, input.select);
        if (normalized.error) {
          throw {
            __athenaNormalizedError: normalized.error,
            __athenaStatus: normalized.status,
            __athenaRaw: normalized.raw,
            __athenaResponse: rawResult
          };
        }
        return {
          normalized,
          response: rawResult,
          attempt
        };
      },
      {
        retry: input.retry,
        retryDelay: input.retryDelay
      }
    ).then((result) => {
      const applied = entry.activeRequestId === requestId;
      if (applied) {
        const finishedAt = Date.now();
        const doneRequestLog = {
          ...startRequestLog,
          attempt: result.attempt,
          endedAt: finishedAt
        };
        this.setQueryState(
          entry,
          {
            ...entry.state,
            status: "success",
            isFetching: false,
            error: null,
            data: result.normalized.data,
            lastRequest: doneRequestLog,
            lastResponse: result.response,
            updatedAt: finishedAt
          },
          "query_updated"
        );
      }
      return {
        ...result.normalized,
        __applied: applied
      };
    }).catch((error) => {
      const wrapped = typeof error === "object" && error !== null ? error : void 0;
      const normalizedError = wrapped?.__athenaNormalizedError ? wrapped.__athenaNormalizedError : normalizeAthenaError(error);
      const status = typeof wrapped?.__athenaStatus === "number" ? wrapped.__athenaStatus : normalizedError.status ?? 500;
      const raw = wrapped?.__athenaRaw ?? normalizedError.raw ?? null;
      const response = wrapped?.__athenaResponse ?? raw;
      const applied = entry.activeRequestId === requestId;
      if (applied) {
        const finishedAt = Date.now();
        const doneRequestLog = {
          ...startRequestLog,
          endedAt: finishedAt,
          attempt: entry.state.lastRequest?.requestId === requestId ? entry.state.lastRequest.attempt : startRequestLog.attempt
        };
        this.setQueryState(
          entry,
          {
            ...entry.state,
            status: "error",
            isFetching: false,
            error: normalizedError,
            lastRequest: doneRequestLog,
            lastResponse: response,
            updatedAt: finishedAt
          },
          "query_updated"
        );
      }
      return {
        data: void 0,
        error: normalizedError,
        status,
        raw,
        __applied: applied
      };
    }).finally(() => {
      const inflight = this.inflightQueries.get(input.queryKeyToken);
      if (inflight === executionPromise) {
        this.inflightQueries.delete(input.queryKeyToken);
      }
    });
    this.inflightQueries.set(input.queryKeyToken, executionPromise);
    return executionPromise;
  }
  async executeMutation(input) {
    const entry = this.ensureMutationEntry(input.mutationKeyToken);
    const requestId = ++this.requestCounter;
    entry.activeRequestId = requestId;
    const startRequestLog = {
      requestId,
      mutationKey: input.mutationKey,
      mutationKeyToken: input.mutationKeyToken,
      attempt: 1,
      startedAt: Date.now(),
      variables: input.variables
    };
    this.setMutationState(
      entry,
      {
        ...entry.state,
        status: "loading",
        isLoading: true,
        error: null,
        lastVariables: input.variables,
        lastRequest: startRequestLog
      },
      "mutation_updated"
    );
    try {
      const result = await runWithRetry(
        async (attempt) => {
          const attemptRequestLog = {
            ...startRequestLog,
            attempt
          };
          if (entry.activeRequestId === requestId) {
            this.setMutationState(
              entry,
              {
                ...entry.state,
                lastRequest: attemptRequestLog,
                isLoading: true
              },
              "mutation_updated"
            );
          }
          const rawResult = await input.mutationFn(input.variables);
          const normalized = normalizeAthenaResult(rawResult, input.select);
          if (normalized.error) {
            throw {
              __athenaNormalizedError: normalized.error,
              __athenaStatus: normalized.status,
              __athenaRaw: normalized.raw,
              __athenaResponse: rawResult
            };
          }
          return {
            normalized,
            response: rawResult,
            attempt
          };
        },
        {
          retry: input.retry,
          retryDelay: input.retryDelay
        }
      );
      if (entry.activeRequestId === requestId) {
        const finishedAt = Date.now();
        const doneRequestLog = {
          ...startRequestLog,
          attempt: result.attempt,
          endedAt: finishedAt
        };
        this.setMutationState(
          entry,
          {
            ...entry.state,
            status: "success",
            isLoading: false,
            data: result.normalized.data,
            error: null,
            lastVariables: input.variables,
            lastRequest: doneRequestLog,
            lastResponse: result.response,
            updatedAt: finishedAt
          },
          "mutation_updated"
        );
      }
      return result.normalized;
    } catch (error) {
      const wrapped = typeof error === "object" && error !== null ? error : void 0;
      const normalizedError = wrapped?.__athenaNormalizedError ? wrapped.__athenaNormalizedError : normalizeAthenaError(error);
      const status = typeof wrapped?.__athenaStatus === "number" ? wrapped.__athenaStatus : normalizedError.status ?? 500;
      const raw = wrapped?.__athenaRaw ?? normalizedError.raw ?? null;
      const response = wrapped?.__athenaResponse ?? raw;
      if (entry.activeRequestId === requestId) {
        const finishedAt = Date.now();
        const doneRequestLog = {
          ...startRequestLog,
          endedAt: finishedAt,
          attempt: entry.state.lastRequest?.requestId === requestId ? entry.state.lastRequest.attempt : startRequestLog.attempt
        };
        this.setMutationState(
          entry,
          {
            ...entry.state,
            status: "error",
            isLoading: false,
            error: normalizedError,
            lastVariables: input.variables,
            lastRequest: doneRequestLog,
            lastResponse: response,
            updatedAt: finishedAt
          },
          "mutation_updated"
        );
      }
      return {
        data: void 0,
        error: normalizedError,
        status,
        raw
      };
    }
  }
  ensureQueryEntry(key) {
    let entry = this.queryEntries.get(key);
    if (entry) return entry;
    entry = {
      key,
      state: createInitialQueryState(),
      listeners: /* @__PURE__ */ new Set(),
      activeRequestId: 0
    };
    this.queryEntries.set(key, entry);
    return entry;
  }
  ensureMutationEntry(key) {
    let entry = this.mutationEntries.get(key);
    if (entry) return entry;
    entry = {
      key,
      state: createInitialMutationState(),
      listeners: /* @__PURE__ */ new Set(),
      activeRequestId: 0
    };
    this.mutationEntries.set(key, entry);
    return entry;
  }
  scheduleQueryGc(entry) {
    const gcTime = shouldUseMemoryCache(this.config) ? Math.max(0, this.config.cache?.gcTime ?? 3e5) : Math.max(0, this.config.cache?.gcTime ?? 0);
    entry.gcTimer = setTimeout(() => {
      const current = this.queryEntries.get(entry.key);
      if (!current || current.listeners.size > 0) return;
      this.queryEntries.delete(entry.key);
      this.inflightQueries.delete(entry.key);
      this.emitEvent({
        type: "query_gc",
        key: entry.key,
        state: current.state,
        timestamp: Date.now()
      });
    }, gcTime);
  }
  scheduleMutationGc(entry) {
    const gcTime = shouldUseMemoryCache(this.config) ? Math.max(0, this.config.cache?.gcTime ?? 3e5) : Math.max(0, this.config.cache?.gcTime ?? 0);
    entry.gcTimer = setTimeout(() => {
      const current = this.mutationEntries.get(entry.key);
      if (!current || current.listeners.size > 0) return;
      this.mutationEntries.delete(entry.key);
    }, gcTime);
  }
  setQueryState(entry, state, eventType) {
    entry.state = state;
    for (const listener of entry.listeners) {
      listener();
    }
    this.emitEvent({
      type: eventType,
      key: entry.key,
      state,
      timestamp: Date.now()
    });
  }
  setMutationState(entry, state, eventType) {
    entry.state = state;
    for (const listener of entry.listeners) {
      listener();
    }
    this.emitEvent({
      type: eventType,
      key: entry.key,
      state,
      timestamp: Date.now()
    });
  }
  emitEvent(event) {
    for (const listener of this.eventSubscribers) {
      listener(event);
    }
    for (const adapter of this.adapters) {
      adapter.onEvent?.(event);
      if (event.type === "query_updated" || event.type === "query_reset" || event.type === "query_gc") {
        adapter.onQueryUpdated?.(event);
      }
      if (event.type === "mutation_updated" || event.type === "mutation_reset") {
        adapter.onMutationUpdated?.(event);
      }
    }
  }
};
function createAthenaQueryClient(config) {
  return new AthenaQueryClient(config);
}
function attachStateAdapter(client, adapter) {
  return client.attachAdapter(adapter);
}
var AthenaQueryClientContext = createContext(null);
function AthenaQueryClientProvider(props) {
  const memoizedClient = useMemo(() => {
    if (props.client) {
      return props.client;
    }
    return createAthenaQueryClient(props.config);
  }, [props.client, props.config]);
  return createElement(
    AthenaQueryClientContext.Provider,
    { value: memoizedClient },
    props.children
  );
}
function useAthenaQueryClient() {
  const client = useContext(AthenaQueryClientContext);
  if (!client) {
    throw new Error(
      "No AthenaQueryClient found. Wrap your component tree with AthenaQueryClientProvider."
    );
  }
  return client;
}
function getBrowserTarget() {
  const maybeGlobal = globalThis;
  const hasListeners = (value) => Boolean(value) && typeof value === "object" && typeof value.addEventListener === "function" && typeof value.removeEventListener === "function";
  if (hasListeners(maybeGlobal.window)) {
    return maybeGlobal.window;
  }
  if (hasListeners(maybeGlobal)) {
    return maybeGlobal;
  }
  return null;
}
function useQuery(options) {
  const client = useAthenaQueryClient();
  const queryKeyRef = useRef(options.queryKey);
  queryKeyRef.current = options.queryKey;
  const queryFnRef = useRef(options.queryFn);
  queryFnRef.current = options.queryFn;
  const selectRef = useRef(options.select);
  selectRef.current = options.select;
  const onSuccessRef = useRef(options.onSuccess);
  onSuccessRef.current = options.onSuccess;
  const onErrorRef = useRef(options.onError);
  onErrorRef.current = options.onError;
  const onSettledRef = useRef(options.onSettled);
  onSettledRef.current = options.onSettled;
  const enabledRef = useRef(options.enabled ?? true);
  enabledRef.current = options.enabled ?? true;
  const retryRef = useRef(options.retry);
  retryRef.current = options.retry;
  const retryDelayRef = useRef(options.retryDelay);
  retryDelayRef.current = options.retryDelay;
  const initialDataRef = useRef(options.initialData);
  initialDataRef.current = options.initialData;
  const refetchOnMountRef = useRef(options.refetchOnMount);
  refetchOnMountRef.current = options.refetchOnMount;
  const refetchOnWindowFocusRef = useRef(options.refetchOnWindowFocus);
  refetchOnWindowFocusRef.current = options.refetchOnWindowFocus;
  const refetchOnReconnectRef = useRef(options.refetchOnReconnect);
  refetchOnReconnectRef.current = options.refetchOnReconnect;
  const queryKeyToken = useMemo(
    () => client.getQueryKeyToken(options.queryKey),
    [client, options.queryKey]
  );
  const activeQueryKeyTokenRef = useRef(queryKeyToken);
  activeQueryKeyTokenRef.current = queryKeyToken;
  const subscribe = useCallback(
    (listener) => client.subscribeQuery(queryKeyToken, listener),
    [client, queryKeyToken]
  );
  const getSnapshot = useCallback(
    () => client.getQueryState(queryKeyToken),
    [client, queryKeyToken]
  );
  const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
  const effectiveSnapshot = useMemo(() => {
    if (snapshot.status === "idle" && snapshot.data === void 0 && initialDataRef.current !== void 0) {
      return {
        ...snapshot,
        status: "success",
        data: initialDataRef.current,
        error: null
      };
    }
    return snapshot;
  }, [snapshot]);
  const runQuery = useCallback(
    async (force = false) => {
      const result = await client.executeQuery({
        queryKey: queryKeyRef.current,
        queryKeyToken,
        queryFn: () => queryFnRef.current(),
        select: selectRef.current,
        retry: retryRef.current ?? client.defaultQueryOptions.retry ?? 0,
        retryDelay: retryDelayRef.current ?? client.defaultQueryOptions.retryDelay,
        dedupe: true,
        force
      });
      const internalResult = result;
      if (activeQueryKeyTokenRef.current !== queryKeyToken || internalResult.__applied === false) {
        return result;
      }
      if (result.error) {
        onErrorRef.current?.(result.error);
        onSettledRef.current?.(result.data, result.error);
        return result;
      }
      onSuccessRef.current?.(result.data);
      onSettledRef.current?.(result.data, null);
      return result;
    },
    [client, queryKeyToken]
  );
  const lastAutoKeyRef = useRef(null);
  useEffect(() => {
    const refetchOnMount = refetchOnMountRef.current ?? client.defaultQueryOptions.refetchOnMount ?? true;
    const isFirstRenderForKey = lastAutoKeyRef.current !== queryKeyToken;
    lastAutoKeyRef.current = queryKeyToken;
    if (!enabledRef.current) {
      return;
    }
    const state = client.getQueryState(queryKeyToken);
    const shouldFetch = state.status === "idle" || isFirstRenderForKey && refetchOnMount;
    if (shouldFetch) {
      void runQuery(false);
    }
  }, [client, queryKeyToken, runQuery]);
  useEffect(() => {
    const browser = getBrowserTarget();
    if (!browser || !enabledRef.current) {
      return void 0;
    }
    const refetchOnWindowFocus = refetchOnWindowFocusRef.current ?? client.defaultQueryOptions.refetchOnWindowFocus ?? false;
    if (!refetchOnWindowFocus) {
      return void 0;
    }
    const onFocus = () => {
      if (!enabledRef.current) return;
      void runQuery(true);
    };
    browser.addEventListener("focus", onFocus);
    return () => {
      browser.removeEventListener("focus", onFocus);
    };
  }, [client, runQuery]);
  useEffect(() => {
    const browser = getBrowserTarget();
    if (!browser || !enabledRef.current) {
      return void 0;
    }
    const refetchOnReconnect = refetchOnReconnectRef.current ?? client.defaultQueryOptions.refetchOnReconnect ?? false;
    if (!refetchOnReconnect) {
      return void 0;
    }
    const onReconnect = () => {
      if (!enabledRef.current) return;
      void runQuery(true);
    };
    browser.addEventListener("online", onReconnect);
    return () => {
      browser.removeEventListener("online", onReconnect);
    };
  }, [client, runQuery]);
  const refetch = useCallback(() => runQuery(true), [runQuery]);
  const reset = useCallback(() => {
    client.resetQuery(queryKeyRef.current);
  }, [client]);
  return {
    data: effectiveSnapshot.data,
    error: effectiveSnapshot.error,
    isLoading: effectiveSnapshot.status === "loading" && effectiveSnapshot.data === void 0,
    isFetching: effectiveSnapshot.isFetching,
    isSuccess: effectiveSnapshot.status === "success",
    isError: effectiveSnapshot.status === "error",
    status: effectiveSnapshot.status,
    refetch,
    reset,
    lastResponse: effectiveSnapshot.lastResponse,
    lastRequest: effectiveSnapshot.lastRequest
  };
}
function useMutation(options) {
  const client = useAthenaQueryClient();
  const mutationKeyRef = useRef(options.mutationKey);
  mutationKeyRef.current = options.mutationKey;
  const mutationFnRef = useRef(options.mutationFn);
  mutationFnRef.current = options.mutationFn;
  const selectRef = useRef(options.select);
  selectRef.current = options.select;
  const retryRef = useRef(options.retry);
  retryRef.current = options.retry;
  const retryDelayRef = useRef(options.retryDelay);
  retryDelayRef.current = options.retryDelay;
  const onMutateRef = useRef(options.onMutate);
  onMutateRef.current = options.onMutate;
  const onSuccessRef = useRef(options.onSuccess);
  onSuccessRef.current = options.onSuccess;
  const onErrorRef = useRef(options.onError);
  onErrorRef.current = options.onError;
  const onSettledRef = useRef(options.onSettled);
  onSettledRef.current = options.onSettled;
  const mutationKeyToken = useMemo(
    () => client.getMutationKeyToken(options.mutationKey),
    [client, options.mutationKey]
  );
  const subscribe = useCallback(
    (listener) => client.subscribeMutation(mutationKeyToken, listener),
    [client, mutationKeyToken]
  );
  const getSnapshot = useCallback(
    () => client.getMutationState(mutationKeyToken),
    [client, mutationKeyToken]
  );
  const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
  const mutateAsync = useCallback(
    async (variables) => {
      await onMutateRef.current?.(variables);
      const result = await client.executeMutation({
        mutationKey: mutationKeyRef.current,
        mutationKeyToken,
        variables,
        mutationFn: (currentVariables) => mutationFnRef.current(currentVariables),
        select: selectRef.current,
        retry: retryRef.current ?? client.defaultMutationOptions.retry ?? 0,
        retryDelay: retryDelayRef.current ?? client.defaultMutationOptions.retryDelay
      });
      if (result.error) {
        onErrorRef.current?.(result.error, variables);
        onSettledRef.current?.(result.data, result.error, variables);
        throw result.error;
      }
      const data = result.data;
      onSuccessRef.current?.(data, variables);
      onSettledRef.current?.(data, null, variables);
      return data;
    },
    [client, mutationKeyToken]
  );
  const mutate = useCallback(
    (variables) => {
      void mutateAsync(variables).catch(() => void 0);
    },
    [mutateAsync]
  );
  const reset = useCallback(() => {
    client.resetMutation(mutationKeyRef.current);
  }, [client]);
  return {
    mutate,
    mutateAsync,
    data: snapshot.data,
    error: snapshot.error,
    isIdle: snapshot.status === "idle",
    isLoading: snapshot.status === "loading",
    isSuccess: snapshot.status === "success",
    isError: snapshot.status === "error",
    status: snapshot.status,
    reset,
    lastResponse: snapshot.lastResponse,
    lastVariables: snapshot.lastVariables,
    lastRequest: snapshot.lastRequest
  };
}
function resolveGetSession(authClient) {
  if ("getSession" in authClient && typeof authClient.getSession === "function") {
    return authClient.getSession;
  }
  if ("auth" in authClient && authClient.auth && typeof authClient.auth.getSession === "function") {
    return authClient.auth.getSession;
  }
  throw new Error("useSession requires an auth-capable client (createClient(...).auth or createAuthClient(...))");
}
function useSession(authClient, options = {}) {
  const enabled = options.enabled ?? true;
  const refetchOnMount = options.refetchOnMount ?? true;
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [isPending, setIsPending] = useState(enabled);
  const [isRefetching, setIsRefetching] = useState(false);
  const requestIdRef = useRef(0);
  const mountedRef = useRef(true);
  const dataRef = useRef(null);
  const getSession = resolveGetSession(
    authClient
  );
  useEffect(() => {
    dataRef.current = data;
  }, [data]);
  const toFallbackErrorDetails = (code, message, status) => ({
    code,
    message,
    status
  });
  const runFetch = useCallback(async () => {
    const requestId = ++requestIdRef.current;
    const hasData = dataRef.current !== null;
    if (hasData) {
      setIsRefetching(true);
    } else {
      setIsPending(true);
    }
    try {
      const result = await getSession(options.fetchInput, options.callOptions);
      if (!mountedRef.current || requestId !== requestIdRef.current) {
        return null;
      }
      if (result.ok) {
        setData(result.data ?? null);
        setError(null);
        return result.data ?? null;
      }
      setError(
        result.errorDetails ?? toFallbackErrorDetails(
          "UNKNOWN_ERROR",
          result.error ?? "Failed to fetch session",
          result.status
        )
      );
      return null;
    } catch (requestError) {
      if (!mountedRef.current || requestId !== requestIdRef.current) {
        return null;
      }
      const message = requestError instanceof Error ? requestError.message : "Failed to fetch session";
      setError(toFallbackErrorDetails("NETWORK_ERROR", message, 0));
      return null;
    } finally {
      if (mountedRef.current && requestId === requestIdRef.current) {
        setIsPending(false);
        setIsRefetching(false);
      }
    }
  }, [getSession, options.callOptions, options.fetchInput]);
  useEffect(() => {
    mountedRef.current = true;
    if (enabled && refetchOnMount) {
      void runFetch();
    } else {
      setIsPending(false);
    }
    return () => {
      mountedRef.current = false;
    };
  }, [enabled, refetchOnMount, runFetch]);
  const refetch = useCallback(async () => {
    return await runFetch();
  }, [runFetch]);
  return {
    data,
    error,
    isPending,
    isRefetching,
    refetch
  };
}

// src/schema/model-form.ts
function resolveNullishValue(mode) {
  if (mode === "undefined") return void 0;
  if (mode === "null") return null;
  return "";
}
function isRecord3(value) {
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function isNullableColumn(model, key) {
  const nullable = model.meta.nullable;
  return nullable?.[key] === true;
}
function toModelFormDefaults(model, values, options) {
  const source = values;
  if (!isRecord3(source)) {
    return {};
  }
  const mode = options?.nullishMode ?? "empty-string";
  const nullishValue = resolveNullishValue(mode);
  const result = {};
  for (const [key, value] of Object.entries(source)) {
    if (value === null && isNullableColumn(model, key)) {
      result[key] = nullishValue;
      continue;
    }
    result[key] = value;
  }
  return result;
}
function toModelPayload(model, formValues, options) {
  const emptyStringAsNull = options?.emptyStringAsNull ?? true;
  const stripUndefined = options?.stripUndefined ?? true;
  const result = {};
  for (const [key, rawValue] of Object.entries(formValues)) {
    if (rawValue === void 0 && stripUndefined) {
      continue;
    }
    if (emptyStringAsNull && rawValue === "" && isNullableColumn(model, key)) {
      result[key] = null;
      continue;
    }
    result[key] = rawValue;
  }
  return result;
}
function createModelFormAdapter(model) {
  return {
    model,
    toDefaults(values, options) {
      return toModelFormDefaults(model, values, options);
    },
    toInsert(values, options) {
      return toModelPayload(model, values, options);
    },
    toUpdate(values, options) {
      return toModelPayload(model, values, options);
    }
  };
}

export { AthenaGatewayError, AthenaQueryClient, AthenaQueryClientProvider, attachStateAdapter, createAthenaQueryClient, createModelFormAdapter, isAthenaGatewayError, toModelFormDefaults, toModelPayload, useAthenaGateway, useAthenaQueryClient, useMutation, useQuery, useSession };
//# sourceMappingURL=react.js.map
//# sourceMappingURL=react.js.map