// src/index.ts
import { router as Router } from "@inertiajs/core";

// src/createInertiaApp.ts
import { router as router2, setupProgress } from "@inertiajs/core";
import { createElement as createElement2 } from "react";

// src/App.ts
import { createHeadManager, router } from "@inertiajs/core";
import { createElement, useEffect, useMemo, useState } from "react";

// src/HeadContext.ts
import { createContext } from "react";
var headContext = createContext(void 0);
headContext.displayName = "InertiaHeadContext";
var HeadContext_default = headContext;

// src/PageContext.ts
import { createContext as createContext2 } from "react";
var pageContext = createContext2(void 0);
pageContext.displayName = "InertiaPageContext";
var PageContext_default = pageContext;

// src/App.ts
var currentIsInitialPage = true;
var routerIsInitialized = false;
var swapComponent = async () => {
  currentIsInitialPage = false;
};
function App({
  children,
  initialPage,
  initialComponent,
  resolveComponent,
  titleCallback,
  onHeadUpdate
}) {
  const [current, setCurrent] = useState({
    component: initialComponent || null,
    page: initialPage,
    key: null
  });
  const headManager = useMemo(() => {
    return createHeadManager(
      typeof window === "undefined",
      titleCallback || ((title) => title),
      onHeadUpdate || (() => {
      })
    );
  }, []);
  if (!routerIsInitialized) {
    router.init({
      initialPage,
      resolveComponent,
      swapComponent: async (args) => swapComponent(args)
    });
    routerIsInitialized = true;
  }
  useEffect(() => {
    swapComponent = async ({ component, page, preserveState }) => {
      if (currentIsInitialPage) {
        currentIsInitialPage = false;
        return;
      }
      setCurrent((current2) => ({
        component,
        page,
        key: preserveState ? current2.key : Date.now()
      }));
    };
    router.on("navigate", () => headManager.forceUpdate());
  }, []);
  if (!current.component) {
    return createElement(
      HeadContext_default.Provider,
      { value: headManager },
      createElement(PageContext_default.Provider, { value: current.page }, null)
    );
  }
  const renderChildren = children || (({ Component, props, key }) => {
    const child = createElement(Component, { key, ...props });
    if (typeof Component.layout === "function") {
      return Component.layout(child);
    }
    if (Array.isArray(Component.layout)) {
      return Component.layout.concat(child).reverse().reduce((children2, Layout) => createElement(Layout, { children: children2, ...props }));
    }
    return child;
  });
  return createElement(
    HeadContext_default.Provider,
    { value: headManager },
    createElement(
      PageContext_default.Provider,
      { value: current.page },
      renderChildren({
        Component: current.component,
        key: current.key,
        props: current.page.props
      })
    )
  );
}
App.displayName = "Inertia";

// src/createInertiaApp.ts
async function createInertiaApp({
  id = "app",
  resolve,
  setup,
  title,
  progress = {},
  page,
  render
}) {
  const isServer = typeof window === "undefined";
  const el = isServer ? null : document.getElementById(id);
  const initialPage = page || JSON.parse(el.dataset.page);
  const resolveComponent = (name) => Promise.resolve(resolve(name)).then((module) => module.default || module);
  let head = [];
  const reactApp = await Promise.all([
    resolveComponent(initialPage.component),
    router2.decryptHistory().catch(() => {
    })
  ]).then(([initialComponent]) => {
    return setup({
      // @ts-expect-error
      el,
      App,
      props: {
        initialPage,
        initialComponent,
        resolveComponent,
        titleCallback: title,
        onHeadUpdate: isServer ? (elements) => head = elements : null
      }
    });
  });
  if (!isServer && progress) {
    setupProgress(progress);
  }
  if (isServer) {
    const body = await render(
      createElement2(
        "div",
        {
          id,
          "data-page": JSON.stringify(initialPage)
        },
        // @ts-expect-error
        reactApp
      )
    );
    return { head, body };
  }
}

// src/Deferred.ts
import { useEffect as useEffect2, useMemo as useMemo2, useState as useState2 } from "react";

