import {
  QueryErrorResetBoundaryContext,
  QueryObserver,
  React,
  ServerQueryContext,
  createValue,
  useBaseQuery,
  useContext,
  useQuery,
  useQueryErrorResetBoundary
} from "../chunk.ZZDLWAFA.js";
import "../chunk.BXLYIO5Q.js";
import {
  CancelledError,
  MutationCache,
  QueryCache,
  QueryClient,
  QueryClientProvider,
  Subscribable,
  focusManager,
  getDefaultState,
  getNextPageParam,
  getPreviousPageParam,
  hashQueryKey,
  infiniteQueryBehavior,
  isCancelledError,
  isQueryKey,
  noop,
  notifyManager,
  onlineManager,
  parseFilterArgs,
  parseQueryArgs,
  setLogger,
  useQueryClient
} from "../chunk.22IV34P4.js";
import {
  _extends,
  _inheritsLoose
} from "../chunk.JNDOIKBN.js";

// node_modules/react-query/es/core/utils.js
function difference(array1, array2) {
  return array1.filter(function(x) {
    return array2.indexOf(x) === -1;
  });
}
function replaceAt(array, index, value) {
  var copy = array.slice(0);
  copy[index] = value;
  return copy;
}
function parseMutationArgs(arg1, arg2, arg3) {
  if (isQueryKey(arg1)) {
    if (typeof arg2 === "function") {
      return _extends({}, arg3, {
        mutationKey: arg1,
        mutationFn: arg2
      });
    }
    return _extends({}, arg2, {
      mutationKey: arg1
    });
  }
  if (typeof arg1 === "function") {
    return _extends({}, arg2, {
      mutationFn: arg1
    });
  }
  return _extends({}, arg1);
}
function isError(value) {
  return value instanceof Error;
}

// node_modules/react-query/es/core/infiniteQueryBehavior.js
function hasNextPage(options, pages) {
  if (options.getNextPageParam && Array.isArray(pages)) {
    var nextPageParam = getNextPageParam(options, pages);
    return typeof nextPageParam !== "undefined" && nextPageParam !== null && nextPageParam !== false;
  }
}
function hasPreviousPage(options, pages) {
  if (options.getPreviousPageParam && Array.isArray(pages)) {
    var previousPageParam = getPreviousPageParam(options, pages);
    return typeof previousPageParam !== "undefined" && previousPageParam !== null && previousPageParam !== false;
  }
}