// src/usePage.ts
import { useContext } from "react";
function usePage() {
  const page = useContext(PageContext_default);
  if (!page) {
    throw new Error("usePage must be used within the Inertia component");
  }
  return page;
}

// src/Deferred.ts
var urlWithoutHash = (url) => {
  url = new URL(url.href);
  url.hash = "";
  return url;
};
var isSameUrlWithoutHash = (url1, url2) => {
  return urlWithoutHash(url1).href === urlWithoutHash(url2).href;
};
var Deferred = ({ children, data, fallback }) => {
  if (!data) {
    throw new Error("`<Deferred>` requires a `data` prop to be a string or array of strings");
  }
  const [loaded, setLoaded] = useState2(false);
  const pageProps = usePage().props;
  const keys = useMemo2(() => Array.isArray(data) ? data : [data], [data]);
  useEffect2(() => {
    const removeListener = router3.on("start", (e) => {
      const isPartialVisit = e.detail.visit.only.length > 0 || e.detail.visit.except.length > 0;
      const isReloadingKey = e.detail.visit.only.find((key) => keys.includes(key));
      if (isSameUrlWithoutHash(e.detail.visit.url, window.location) && (!isPartialVisit || isReloadingKey)) {
        setLoaded(false);
      }
    });
    return () => {
      removeListener();
    };
  }, []);
  useEffect2(() => {
    setLoaded(keys.every((key) => pageProps[key] !== void 0));
  }, [pageProps, keys]);
  if (loaded) {
    return typeof children === "function" ? children() : children;
  }
  return typeof fallback === "function" ? fallback() : fallback;
};
Deferred.displayName = "InertiaDeferred";
var Deferred_default = Deferred;

// src/Form.ts
import {
  formDataToObject,
  mergeDataIntoQueryString,
  resetFormFields
} from "@inertiajs/core";
import { isEqual as isEqual2 } from "lodash-es";
import {
  createElement as createElement3,
  forwardRef,
  useEffect as useEffect5,
  useImperativeHandle,
  useMemo as useMemo4,
  useRef as useRef2,
  useState as useState5
} from "react";

// src/useForm.ts
import {
  router as router5
} from "@inertiajs/core";
import { cloneDeep, get, has, isEqual, set } from "lodash-es";
import { useCallback, useEffect as useEffect4, useLayoutEffect, useMemo as useMemo3, useRef, useState as useState4 } from "react";

// src/useRemember.ts
import { router as router4 } from "@inertiajs/core";
import { useEffect as useEffect3, useState as useState3 } from "react";
function useRemember(initialState, key) {
  const [state, setState] = useState3(() => {
    const restored = router4.restore(key);
    return restored !== void 0 ? restored : initialState;
  });
  useEffect3(() => {
    router4.remember(state, key);
  }, [state, key]);
  return [state, setState];
}