// node_modules/react-query/es/core/queriesObserver.js
var QueriesObserver = /* @__PURE__ */ function(_Subscribable) {
  _inheritsLoose(QueriesObserver2, _Subscribable);
  function QueriesObserver2(client, queries) {
    var _this;
    _this = _Subscribable.call(this) || this;
    _this.client = client;
    _this.queries = [];
    _this.result = [];
    _this.observers = [];
    _this.observersMap = {};
    if (queries) {
      _this.setQueries(queries);
    }
    return _this;
  }
  var _proto = QueriesObserver2.prototype;
  _proto.onSubscribe = function onSubscribe() {
    var _this2 = this;
    if (this.listeners.length === 1) {
      this.observers.forEach(function(observer) {
        observer.subscribe(function(result) {
          _this2.onUpdate(observer, result);
        });
      });
    }
  };
  _proto.onUnsubscribe = function onUnsubscribe() {
    if (!this.listeners.length) {
      this.destroy();
    }
  };
  _proto.destroy = function destroy() {
    this.listeners = [];
    this.observers.forEach(function(observer) {
      observer.destroy();
    });
  };
  _proto.setQueries = function setQueries(queries, notifyOptions) {
    this.queries = queries;
    this.updateObservers(notifyOptions);
  };
  _proto.getCurrentResult = function getCurrentResult() {
    return this.result;
  };
  _proto.getOptimisticResult = function getOptimisticResult(queries) {
    var _this3 = this;
    return queries.map(function(options) {
      var defaultedOptions = _this3.client.defaultQueryObserverOptions(options);
      return _this3.getObserver(defaultedOptions).getOptimisticResult(defaultedOptions);
    });
  };
  _proto.getObserver = function getObserver(options) {
    var defaultedOptions = this.client.defaultQueryObserverOptions(options);
    return this.observersMap[defaultedOptions.queryHash] || new QueryObserver(this.client, defaultedOptions);
  };
  _proto.updateObservers = function updateObservers(notifyOptions) {
    var _this4 = this;
    notifyManager.batch(function() {
      var hasIndexChange = false;
      var prevObservers = _this4.observers;
      var prevOberversMap = _this4.observersMap;
      var newResult = [];
      var newObservers = [];
      var newObserversMap = {};
      _this4.queries.forEach(function(options, i) {
        var defaultedOptions = _this4.client.defaultQueryObserverOptions(options);
        var queryHash = defaultedOptions.queryHash;
        var observer = _this4.getObserver(defaultedOptions);
        if (prevOberversMap[queryHash]) {
          observer.setOptions(defaultedOptions, notifyOptions);
        }
        if (observer !== prevObservers[i]) {
          hasIndexChange = true;
        }
        newObservers.push(observer);
        newResult.push(observer.getCurrentResult());
        newObserversMap[queryHash] = observer;
      });
      if (prevObservers.length === newObservers.length && !hasIndexChange) {
        return;
      }
      _this4.observers = newObservers;
      _this4.observersMap = newObserversMap;
      _this4.result = newResult;
      if (!_this4.hasListeners()) {
        return;
      }
      difference(prevObservers, newObservers).forEach(function(observer) {
        observer.destroy();
      });
      difference(newObservers, prevObservers).forEach(function(observer) {
        observer.subscribe(function(result) {
          _this4.onUpdate(observer, result);
        });
      });
      _this4.notify();
    });
  };
  _proto.onUpdate = function onUpdate(observer, result) {
    var index = this.observers.indexOf(observer);
    if (index !== -1) {
      this.result = replaceAt(this.result, index, result);
      this.notify();
    }
  };
  _proto.notify = function notify() {
    var _this5 = this;
    notifyManager.batch(function() {
      _this5.listeners.forEach(function(listener) {
        listener(_this5.result);
      });
    });
  };
  return QueriesObserver2;
}(Subscribable);

// node_modules/react-query/es/core/infiniteQueryObserver.js
var InfiniteQueryObserver = /* @__PURE__ */ function(_QueryObserver) {
  _inheritsLoose(InfiniteQueryObserver2, _QueryObserver);
  function InfiniteQueryObserver2(client, options) {
    return _QueryObserver.call(this, client, options) || this;
  }
  var _proto = InfiniteQueryObserver2.prototype;
  _proto.bindMethods = function bindMethods() {
    _QueryObserver.prototype.bindMethods.call(this);
    this.fetchNextPage = this.fetchNextPage.bind(this);
    this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
  };
  _proto.setOptions = function setOptions(options) {
    _QueryObserver.prototype.setOptions.call(this, _extends({}, options, {
      behavior: infiniteQueryBehavior()
    }));
  };
  _proto.fetchNextPage = function fetchNextPage(options) {
    return this.fetch({
      cancelRefetch: true,
      throwOnError: options == null ? void 0 : options.throwOnError,
      meta: {
        fetchMore: {
          direction: "forward",
          pageParam: options == null ? void 0 : options.pageParam
        }
      }
    });
  };
  _proto.fetchPreviousPage = function fetchPreviousPage(options) {
    return this.fetch({
      cancelRefetch: true,
      throwOnError: options == null ? void 0 : options.throwOnError,
      meta: {
        fetchMore: {
          direction: "backward",
          pageParam: options == null ? void 0 : options.pageParam
        }
      }
    });
  };
  _proto.createResult = function createResult(query, options) {
    var _state$data, _state$data2, _state$fetchMeta, _state$fetchMeta$fetc, _state$fetchMeta2, _state$fetchMeta2$fet;
    var state = query.state;
    var result = _QueryObserver.prototype.createResult.call(this, query, options);
    return _extends({}, result, {
      fetchNextPage: this.fetchNextPage,
      fetchPreviousPage: this.fetchPreviousPage,
      hasNextPage: hasNextPage(options, (_state$data = state.data) == null ? void 0 : _state$data.pages),
      hasPreviousPage: hasPreviousPage(options, (_state$data2 = state.data) == null ? void 0 : _state$data2.pages),
      isFetchingNextPage: state.isFetching && ((_state$fetchMeta = state.fetchMeta) == null ? void 0 : (_state$fetchMeta$fetc = _state$fetchMeta.fetchMore) == null ? void 0 : _state$fetchMeta$fetc.direction) === "forward",
      isFetchingPreviousPage: state.isFetching && ((_state$fetchMeta2 = state.fetchMeta) == null ? void 0 : (_state$fetchMeta2$fet = _state$fetchMeta2.fetchMore) == null ? void 0 : _state$fetchMeta2$fet.direction) === "backward"
    });
  };
  return InfiniteQueryObserver2;
}(QueryObserver);

// node_modules/react-query/es/core/mutationObserver.js
var MutationObserver = /* @__PURE__ */ function(_Subscribable) {
  _inheritsLoose(MutationObserver2, _Subscribable);
  function MutationObserver2(client, options) {
    var _this;
    _this = _Subscribable.call(this) || this;
    _this.client = client;
    _this.setOptions(options);
    _this.bindMethods();
    _this.updateResult();
    return _this;
  }
  var _proto = MutationObserver2.prototype;
  _proto.bindMethods = function bindMethods() {
    this.mutate = this.mutate.bind(this);
    this.reset = this.reset.bind(this);
  };
  _proto.setOptions = function setOptions(options) {
    this.options = this.client.defaultMutationOptions(options);
  };
  _proto.onUnsubscribe = function onUnsubscribe() {
    if (!this.listeners.length) {
      var _this$currentMutation;
      (_this$currentMutation = this.currentMutation) == null ? void 0 : _this$currentMutation.removeObserver(this);
    }
  };
  _proto.onMutationUpdate = function onMutationUpdate(action) {
    this.updateResult();
    var notifyOptions = {
      listeners: true
    };
    if (action.type === "success") {
      notifyOptions.onSuccess = true;
    } else if (action.type === "error") {
      notifyOptions.onError = true;
    }
    this.notify(notifyOptions);
  };
  _proto.getCurrentResult = function getCurrentResult() {
    return this.currentResult;
  };
  _proto.reset = function reset() {
    this.currentMutation = void 0;
    this.updateResult();
    this.notify({
      listeners: true
    });
  };
  _proto.mutate = function mutate(variables, options) {
    this.mutateOptions = options;
    if (this.currentMutation) {
      this.currentMutation.removeObserver(this);
    }
    this.currentMutation = this.client.getMutationCache().build(this.client, _extends({}, this.options, {
      variables: typeof variables !== "undefined" ? variables : this.options.variables
    }));
    this.currentMutation.addObserver(this);
    return this.currentMutation.execute();
  };
  _proto.updateResult = function updateResult() {
    var state = this.currentMutation ? this.currentMutation.state : getDefaultState();
    this.currentResult = _extends({}, state, {
      isLoading: state.status === "loading",
      isSuccess: state.status === "success",
      isError: state.status === "error",
      isIdle: state.status === "idle",
      mutate: this.mutate,
      reset: this.reset
    });
  };
  _proto.notify = function notify(options) {
    var _this2 = this;
    notifyManager.batch(function() {
      if (_this2.mutateOptions) {
        if (options.onSuccess) {
          _this2.mutateOptions.onSuccess == null ? void 0 : _this2.mutateOptions.onSuccess(_this2.currentResult.data, _this2.currentResult.variables, _this2.currentResult.context);
          _this2.mutateOptions.onSettled == null ? void 0 : _this2.mutateOptions.onSettled(_this2.currentResult.data, null, _this2.currentResult.variables, _this2.currentResult.context);
        } else if (options.onError) {
          _this2.mutateOptions.onError == null ? void 0 : _this2.mutateOptions.onError(_this2.currentResult.error, _this2.currentResult.variables, _this2.currentResult.context);
          _this2.mutateOptions.onSettled == null ? void 0 : _this2.mutateOptions.onSettled(void 0, _this2.currentResult.error, _this2.currentResult.variables, _this2.currentResult.context);
        }
      }
      if (options.listeners) {
        _this2.listeners.forEach(function(listener) {
          listener(_this2.currentResult);
        });
      }
    });
  };
  return MutationObserver2;
}(Subscribable);