// src/useForm.ts
function useForm(rememberKeyOrInitialValues, maybeInitialValues) {
  const isMounted = useRef(null);
  const rememberKey = typeof rememberKeyOrInitialValues === "string" ? rememberKeyOrInitialValues : null;
  const [defaults, setDefaults] = useState4(
    (typeof rememberKeyOrInitialValues === "string" ? maybeInitialValues : rememberKeyOrInitialValues) || {}
  );
  const cancelToken = useRef(null);
  const recentlySuccessfulTimeoutId = useRef(null);
  const [data, setData] = rememberKey ? useRemember(defaults, `${rememberKey}:data`) : useState4(defaults);
  const [errors, setErrors] = rememberKey ? useRemember({}, `${rememberKey}:errors`) : useState4({});
  const [hasErrors, setHasErrors] = useState4(false);
  const [processing, setProcessing] = useState4(false);
  const [progress, setProgress] = useState4(null);
  const [wasSuccessful, setWasSuccessful] = useState4(false);
  const [recentlySuccessful, setRecentlySuccessful] = useState4(false);
  const transform = useRef((data2) => data2);
  const isDirty = useMemo3(() => !isEqual(data, defaults), [data, defaults]);
  useEffect4(() => {
    isMounted.current = true;
    return () => {
      isMounted.current = false;
    };
  }, []);
  const setDefaultsCalledInOnSuccess = useRef(false);
  const submit = useCallback(
    (...args) => {
      const objectPassed = typeof args[0] === "object";
      const method = objectPassed ? args[0].method : args[0];
      const url = objectPassed ? args[0].url : args[1];
      const options = (objectPassed ? args[1] : args[2]) ?? {};
      setDefaultsCalledInOnSuccess.current = false;
      const _options = {
        ...options,
        onCancelToken: (token) => {
          cancelToken.current = token;
          if (options.onCancelToken) {
            return options.onCancelToken(token);
          }
        },
        onBefore: (visit) => {
          setWasSuccessful(false);
          setRecentlySuccessful(false);
          clearTimeout(recentlySuccessfulTimeoutId.current);
          if (options.onBefore) {
            return options.onBefore(visit);
          }
        },
        onStart: (visit) => {
          setProcessing(true);
          if (options.onStart) {
            return options.onStart(visit);
          }
        },
        onProgress: (event) => {
          setProgress(event);
          if (options.onProgress) {
            return options.onProgress(event);
          }
        },
        onSuccess: async (page) => {
          if (isMounted.current) {
            setProcessing(false);
            setProgress(null);
            setErrors({});
            setHasErrors(false);
            setWasSuccessful(true);
            setRecentlySuccessful(true);
            recentlySuccessfulTimeoutId.current = setTimeout(() => {
              if (isMounted.current) {
                setRecentlySuccessful(false);
              }
            }, 2e3);
          }
          const onSuccess = options.onSuccess ? await options.onSuccess(page) : null;
          if (isMounted.current && !setDefaultsCalledInOnSuccess.current) {
            setData((data2) => {
              setDefaults(cloneDeep(data2));
              return data2;
            });
          }
          return onSuccess;
        },
        onError: (errors2) => {
          if (isMounted.current) {
            setProcessing(false);
            setProgress(null);
            setErrors(errors2);
            setHasErrors(true);
          }
          if (options.onError) {
            return options.onError(errors2);
          }
        },
        onCancel: () => {
          if (isMounted.current) {
            setProcessing(false);
            setProgress(null);
          }
          if (options.onCancel) {
            return options.onCancel();
          }
        },
        onFinish: (visit) => {
          if (isMounted.current) {
            setProcessing(false);
            setProgress(null);
          }
          cancelToken.current = null;
          if (options.onFinish) {
            return options.onFinish(visit);
          }
        }
      };
      if (method === "delete") {
        router5.delete(url, { ..._options, data: transform.current(data) });
      } else {
        router5[method](url, transform.current(data), _options);
      }
    },
    [data, setErrors, transform]
  );
  const setDataFunction = useCallback(
    (keyOrData, maybeValue) => {
      if (typeof keyOrData === "string") {
        setData((data2) => set(cloneDeep(data2), keyOrData, maybeValue));
      } else if (typeof keyOrData === "function") {
        setData((data2) => keyOrData(data2));
      } else {
        setData(keyOrData);
      }
    },
    [setData]
  );
  const [dataAsDefaults, setDataAsDefaults] = useState4(false);
  const setDefaultsFunction = useCallback(
    (fieldOrFields, maybeValue) => {
      setDefaultsCalledInOnSuccess.current = true;
      if (typeof fieldOrFields === "undefined") {
        setDefaults(data);
        setDataAsDefaults(true);
      } else {
        setDefaults((defaults2) => {
          return typeof fieldOrFields === "string" ? set(cloneDeep(defaults2), fieldOrFields, maybeValue) : Object.assign(cloneDeep(defaults2), fieldOrFields);
        });
      }
    },
    [data, setDefaults]
  );
  useLayoutEffect(() => {
    if (!dataAsDefaults) {
      return;
    }
    if (isDirty) {
      setDefaults(data);
    }
    setDataAsDefaults(false);
  }, [dataAsDefaults]);
  const reset = useCallback(
    (...fields) => {
      if (fields.length === 0) {
        setData(defaults);
      } else {
        setData(
          (data2) => fields.filter((key) => has(defaults, key)).reduce(
            (carry, key) => {
              return set(carry, key, get(defaults, key));
            },
            { ...data2 }
          )
        );
      }
    },
    [setData, defaults]
  );
  const setError = useCallback(
    (fieldOrFields, maybeValue) => {
      setErrors((errors2) => {
        const newErrors = {
          ...errors2,
          ...typeof fieldOrFields === "string" ? { [fieldOrFields]: maybeValue } : fieldOrFields
        };
        setHasErrors(Object.keys(newErrors).length > 0);
        return newErrors;
      });
    },
    [setErrors, setHasErrors]
  );
  const clearErrors = useCallback(
    (...fields) => {
      setErrors((errors2) => {
        const newErrors = Object.keys(errors2).reduce(
          (carry, field) => ({
            ...carry,
            ...fields.length > 0 && !fields.includes(field) ? { [field]: errors2[field] } : {}
          }),
          {}
        );
        setHasErrors(Object.keys(newErrors).length > 0);
        return newErrors;
      });
    },
    [setErrors, setHasErrors]
  );
  const resetAndClearErrors = useCallback(
    (...fields) => {
      reset(...fields);
      clearErrors(...fields);
    },
    [reset, clearErrors]
  );
  const createSubmitMethod = (method) => (url, options) => {
    submit(method, url, options);
  };
  const getMethod = useCallback(createSubmitMethod("get"), [submit]);
  const post = useCallback(createSubmitMethod("post"), [submit]);
  const put = useCallback(createSubmitMethod("put"), [submit]);
  const patch = useCallback(createSubmitMethod("patch"), [submit]);
  const deleteMethod = useCallback(createSubmitMethod("delete"), [submit]);
  const cancel = useCallback(() => {
    if (cancelToken.current) {
      cancelToken.current.cancel();
    }
  }, []);
  const transformFunction = useCallback((callback) => {
    transform.current = callback;
  }, []);
  return {
    data,
    setData: setDataFunction,
    isDirty,
    errors,
    hasErrors,
    processing,
    progress,
    wasSuccessful,
    recentlySuccessful,
    transform: transformFunction,
    setDefaults: setDefaultsFunction,
    reset,
    setError,
    clearErrors,
    resetAndClearErrors,
    submit,
    get: getMethod,
    post,
    put,
    patch,
    delete: deleteMethod,
    cancel
  };
}