// node_modules/react-query/es/react/QueryErrorResetBoundary.js
var QueryErrorResetBoundary = function QueryErrorResetBoundary2(_ref) {
  var children = _ref.children;
  var value = React.useMemo(function() {
    return createValue();
  }, []);
  return /* @__PURE__ */ React.createElement(QueryErrorResetBoundaryContext.Provider, {
    value
  }, typeof children === "function" ? children(value) : children);
};

// node_modules/react-query/es/react/useIsFetching.js
import React2 from "react";
function useIsFetching(arg1, arg2) {
  var mountedRef = React2.useRef(false);
  var queryClient = useQueryClient();
  var _parseFilterArgs = parseFilterArgs(arg1, arg2), filters = _parseFilterArgs[0];
  var _React$useState = React2.useState(queryClient.isFetching(filters)), isFetching = _React$useState[0], setIsFetching = _React$useState[1];
  var filtersRef = React2.useRef(filters);
  filtersRef.current = filters;
  var isFetchingRef = React2.useRef(isFetching);
  isFetchingRef.current = isFetching;
  React2.useEffect(function() {
    mountedRef.current = true;
    var unsubscribe = queryClient.getQueryCache().subscribe(notifyManager.batchCalls(function() {
      if (mountedRef.current) {
        var newIsFetching = queryClient.isFetching(filtersRef.current);
        if (isFetchingRef.current !== newIsFetching) {
          setIsFetching(newIsFetching);
        }
      }
    }));
    return function() {
      mountedRef.current = false;
      unsubscribe();
    };
  }, [queryClient]);
  return isFetching;
}

// node_modules/react-query/es/react/useMutation.js
import React3 from "react";
function useMutation(arg1, arg2, arg3) {
  var mountedRef = React3.useRef(false);
  var _React$useState = React3.useState(0), forceUpdate = _React$useState[1];
  var options = parseMutationArgs(arg1, arg2, arg3);
  var queryClient = useQueryClient();
  var obsRef = React3.useRef();
  if (!obsRef.current) {
    obsRef.current = new MutationObserver(queryClient, options);
  } else {
    obsRef.current.setOptions(options);
  }
  var currentResult = obsRef.current.getCurrentResult();
  React3.useEffect(function() {
    mountedRef.current = true;
    var unsubscribe = obsRef.current.subscribe(notifyManager.batchCalls(function() {
      if (mountedRef.current) {
        forceUpdate(function(x) {
          return x + 1;
        });
      }
    }));
    return function() {
      mountedRef.current = false;
      unsubscribe();
    };
  }, []);
  var mutate = React3.useCallback(function(variables, mutateOptions) {
    obsRef.current.mutate(variables, mutateOptions).catch(noop);
  }, []);
  if (currentResult.error && obsRef.current.options.useErrorBoundary) {
    throw currentResult.error;
  }
  return _extends({}, currentResult, {
    mutate,
    mutateAsync: currentResult.mutate
  });
}

// node_modules/react-query/es/react/useQueries.js
import React4 from "react";
function useQueries(queries) {
  var mountedRef = React4.useRef(false);
  var _React$useState = React4.useState(0), forceUpdate = _React$useState[1];
  var queryClient = useQueryClient();
  var defaultedQueries = queries.map(function(options) {
    var defaultedOptions = queryClient.defaultQueryObserverOptions(options);
    defaultedOptions.optimisticResults = true;
    return defaultedOptions;
  });
  var obsRef = React4.useRef();
  if (!obsRef.current) {
    obsRef.current = new QueriesObserver(queryClient, defaultedQueries);
  }
  var result = obsRef.current.getOptimisticResult(defaultedQueries);
  React4.useEffect(function() {
    mountedRef.current = true;
    var unsubscribe = obsRef.current.subscribe(notifyManager.batchCalls(function() {
      if (mountedRef.current) {
        forceUpdate(function(x) {
          return x + 1;
        });
      }
    }));
    return function() {
      mountedRef.current = false;
      unsubscribe();
    };
  }, []);
  React4.useEffect(function() {
    obsRef.current.setQueries(defaultedQueries, {
      listeners: false
    });
  }, [defaultedQueries]);
  return result;
}

// node_modules/react-query/es/react/useInfiniteQuery.js
function useInfiniteQuery(arg1, arg2, arg3) {
  var options = parseQueryArgs(arg1, arg2, arg3);
  return useBaseQuery(options, InfiniteQueryObserver);
}

// src/runtime/functions/browser.ts
function useQueryFunctionBrowser(fn, args, options) {
  return useQuery([fn.name, args], (ctx) => {
    const abortController = new AbortController();
    const resultPromise = invokeViaHttp({functionName: ctx.queryKey[0], args: ctx.queryKey[1]}, abortController.signal);
    return Object.assign(resultPromise, {
      cancel() {
        abortController.abort();
      }
    });
  }, options);
}
function useMutationFunctionBrowser(fn, options = {}) {
  return useMutation((args) => {
    return invokeViaHttp({functionName: fn.name, args});
  }, options);
}
async function invokeViaHttp(batch, signal) {
  const res = await fetch(process.env.NOSTALGIE_RPC_PATH, {
    method: "POST",
    headers: {
      "content-type": "application/json"
    },
    body: JSON.stringify(batch),
    signal
  });
  if (!res.ok) {
    throw new Error(`Request failed`);
  }
  return res.json();
}

// src/invariant.ts
function invariant(value, message) {
  if (!value) {
    throw new Error(`Invariant violation: ${message}`);
  }
}

// src/runtime/functions/server.ts
function useQueryFunctionServer(fn, args, options) {
  const serverQueryExecutor = useContext(ServerQueryContext);
  if (!serverQueryExecutor) {
    throw new Error(`Invariant violation: the useFunction hook must be called within a ServerQueryContext`);
  }
  return serverQueryExecutor.executeQuery(fn, args, Object.assign(Object.create(null), options, {retry: false}));
}
function useMutationFunctionServer(_fn, _options = {}) {
  invariant(true, `The "mutate" method of observers returned by mutation hooks must not be invoked on the server`);
}

// src/runtime/functions/index.ts
function createQueryFunction(fn, factoryOptions) {
  return function useBoundQueryFunction(args, options) {
    if (process.env.NOSTALGIE_BUILD_TARGET === "browser") {
      if (!isFunctionFacade(fn)) {
        throw new Error("Invariant violation: Attempting to invoke a server function not decorated by the Proxy facade");
      }
      return useQueryFunctionBrowser(fn, args, Object.assign({}, factoryOptions, options));
    } else {
      return useQueryFunctionServer(fn, args, Object.assign({}, factoryOptions, options));
    }
  };
}
function useQueryFunction(fn, args, options) {
  if (process.env.NOSTALGIE_BUILD_TARGET === "browser") {
    if (!isFunctionFacade(fn)) {
      throw new Error("Invariant violation: Attempting to invoke a server function not decorated by the Proxy facade");
    }
    return useQueryFunctionBrowser(fn, args, options);
  } else {
    return useQueryFunctionServer(fn, args, options);
  }
}
function createMutationFunction(fn, factoryOptions) {
  return function useBoundMutationFunction(options) {
    if (process.env.NOSTALGIE_BUILD_TARGET === "browser") {
      if (!isFunctionFacade(fn)) {
        throw new Error("Invariant violation: Attempting to invoke a server function not decorated by the Proxy facade");
      }
      return useMutationFunctionBrowser(fn, Object.assign({}, factoryOptions, options));
    } else {
      return useMutationFunctionServer(fn, Object.assign({}, factoryOptions, options));
    }
  };
}
function isFunctionFacade(fn) {
  return fn && typeof fn === "object" && fn.name && typeof fn.name === "string";
}
export {
  CancelledError,
  InfiniteQueryObserver,
  MutationCache,
  MutationObserver,
  QueriesObserver,
  QueryCache,
  QueryClient,
  QueryClientProvider,
  QueryErrorResetBoundary,
  QueryObserver,
  createMutationFunction,
  createQueryFunction,
  focusManager,
  hashQueryKey,
  isCancelledError,
  isError,
  notifyManager,
  onlineManager,
  setLogger,
  useInfiniteQuery,
  useIsFetching,
  useMutation,
  useQueries,
  useQuery,
  useQueryClient,
  useQueryErrorResetBoundary,
  useQueryFunction
};