// src/Form.ts
var noop = () => void 0;
var Form = forwardRef(
  ({
    action = "",
    method = "get",
    headers = {},
    queryStringArrayFormat = "brackets",
    errorBag = null,
    showProgress = true,
    transform = (data) => data,
    options = {},
    onStart = noop,
    onProgress = noop,
    onFinish = noop,
    onBefore = noop,
    onCancel = noop,
    onSuccess = noop,
    onError = noop,
    onCancelToken = noop,
    onSubmitComplete = noop,
    disableWhileProcessing = false,
    resetOnError = false,
    resetOnSuccess = false,
    setDefaultsOnSuccess = false,
    invalidateCacheTags = [],
    children,
    ...props
  }, ref) => {
    const form = useForm({});
    const formElement = useRef2(null);
    const resolvedMethod = useMemo4(() => {
      return typeof action === "object" ? action.method : method.toLowerCase();
    }, [action, method]);
    const [isDirty, setIsDirty] = useState5(false);
    const defaultData = useRef2(new FormData());
    const getFormData = () => new FormData(formElement.current);
    const getData = () => formDataToObject(getFormData());
    const updateDirtyState = (event) => setIsDirty(event.type === "reset" ? false : !isEqual2(getData(), formDataToObject(defaultData.current)));
    useEffect5(() => {
      defaultData.current = getFormData();
      const formEvents = ["input", "change", "reset"];
      formEvents.forEach((e) => formElement.current.addEventListener(e, updateDirtyState));
      return () => formEvents.forEach((e) => formElement.current?.removeEventListener(e, updateDirtyState));
    }, []);
    const reset = (...fields) => {
      resetFormFields(formElement.current, defaultData.current, fields);
    };
    const resetAndClearErrors = (...fields) => {
      form.clearErrors(...fields);
      reset(...fields);
    };
    const maybeReset = (resetOption) => {
      if (!resetOption) {
        return;
      }
      if (resetOption === true) {
        reset();
      } else if (resetOption.length > 0) {
        reset(...resetOption);
      }
    };
    const submit = () => {
      const [url, _data] = mergeDataIntoQueryString(
        resolvedMethod,
        typeof action === "object" ? action.url : action,
        getData(),
        queryStringArrayFormat
      );
      const submitOptions = {
        headers,
        errorBag,
        showProgress,
        invalidateCacheTags,
        onCancelToken,
        onBefore,
        onStart,
        onProgress,
        onFinish,
        onCancel,
        onSuccess: (...args) => {
          onSuccess(...args);
          onSubmitComplete({
            reset,
            defaults
          });
          maybeReset(resetOnSuccess);
          if (setDefaultsOnSuccess === true) {
            defaults();
          }
        },
        onError(...args) {
          onError(...args);
          maybeReset(resetOnError);
        },
        ...options
      };
      form.transform(() => transform(_data));
      form.submit(resolvedMethod, url, submitOptions);
    };
    const defaults = () => {
      defaultData.current = getFormData();
      setIsDirty(false);
    };
    const exposed = () => ({
      errors: form.errors,
      hasErrors: form.hasErrors,
      processing: form.processing,
      progress: form.progress,
      wasSuccessful: form.wasSuccessful,
      recentlySuccessful: form.recentlySuccessful,
      isDirty,
      clearErrors: form.clearErrors,
      resetAndClearErrors,
      setError: form.setError,
      reset,
      submit,
      defaults
    });
    useImperativeHandle(ref, exposed, [form, isDirty, submit]);
    return createElement3(
      "form",
      {
        ...props,
        ref: formElement,
        action: typeof action === "object" ? action.url : action,
        method: resolvedMethod,
        onSubmit: (event) => {
          event.preventDefault();
          submit();
        },
        // Only React 19 supports passing a boolean to the `inert` attribute.
        // To support earlier versions as well, we use the string 'true'.
        // Unfortunately, React 19 treats an empty string as `false`.
        // See: https://github.com/inertiajs/inertia/pull/2536
        inert: disableWhileProcessing && form.processing && "true"
      },
      typeof children === "function" ? children(exposed()) : children
    );
  }
);
Form.displayName = "InertiaForm";
var Form_default = Form;

// src/Head.ts
import { escape } from "lodash-es";
import React, { useContext as useContext2, useEffect as useEffect6, useMemo as useMemo5 } from "react";
var Head = function({ children, title }) {
  const headManager = useContext2(HeadContext_default);
  const provider = useMemo5(() => headManager.createProvider(), [headManager]);
  const isServer = typeof window === "undefined";
  useEffect6(() => {
    provider.reconnect();
    provider.update(renderNodes(children));
    return () => {
      provider.disconnect();
    };
  }, [provider, children, title]);
  function isUnaryTag(node) {
    return [
      "area",
      "base",
      "br",
      "col",
      "embed",
      "hr",
      "img",
      "input",
      "keygen",
      "link",
      "meta",
      "param",
      "source",
      "track",
      "wbr"
    ].indexOf(node.type) > -1;
  }
  function renderTagStart(node) {
    const attrs = Object.keys(node.props).reduce((carry, name) => {
      if (["head-key", "children", "dangerouslySetInnerHTML"].includes(name)) {
        return carry;
      }
      const value = String(node.props[name]);
      if (value === "") {
        return carry + ` ${name}`;
      } else {
        return carry + ` ${name}="${escape(value)}"`;
      }
    }, "");
    return `<${node.type}${attrs}>`;
  }
  function renderTagChildren(node) {
    return typeof node.props.children === "string" ? node.props.children : node.props.children.reduce((html, child) => html + renderTag(child), "");
  }
  function renderTag(node) {
    let html = renderTagStart(node);
    if (node.props.children) {
      html += renderTagChildren(node);
    }
    if (node.props.dangerouslySetInnerHTML) {
      html += node.props.dangerouslySetInnerHTML.__html;
    }
    if (!isUnaryTag(node)) {
      html += `</${node.type}>`;
    }
    return html;
  }
  function ensureNodeHasInertiaProp(node) {
    return React.cloneElement(node, {
      inertia: node.props["head-key"] !== void 0 ? node.props["head-key"] : ""
    });
  }
  function renderNode(node) {
    return renderTag(ensureNodeHasInertiaProp(node));
  }
  function renderNodes(nodes) {
    const computed = React.Children.toArray(nodes).filter((node) => node).map((node) => renderNode(node));
    if (title && !computed.find((tag) => tag.startsWith("<title"))) {
      computed.push(`<title inertia>${title}</title>`);
    }
    return computed;
  }
  if (isServer) {
    provider.update(renderNodes(children));
  }
  return null;
};
var Head_default = Head;

// src/Link.ts
import {
  mergeDataIntoQueryString as mergeDataIntoQueryString2,
  router as router6,
  shouldIntercept,
  shouldNavigate
} from "@inertiajs/core";
import { createElement as createElement4, forwardRef as forwardRef2, useEffect as useEffect7, useMemo as useMemo6, useRef as useRef3, useState as useState6 } from "react";
var noop2 = () => void 0;
var Link = forwardRef2(
  ({
    children,
    as = "a",
    data = {},
    href = "",
    method = "get",
    preserveScroll = false,
    preserveState = null,
    replace = false,
    only = [],
    except = [],
    headers = {},
    queryStringArrayFormat = "brackets",
    async = false,
    onClick = noop2,
    onCancelToken = noop2,
    onBefore = noop2,
    onStart = noop2,
    onProgress = noop2,
    onFinish = noop2,
    onCancel = noop2,
    onSuccess = noop2,
    onError = noop2,
    onPrefetching = noop2,
    onPrefetched = noop2,
    prefetch = false,
    cacheFor = 0,
    cacheTags = [],
    ...props
  }, ref) => {
    const [inFlightCount, setInFlightCount] = useState6(0);
    const hoverTimeout = useRef3(null);
    const _method = useMemo6(() => {
      return typeof href === "object" ? href.method : method.toLowerCase();
    }, [href, method]);
    const _as = useMemo6(() => {
      if (typeof as !== "string" || as.toLowerCase() !== "a") {
        return as;
      }
      return _method !== "get" ? "button" : as.toLowerCase();
    }, [as, _method]);
    const mergeDataArray = useMemo6(
      () => mergeDataIntoQueryString2(_method, typeof href === "object" ? href.url : href, data, queryStringArrayFormat),
      [href, _method, data, queryStringArrayFormat]
    );
    const url = useMemo6(() => mergeDataArray[0], [mergeDataArray]);
    const _data = useMemo6(() => mergeDataArray[1], [mergeDataArray]);
    const baseParams = useMemo6(
      () => ({
        data: _data,
        method: _method,
        preserveScroll,
        preserveState: preserveState ?? _method !== "get",
        replace,
        only,
        except,
        headers,
        async
      }),
      [_data, _method, preserveScroll, preserveState, replace, only, except, headers, async]
    );
    const visitParams = useMemo6(
      () => ({
        ...baseParams,
        onCancelToken,
        onBefore,
        onStart(visit) {
          setInFlightCount((count) => count + 1);
          onStart(visit);
        },
        onProgress,
        onFinish(visit) {
          setInFlightCount((count) => count - 1);
          onFinish(visit);
        },
        onCancel,
        onSuccess,
        onError
      }),
      [baseParams, onCancelToken, onBefore, onStart, onProgress, onFinish, onCancel, onSuccess, onError]
    );
    const prefetchModes = useMemo6(
      () => {
        if (prefetch === true) {
          return ["hover"];
        }
        if (prefetch === false) {
          return [];
        }
        if (Array.isArray(prefetch)) {
          return prefetch;
        }
        return [prefetch];
      },
      Array.isArray(prefetch) ? prefetch : [prefetch]
    );
    const cacheForValue = useMemo6(() => {
      if (cacheFor !== 0) {
        return cacheFor;
      }
      if (prefetchModes.length === 1 && prefetchModes[0] === "click") {
        return 0;
      }
      return 3e4;
    }, [cacheFor, prefetchModes]);
    const doPrefetch = useMemo6(() => {
      return () => {
        router6.prefetch(
          url,
          {
            ...baseParams,
            onPrefetching,
            onPrefetched
          },
          { cacheFor: cacheForValue, cacheTags }
        );
      };
    }, [url, baseParams, onPrefetching, onPrefetched, cacheForValue, cacheTags]);
    useEffect7(() => {
      return () => {
        clearTimeout(hoverTimeout.current);
      };
    }, []);
    useEffect7(() => {
      if (prefetchModes.includes("mount")) {
        setTimeout(() => doPrefetch());
      }
    }, prefetchModes);
    const regularEvents = {
      onClick: (event) => {
        onClick(event);
        if (shouldIntercept(event)) {
          event.preventDefault();
          router6.visit(url, visitParams);
        }
      }
    };
    const prefetchHoverEvents = {
      onMouseEnter: () => {
        hoverTimeout.current = window.setTimeout(() => {
          doPrefetch();
        }, 75);
      },
      onMouseLeave: () => {
        clearTimeout(hoverTimeout.current);
      },
      onClick: regularEvents.onClick
    };
    const prefetchClickEvents = {
      onMouseDown: (event) => {
        if (shouldIntercept(event)) {
          event.preventDefault();
          doPrefetch();
        }
      },
      onKeyDown: (event) => {
        if (shouldIntercept(event) && shouldNavigate(event)) {
          event.preventDefault();
          doPrefetch();
        }
      },
      onMouseUp: (event) => {
        event.preventDefault();
        router6.visit(url, visitParams);
      },
      onKeyUp: (event) => {
        if (shouldNavigate(event)) {
          event.preventDefault();
          router6.visit(url, visitParams);
        }
      },
      onClick: (event) => {
        onClick(event);
        if (shouldIntercept(event)) {
          event.preventDefault();
        }
      }
    };
    const elProps = useMemo6(() => {
      if (_as === "button") {
        return { type: "button" };
      }
      if (_as === "a" || typeof _as !== "string") {
        return { href: url };
      }
      return {};
    }, [_as, url]);
    return createElement4(
      _as,
      {
        ...props,
        ...elProps,
        ref,
        ...(() => {
          if (prefetchModes.includes("hover")) {
            return prefetchHoverEvents;
          }
          if (prefetchModes.includes("click")) {
            return prefetchClickEvents;
          }
          return regularEvents;
        })(),
        "data-loading": inFlightCount > 0 ? "" : void 0
      },
      children
    );
  }
);
Link.displayName = "InertiaLink";
var Link_default = Link;

// src/usePoll.ts
import { router as router7 } from "@inertiajs/core";
import { useEffect as useEffect8, useRef as useRef4 } from "react";
function usePoll(interval, requestOptions = {}, options = {
  keepAlive: false,
  autoStart: true
}) {
  const pollRef = useRef4(
    router7.poll(interval, requestOptions, {
      ...options,
      autoStart: false
    })
  );
  useEffect8(() => {
    if (options.autoStart ?? true) {
      pollRef.current.start();
    }
    return () => pollRef.current.stop();
  }, []);
  return {
    stop: pollRef.current.stop,
    start: pollRef.current.start
  };
}

// src/usePrefetch.ts
import { router as router8 } from "@inertiajs/core";
import { useEffect as useEffect9, useState as useState7 } from "react";
function usePrefetch(options = {}) {
  const cached = typeof window === "undefined" ? null : router8.getCached(window.location.pathname, options);
  const inFlight = typeof window === "undefined" ? null : router8.getPrefetching(window.location.pathname, options);
  const [lastUpdatedAt, setLastUpdatedAt] = useState7(cached?.staleTimestamp || null);
  const [isPrefetching, setIsPrefetching] = useState7(inFlight !== null);
  const [isPrefetched, setIsPrefetched] = useState7(cached !== null);
  useEffect9(() => {
    const onPrefetchingListener = router8.on("prefetching", (e) => {
      if (e.detail.visit.url.pathname === window.location.pathname) {
        setIsPrefetching(true);
      }
    });
    const onPrefetchedListener = router8.on("prefetched", (e) => {
      if (e.detail.visit.url.pathname === window.location.pathname) {
        setIsPrefetching(false);
        setIsPrefetched(true);
        setLastUpdatedAt(e.detail.fetchedAt);
      }
    });
    return () => {
      onPrefetchedListener();
      onPrefetchingListener();
    };
  }, []);
  return {
    lastUpdatedAt,
    isPrefetching,
    isPrefetched,
    flush: () => router8.flush(window.location.pathname, options)
  };
}

// src/WhenVisible.ts
import { router as router9 } from "@inertiajs/core";
import { createElement as createElement5, useCallback as useCallback2, useEffect as useEffect10, useRef as useRef5, useState as useState8 } from "react";
var WhenVisible = ({ children, data, params, buffer, as, always, fallback }) => {
  always = always ?? false;
  as = as ?? "div";
  fallback = fallback ?? null;
  const [loaded, setLoaded] = useState8(false);
  const hasFetched = useRef5(false);
  const fetching = useRef5(false);
  const ref = useRef5(null);
  const getReloadParams = useCallback2(() => {
    if (data) {
      return {
        only: Array.isArray(data) ? data : [data]
      };
    }
    if (!params) {
      throw new Error("You must provide either a `data` or `params` prop.");
    }
    return params;
  }, [params, data]);
  useEffect10(() => {
    if (!ref.current) {
      return;
    }
    const observer = new IntersectionObserver(
      (entries) => {
        if (!entries[0].isIntersecting) {
          return;
        }
        if (!always && hasFetched.current) {
          observer.disconnect();
        }
        if (fetching.current) {
          return;
        }
        hasFetched.current = true;
        fetching.current = true;
        const reloadParams = getReloadParams();
        router9.reload({
          ...reloadParams,
          onStart: (e) => {
            fetching.current = true;
            reloadParams.onStart?.(e);
          },
          onFinish: (e) => {
            setLoaded(true);
            fetching.current = false;
            reloadParams.onFinish?.(e);
            if (!always) {
              observer.disconnect();
            }
          }
        });
      },
      {
        rootMargin: `${buffer || 0}px`
      }
    );
    observer.observe(ref.current);
    return () => {
      observer.disconnect();
    };
  }, [ref, getReloadParams, buffer]);
  const resolveChildren = () => typeof children === "function" ? children() : children;
  const resolveFallback = () => typeof fallback === "function" ? fallback() : fallback;
  if (always || !loaded) {
    return createElement5(
      as,
      {
        props: null,
        ref
      },
      loaded ? resolveChildren() : resolveFallback()
    );
  }
  return loaded ? resolveChildren() : null;
};
WhenVisible.displayName = "InertiaWhenVisible";
var WhenVisible_default = WhenVisible;

// src/index.ts
var router3 = Router;
export {
  Deferred_default as Deferred,
  Form_default as Form,
  Head_default as Head,
  Link_default as Link,
  WhenVisible_default as WhenVisible,
  createInertiaApp,
  router3 as router,
  useForm,
  usePage,
  usePoll,
  usePrefetch,
  useRemember
};
//# sourceMappingURL=index.esm.js.map
