import {
  Fragment,
  computed,
  createApp,
  createSSRApp,
  defineComponent,
  h,
  inject,
  isReactive,
  markRaw,
  nextTick,
  onBeforeUnmount,
  onMounted,
  onUnmounted,
  provide,
  reactive,
  ref,
  shallowRef,
  watch
} from "./chunk-Q65E7YNW.js";
import "./chunk-PZ5AY32C.js";

// node_modules/es-toolkit/dist/array/chunk.mjs
function chunk(arr, size2) {
  if (!Number.isInteger(size2) || size2 <= 0) throw new Error("Size must be an integer greater than zero.");
  const chunkLength = Math.ceil(arr.length / size2);
  const result2 = Array(chunkLength);
  for (let index = 0; index < chunkLength; index++) {
    const start2 = index * size2;
    const end = start2 + size2;
    result2[index] = arr.slice(start2, end);
  }
  return result2;
}

// node_modules/es-toolkit/dist/array/compact.mjs
function compact(arr) {
  const result2 = [];
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    if (item) result2.push(item);
  }
  return result2;
}

// node_modules/es-toolkit/dist/array/difference.mjs
function difference(firstArr, secondArr) {
  const secondSet = new Set(secondArr);
  return firstArr.filter((item) => !secondSet.has(item));
}

// node_modules/es-toolkit/dist/array/differenceBy.mjs
function differenceBy(firstArr, secondArr, mapper) {
  const mappedSecondSet = new Set(secondArr.map((item) => mapper(item)));
  return firstArr.filter((item) => {
    return !mappedSecondSet.has(mapper(item));
  });
}

// node_modules/es-toolkit/dist/array/differenceWith.mjs
function differenceWith(firstArr, secondArr, areItemsEqual) {
  return firstArr.filter((firstItem) => {
    return secondArr.every((secondItem) => {
      return !areItemsEqual(firstItem, secondItem);
    });
  });
}

// node_modules/es-toolkit/dist/array/drop.mjs
function drop(arr, itemsCount) {
  itemsCount = Math.max(itemsCount, 0);
  return arr.slice(itemsCount);
}

// node_modules/es-toolkit/dist/array/dropRight.mjs
function dropRight(arr, itemsCount) {
  itemsCount = Math.min(-itemsCount, 0);
  if (itemsCount === 0) return arr.slice();
  return arr.slice(0, itemsCount);
}

// node_modules/es-toolkit/dist/array/dropRightWhile.mjs
function dropRightWhile(arr, canContinueDropping) {
  for (let i = arr.length - 1; i >= 0; i--) if (!canContinueDropping(arr[i], i, arr)) return arr.slice(0, i + 1);
  return [];
}

// node_modules/es-toolkit/dist/array/dropWhile.mjs
function dropWhile(arr, canContinueDropping) {
  const dropEndIndex = arr.findIndex((item, index, arr2) => !canContinueDropping(item, index, arr2));
  if (dropEndIndex === -1) return [];
  return arr.slice(dropEndIndex);
}

// node_modules/es-toolkit/dist/array/fill.mjs
function fill(array, value, start2 = 0, end = array.length) {
  const length = array.length;
  const finalStart = Math.max(start2 >= 0 ? start2 : length + start2, 0);
  const finalEnd = Math.min(end >= 0 ? end : length + end, length);
  for (let i = finalStart; i < finalEnd; i++) array[i] = value;
  return array;
}

// node_modules/es-toolkit/dist/array/flatten.mjs
function flatten(arr, depth = 1) {
  const result2 = [];
  const flooredDepth = Math.floor(depth);
  const recursive = (arr2, currentDepth) => {
    for (let i = 0; i < arr2.length; i++) {
      const item = arr2[i];
      if (Array.isArray(item) && currentDepth < flooredDepth) recursive(item, currentDepth + 1);
      else result2.push(item);
    }
  };
  recursive(arr, 0);
  return result2;
}

// node_modules/es-toolkit/dist/array/groupBy.mjs
function groupBy(arr, getKeyFromItem) {
  const result2 = {};
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    const key2 = getKeyFromItem(item, i, arr);
    if (!Object.hasOwn(result2, key2)) result2[key2] = [];
    result2[key2].push(item);
  }
  return result2;
}

// node_modules/es-toolkit/dist/array/head.mjs
function head(arr) {
  return arr[0];
}

// node_modules/es-toolkit/dist/array/initial.mjs
function initial(arr) {
  return arr.slice(0, -1);
}

// node_modules/es-toolkit/dist/array/intersection.mjs
function intersection(firstArr, secondArr) {
  const secondSet = new Set(secondArr);
  return firstArr.filter((item) => secondSet.has(item));
}

// node_modules/es-toolkit/dist/array/intersectionBy.mjs
function intersectionBy(firstArr, secondArr, mapper) {
  const result2 = [];
  const mappedSecondSet = new Set(secondArr.map(mapper));
  for (let i = 0; i < firstArr.length; i++) {
    const item = firstArr[i];
    const mappedItem = mapper(item);
    if (mappedSecondSet.has(mappedItem)) {
      result2.push(item);
      mappedSecondSet.delete(mappedItem);
    }
  }
  return result2;
}

// node_modules/es-toolkit/dist/array/intersectionWith.mjs
function intersectionWith(firstArr, secondArr, areItemsEqual) {
  return firstArr.filter((firstItem) => {
    return secondArr.some((secondItem) => {
      return areItemsEqual(firstItem, secondItem);
    });
  });
}

// node_modules/es-toolkit/dist/array/last.mjs
function last(arr) {
  return arr[arr.length - 1];
}

// node_modules/es-toolkit/dist/array/maxBy.mjs
function maxBy(items, getValue) {
  if (items.length === 0) return;
  let maxElement = items[0];
  let max2 = getValue(maxElement, 0, items);
  for (let i = 1; i < items.length; i++) {
    const element = items[i];
    const value = getValue(element, i, items);
    if (value > max2) {
      max2 = value;
      maxElement = element;
    }
  }
  return maxElement;
}

// node_modules/es-toolkit/dist/array/minBy.mjs
function minBy(items, getValue) {
  if (items.length === 0) return;
  let minElement = items[0];
  let min2 = getValue(minElement, 0, items);
  for (let i = 1; i < items.length; i++) {
    const element = items[i];
    const value = getValue(element, i, items);
    if (value < min2) {
      min2 = value;
      minElement = element;
    }
  }
  return minElement;
}

// node_modules/es-toolkit/dist/array/pull.mjs
function pull(arr, valuesToRemove) {
  const valuesSet = new Set(valuesToRemove);
  let resultIndex = 0;
  for (let i = 0; i < arr.length; i++) {
    if (valuesSet.has(arr[i])) continue;
    if (!Object.hasOwn(arr, i)) {
      delete arr[resultIndex++];
      continue;
    }
    arr[resultIndex++] = arr[i];
  }
  arr.length = resultIndex;
  return arr;
}

// node_modules/es-toolkit/dist/array/remove.mjs
function remove(arr, shouldRemoveElement) {
  const originalArr = arr.slice();
  const removed = [];
  let resultIndex = 0;
  for (let i = 0; i < arr.length; i++) {
    if (shouldRemoveElement(arr[i], i, originalArr)) {
      removed.push(arr[i]);
      continue;
    }
    if (!Object.hasOwn(arr, i)) {
      delete arr[resultIndex++];
      continue;
    }
    arr[resultIndex++] = arr[i];
  }
  arr.length = resultIndex;
  return removed;
}

// node_modules/es-toolkit/dist/array/sample.mjs
function sample(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

// node_modules/es-toolkit/dist/math/random.mjs
function random(minimum, maximum) {
  if (maximum == null) {
    maximum = minimum;
    minimum = 0;
  }
  if (minimum >= maximum) throw new Error("Invalid input: The maximum value must be greater than the minimum value.");
  return Math.random() * (maximum - minimum) + minimum;
}

// node_modules/es-toolkit/dist/math/randomInt.mjs
function randomInt(minimum, maximum) {
  return Math.floor(random(minimum, maximum));
}

// node_modules/es-toolkit/dist/array/sampleSize.mjs
function sampleSize(array, size2) {
  if (size2 > array.length) throw new Error("Size must be less than or equal to the length of array.");
  const result2 = new Array(size2);
  const selected = /* @__PURE__ */ new Set();
  for (let step = array.length - size2, resultIndex = 0; step < array.length; step++, resultIndex++) {
    let index = randomInt(0, step + 1);
    if (selected.has(index)) index = step;
    selected.add(index);
    result2[resultIndex] = array[index];
  }
  return result2;
}

// node_modules/es-toolkit/dist/array/shuffle.mjs
function shuffle(arr) {
  const result2 = arr.slice();
  for (let i = result2.length - 1; i >= 1; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [result2[i], result2[j]] = [result2[j], result2[i]];
  }
  return result2;
}

// node_modules/es-toolkit/dist/array/tail.mjs
function tail(arr) {
  return arr.slice(1);
}

// node_modules/es-toolkit/dist/compat/predicate/isSymbol.mjs
function isSymbol(value) {
  return typeof value === "symbol" || value instanceof Symbol;
}

// node_modules/es-toolkit/dist/compat/util/toNumber.mjs
function toNumber(value) {
  if (isSymbol(value)) return NaN;
  return Number(value);
}

// node_modules/es-toolkit/dist/compat/util/toFinite.mjs
function toFinite(value) {
  if (!value) return value === 0 ? value : 0;
  value = toNumber(value);
  if (value === Infinity || value === -Infinity) return (value < 0 ? -1 : 1) * Number.MAX_VALUE;
  return value === value ? value : 0;
}

// node_modules/es-toolkit/dist/compat/util/toInteger.mjs
function toInteger(value) {
  const finite = toFinite(value);
  const remainder = finite % 1;
  return remainder ? finite - remainder : finite;
}

// node_modules/es-toolkit/dist/array/take.mjs
function take(arr, count, guard) {
  count = guard || count === void 0 ? 1 : toInteger(count);
  return arr.slice(0, count);
}

// node_modules/es-toolkit/dist/array/takeRight.mjs
function takeRight(arr, count, guard) {
  count = guard || count === void 0 ? 1 : toInteger(count);
  if (count <= 0 || arr.length === 0) return [];
  return arr.slice(-count);
}

// node_modules/es-toolkit/dist/array/uniq.mjs
function uniq(arr) {
  return [...new Set(arr)];
}

// node_modules/es-toolkit/dist/array/uniqBy.mjs
function uniqBy(arr, mapper) {
  const map2 = /* @__PURE__ */ new Map();
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    const key2 = mapper(item, i, arr);
    if (!map2.has(key2)) map2.set(key2, item);
  }
  return Array.from(map2.values());
}

// node_modules/es-toolkit/dist/array/uniqWith.mjs
function uniqWith(arr, areItemsEqual) {
  const result2 = [];
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    if (result2.every((v) => !areItemsEqual(v, item))) result2.push(item);
  }
  return result2;
}

// node_modules/es-toolkit/dist/array/unzip.mjs
function unzip(zipped) {
  let maxLen = 0;
  for (let i = 0; i < zipped.length; i++) if (zipped[i].length > maxLen) maxLen = zipped[i].length;
  const result2 = new Array(maxLen);
  for (let i = 0; i < maxLen; i++) {
    result2[i] = new Array(zipped.length);
    for (let j = 0; j < zipped.length; j++) result2[i][j] = zipped[j][i];
  }
  return result2;
}

// node_modules/es-toolkit/dist/array/windowed.mjs
function windowed(arr, size2, step = 1, { partialWindows = false } = {}) {
  if (size2 <= 0 || !Number.isInteger(size2)) throw new Error("Size must be a positive integer.");
  if (step <= 0 || !Number.isInteger(step)) throw new Error("Step must be a positive integer.");
  const result2 = [];
  const end = partialWindows ? arr.length : arr.length - size2 + 1;
  for (let i = 0; i < end; i += step) result2.push(arr.slice(i, i + size2));
  return result2;
}

// node_modules/es-toolkit/dist/array/without.mjs
function without(array, ...values2) {
  return difference(array, values2);
}

// node_modules/es-toolkit/dist/array/zip.mjs
function zip(...arrs) {
  let rowCount = 0;
  for (let i = 0; i < arrs.length; i++) if (arrs[i].length > rowCount) rowCount = arrs[i].length;
  const columnCount = arrs.length;
  const result2 = Array(rowCount);
  for (let i = 0; i < rowCount; ++i) {
    const row = Array(columnCount);
    for (let j = 0; j < columnCount; ++j) row[j] = arrs[j][i];
    result2[i] = row;
  }
  return result2;
}

// node_modules/es-toolkit/dist/_internal/globalThis.mjs
var globalThis_ = typeof globalThis === "object" && globalThis || typeof window === "object" && window || typeof self === "object" && self || typeof global === "object" && global || /* @__PURE__ */ (function() {
  return this;
})() || Function("return this")();

// node_modules/es-toolkit/dist/_internal/DOMException.mjs
var DOMException2 = typeof globalThis_.DOMException !== "undefined" ? globalThis_.DOMException : Error;

// node_modules/es-toolkit/dist/function/after.mjs
function after(n, func) {
  if (!Number.isInteger(n) || n < 0) throw new Error(`n must be a non-negative integer.`);
  let counter = 0;
  return (...args) => {
    if (++counter >= n) return func(...args);
  };
}

// node_modules/es-toolkit/dist/function/ary.mjs
function ary(func, n) {
  return function(...args) {
    return func.apply(this, args.slice(0, n));
  };
}

// node_modules/es-toolkit/dist/function/debounce.mjs
function debounce(func, debounceMs, { signal, edges } = {}) {
  let pendingThis = void 0;
  let pendingArgs = null;
  const leading = edges != null && edges.includes("leading");
  const trailing = edges == null || edges.includes("trailing");
  const invoke2 = () => {
    if (pendingArgs !== null) {
      func.apply(pendingThis, pendingArgs);
      pendingThis = void 0;
      pendingArgs = null;
    }
  };
  const onTimerEnd = () => {
    if (trailing) invoke2();
    cancel();
  };
  let timeoutId = null;
  const schedule = () => {
    if (timeoutId != null) clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      timeoutId = null;
      onTimerEnd();
    }, debounceMs);
  };
  const cancelTimer = () => {
    if (timeoutId !== null) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }
  };
  const cancel = () => {
    cancelTimer();
    pendingThis = void 0;
    pendingArgs = null;
  };
  const flush = () => {
    invoke2();
  };
  const debounced = function(...args) {
    if (signal?.aborted) return;
    pendingThis = this;
    pendingArgs = args;
    const isFirstCall = timeoutId == null;
    schedule();
    if (leading && isFirstCall) invoke2();
  };
  debounced.schedule = schedule;
  debounced.cancel = cancel;
  debounced.flush = flush;
  signal?.addEventListener("abort", cancel, { once: true });
  return debounced;
}

// node_modules/es-toolkit/dist/function/flow.mjs
function flow(...funcs) {
  return function(...args) {
    let result2 = funcs.length ? funcs[0].apply(this, args) : args[0];
    for (let i = 1; i < funcs.length; i++) result2 = funcs[i].call(this, result2);
    return result2;
  };
}

// node_modules/es-toolkit/dist/function/flowRight.mjs
function flowRight(...funcs) {
  return flow(...funcs.reverse());
}

// node_modules/es-toolkit/dist/function/identity.mjs
function identity(x) {
  return x;
}

// node_modules/es-toolkit/dist/function/negate.mjs
function negate(func) {
  return ((...args) => !func(...args));
}

// node_modules/es-toolkit/dist/function/noop.mjs
function noop() {
}

// node_modules/es-toolkit/dist/function/once.mjs
function once(func) {
  let called = false;
  let cache;
  return function(...args) {
    if (!called) {
      called = true;
      cache = func(...args);
    }
    return cache;
  };
}

// node_modules/es-toolkit/dist/function/partial.mjs
function partial(func, ...partialArgs) {
  return partialImpl(func, placeholderSymbol, ...partialArgs);
}
function partialImpl(func, placeholder, ...partialArgs) {
  const partialed = function(...providedArgs) {
    let providedArgsIndex = 0;
    const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
    const remainingArgs = providedArgs.slice(providedArgsIndex);
    return func.apply(this, substitutedArgs.concat(remainingArgs));
  };
  if (func.prototype) partialed.prototype = Object.create(func.prototype);
  return partialed;
}
var placeholderSymbol = /* @__PURE__ */ Symbol("partial.placeholder");
partial.placeholder = placeholderSymbol;

// node_modules/es-toolkit/dist/function/partialRight.mjs
function partialRight(func, ...partialArgs) {
  return partialRightImpl(func, placeholderSymbol2, ...partialArgs);
}
function partialRightImpl(func, placeholder, ...partialArgs) {
  const partialedRight = function(...providedArgs) {
    const placeholderLength = partialArgs.filter((arg) => arg === placeholder).length;
    const rangeLength = Math.max(providedArgs.length - placeholderLength, 0);
    const remainingArgs = providedArgs.slice(0, rangeLength);
    let providedArgsIndex = rangeLength;
    const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
    return func.apply(this, remainingArgs.concat(substitutedArgs));
  };
  if (func.prototype) partialedRight.prototype = Object.create(func.prototype);
  return partialedRight;
}
var placeholderSymbol2 = /* @__PURE__ */ Symbol("partialRight.placeholder");
partialRight.placeholder = placeholderSymbol2;

// node_modules/es-toolkit/dist/function/rest.mjs
function rest(func, startIndex = func.length - 1) {
  return function(...args) {
    const rest3 = args.slice(startIndex);
    const params = args.slice(0, startIndex);
    while (params.length < startIndex) params.push(void 0);
    return func.apply(this, [...params, rest3]);
  };
}

// node_modules/es-toolkit/dist/function/retry.mjs
var DEFAULT_RETRIES = Number.POSITIVE_INFINITY;

// node_modules/es-toolkit/dist/math/inRange.mjs
function inRange(value, minimum, maximum) {
  if (maximum == null) {
    maximum = minimum;
    minimum = 0;
  }
  if (minimum >= maximum) throw new Error("The maximum value must be greater than the minimum value.");
  return minimum <= value && value < maximum;
}

// node_modules/es-toolkit/dist/math/sumBy.mjs
function sumBy(items, getValue) {
  let result2 = 0;
  for (let i = 0; i < items.length; i++) result2 += getValue(items[i], i);
  return result2;
}

// node_modules/es-toolkit/dist/math/meanBy.mjs
function meanBy(items, getValue) {
  return sumBy(items, (item) => getValue(item)) / items.length;
}

// node_modules/es-toolkit/dist/math/range.mjs
function range(start2, end, step = 1) {
  if (end == null) {
    end = start2;
    start2 = 0;
  }
  if (!Number.isInteger(step) || step === 0) throw new Error(`The step value must be a non-zero integer.`);
  const length = Math.max(Math.ceil((end - start2) / step), 0);
  const result2 = new Array(length);
  for (let i = 0; i < length; i++) result2[i] = start2 + i * step;
  return result2;
}

// node_modules/es-toolkit/dist/predicate/isPrimitive.mjs
function isPrimitive(value) {
  return value == null || typeof value !== "object" && typeof value !== "function";
}

// node_modules/es-toolkit/dist/predicate/isTypedArray.mjs
function isTypedArray(x) {
  return ArrayBuffer.isView(x) && !(x instanceof DataView);
}

// node_modules/es-toolkit/dist/object/clone.mjs
function clone(obj) {
  if (isPrimitive(obj)) return obj;
  if (Array.isArray(obj) || isTypedArray(obj) || obj instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && obj instanceof SharedArrayBuffer) return obj.slice(0);
  const prototype = Object.getPrototypeOf(obj);
  if (prototype == null) return Object.assign(Object.create(prototype), obj);
  const Constructor = prototype.constructor;
  if (obj instanceof Date || obj instanceof Map || obj instanceof Set) return new Constructor(obj);
  if (obj instanceof RegExp) {
    const newRegExp = new Constructor(obj);
    newRegExp.lastIndex = obj.lastIndex;
    return newRegExp;
  }
  if (obj instanceof DataView) return new Constructor(obj.buffer.slice(0));
  if (obj instanceof Error) {
    let newError;
    if (obj instanceof AggregateError) newError = new Constructor(obj.errors, obj.message, { cause: obj.cause });
    else newError = new Constructor(obj.message, { cause: obj.cause });
    newError.stack = obj.stack;
    Object.assign(newError, obj);
    return newError;
  }
  if (typeof File !== "undefined" && obj instanceof File) return new Constructor([obj], obj.name, {
    type: obj.type,
    lastModified: obj.lastModified
  });
  if (typeof obj === "object") return Object.assign(Object.create(prototype), obj);
  return obj;
}

// node_modules/es-toolkit/dist/predicate/isBuffer.mjs
function isBuffer(x) {
  return typeof globalThis_.Buffer !== "undefined" && globalThis_.Buffer.isBuffer(x);
}

// node_modules/es-toolkit/dist/compat/_internal/getSymbols.mjs
function getSymbols(object) {
  return Object.getOwnPropertySymbols(object).filter((symbol) => Object.prototype.propertyIsEnumerable.call(object, symbol));
}

// node_modules/es-toolkit/dist/compat/_internal/getTag.mjs
function getTag(value) {
  if (value == null) return value === void 0 ? "[object Undefined]" : "[object Null]";
  return Object.prototype.toString.call(value);
}

// node_modules/es-toolkit/dist/compat/_internal/tags.mjs
var regexpTag = "[object RegExp]";
var stringTag = "[object String]";
var numberTag = "[object Number]";
var booleanTag = "[object Boolean]";
var argumentsTag = "[object Arguments]";
var symbolTag = "[object Symbol]";
var dateTag = "[object Date]";
var mapTag = "[object Map]";
var setTag = "[object Set]";
var arrayTag = "[object Array]";
var functionTag = "[object Function]";
var arrayBufferTag = "[object ArrayBuffer]";
var objectTag = "[object Object]";
var errorTag = "[object Error]";
var dataViewTag = "[object DataView]";
var uint8ArrayTag = "[object Uint8Array]";
var uint8ClampedArrayTag = "[object Uint8ClampedArray]";
var uint16ArrayTag = "[object Uint16Array]";
var uint32ArrayTag = "[object Uint32Array]";
var bigUint64ArrayTag = "[object BigUint64Array]";
var int8ArrayTag = "[object Int8Array]";
var int16ArrayTag = "[object Int16Array]";
var int32ArrayTag = "[object Int32Array]";
var bigInt64ArrayTag = "[object BigInt64Array]";
var float32ArrayTag = "[object Float32Array]";
var float64ArrayTag = "[object Float64Array]";

// node_modules/es-toolkit/dist/object/cloneDeepWith.mjs
function cloneDeepWith(obj, cloneValue) {
  return cloneDeepWithImpl(obj, void 0, obj, /* @__PURE__ */ new Map(), cloneValue);
}
function cloneDeepWithImpl(valueToClone, keyToClone, objectToClone, stack = /* @__PURE__ */ new Map(), cloneValue = void 0) {
  const cloned = cloneValue?.(valueToClone, keyToClone, objectToClone, stack);
  if (cloned !== void 0) return cloned;
  if (isPrimitive(valueToClone)) return valueToClone;
  if (stack.has(valueToClone)) return stack.get(valueToClone);
  if (Array.isArray(valueToClone)) {
    const result2 = new Array(valueToClone.length);
    stack.set(valueToClone, result2);
    for (let i = 0; i < valueToClone.length; i++) result2[i] = cloneDeepWithImpl(valueToClone[i], i, objectToClone, stack, cloneValue);
    if (Object.hasOwn(valueToClone, "index")) result2.index = valueToClone.index;
    if (Object.hasOwn(valueToClone, "input")) result2.input = valueToClone.input;
    return result2;
  }
  if (valueToClone instanceof Date) return new Date(valueToClone.getTime());
  if (valueToClone instanceof RegExp) {
    const result2 = new RegExp(valueToClone.source, valueToClone.flags);
    result2.lastIndex = valueToClone.lastIndex;
    return result2;
  }
  if (valueToClone instanceof Map) {
    const result2 = /* @__PURE__ */ new Map();
    stack.set(valueToClone, result2);
    for (const [key2, value] of valueToClone) result2.set(key2, cloneDeepWithImpl(value, key2, objectToClone, stack, cloneValue));
    return result2;
  }
  if (valueToClone instanceof Set) {
    const result2 = /* @__PURE__ */ new Set();
    stack.set(valueToClone, result2);
    for (const value of valueToClone) result2.add(cloneDeepWithImpl(value, void 0, objectToClone, stack, cloneValue));
    return result2;
  }
  if (isBuffer(valueToClone)) return valueToClone.subarray();
  if (isTypedArray(valueToClone)) {
    const result2 = new (Object.getPrototypeOf(valueToClone)).constructor(valueToClone.length);
    stack.set(valueToClone, result2);
    for (let i = 0; i < valueToClone.length; i++) result2[i] = cloneDeepWithImpl(valueToClone[i], i, objectToClone, stack, cloneValue);
    return result2;
  }
  if (valueToClone instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && valueToClone instanceof SharedArrayBuffer) return valueToClone.slice(0);
  if (valueToClone instanceof DataView) {
    const result2 = new DataView(valueToClone.buffer.slice(0), valueToClone.byteOffset, valueToClone.byteLength);
    stack.set(valueToClone, result2);
    copyProperties(result2, valueToClone, objectToClone, stack, cloneValue);
    return result2;
  }
  if (typeof File !== "undefined" && valueToClone instanceof File) {
    const result2 = new File([valueToClone], valueToClone.name, { type: valueToClone.type });
    stack.set(valueToClone, result2);
    copyProperties(result2, valueToClone, objectToClone, stack, cloneValue);
    return result2;
  }
  if (typeof Blob !== "undefined" && valueToClone instanceof Blob) {
    const result2 = new Blob([valueToClone], { type: valueToClone.type });
    stack.set(valueToClone, result2);
    copyProperties(result2, valueToClone, objectToClone, stack, cloneValue);
    return result2;
  }
  if (valueToClone instanceof Error) {
    const result2 = structuredClone(valueToClone);
    stack.set(valueToClone, result2);
    result2.message = valueToClone.message;
    result2.name = valueToClone.name;
    result2.stack = valueToClone.stack;
    result2.cause = valueToClone.cause;
    result2.constructor = valueToClone.constructor;
    copyProperties(result2, valueToClone, objectToClone, stack, cloneValue);
    return result2;
  }
  if (valueToClone instanceof Boolean) {
    const result2 = new Boolean(valueToClone.valueOf());
    stack.set(valueToClone, result2);
    copyProperties(result2, valueToClone, objectToClone, stack, cloneValue);
    return result2;
  }
  if (valueToClone instanceof Number) {
    const result2 = new Number(valueToClone.valueOf());
    stack.set(valueToClone, result2);
    copyProperties(result2, valueToClone, objectToClone, stack, cloneValue);
    return result2;
  }
  if (valueToClone instanceof String) {
    const result2 = new String(valueToClone.valueOf());
    stack.set(valueToClone, result2);
    copyProperties(result2, valueToClone, objectToClone, stack, cloneValue);
    return result2;
  }
  if (typeof valueToClone === "object" && isCloneableObject(valueToClone)) {
    const result2 = Object.create(Object.getPrototypeOf(valueToClone));
    stack.set(valueToClone, result2);
    copyProperties(result2, valueToClone, objectToClone, stack, cloneValue);
    return result2;
  }
  return valueToClone;
}
function copyProperties(target, source, objectToClone = target, stack, cloneValue) {
  const keys2 = [...Object.keys(source), ...getSymbols(source)];
  for (let i = 0; i < keys2.length; i++) {
    const key2 = keys2[i];
    const descriptor = Object.getOwnPropertyDescriptor(target, key2);
    if (descriptor == null || descriptor.writable) target[key2] = cloneDeepWithImpl(source[key2], key2, objectToClone, stack, cloneValue);
  }
}
function isCloneableObject(object) {
  switch (getTag(object)) {
    case argumentsTag:
    case arrayTag:
    case arrayBufferTag:
    case dataViewTag:
    case booleanTag:
    case dateTag:
    case float32ArrayTag:
    case float64ArrayTag:
    case int8ArrayTag:
    case int16ArrayTag:
    case int32ArrayTag:
    case mapTag:
    case numberTag:
    case objectTag:
    case regexpTag:
    case setTag:
    case stringTag:
    case symbolTag:
    case uint8ArrayTag:
    case uint8ClampedArrayTag:
    case uint16ArrayTag:
    case uint32ArrayTag:
      return true;
    default:
      return false;
  }
}

// node_modules/es-toolkit/dist/object/cloneDeep.mjs
function cloneDeep(obj) {
  return cloneDeepWithImpl(obj, void 0, obj, /* @__PURE__ */ new Map(), void 0);
}

// node_modules/es-toolkit/dist/object/findKey.mjs
function findKey(obj, predicate) {
  return Object.keys(obj).find((key2) => predicate(obj[key2], key2, obj));
}

// node_modules/es-toolkit/dist/predicate/isPlainObject.mjs
function isPlainObject(value) {
  if (!value || typeof value !== "object") return false;
  const proto = Object.getPrototypeOf(value);
  if (!(proto === null || proto === Object.prototype || Object.getPrototypeOf(proto) === null)) return false;
  return Object.prototype.toString.call(value) === "[object Object]";
}

// node_modules/es-toolkit/dist/object/invert.mjs
function invert(obj) {
  const result2 = {};
  const keys2 = Object.keys(obj);
  for (let i = 0; i < keys2.length; i++) {
    const key2 = keys2[i];
    const value = obj[key2];
    result2[value] = key2;
  }
  return result2;
}

// node_modules/es-toolkit/dist/object/mapKeys.mjs
function mapKeys(object, getNewKey) {
  const result2 = {};
  const keys2 = Object.keys(object);
  for (let i = 0; i < keys2.length; i++) {
    const key2 = keys2[i];
    const value = object[key2];
    result2[getNewKey(value, key2, object)] = value;
  }
  return result2;
}

// node_modules/es-toolkit/dist/object/mapValues.mjs
function mapValues(object, getNewValue) {
  const result2 = {};
  const keys2 = Object.keys(object);
  for (let i = 0; i < keys2.length; i++) {
    const key2 = keys2[i];
    const value = object[key2];
    result2[key2] = getNewValue(value, key2, object);
  }
  return result2;
}

// node_modules/es-toolkit/dist/_internal/isUnsafeProperty.mjs
function isUnsafeProperty(key2) {
  return key2 === "__proto__";
}

// node_modules/es-toolkit/dist/string/capitalize.mjs
function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}

// node_modules/es-toolkit/dist/string/words.mjs
var CASE_SPLIT_PATTERN = new RegExp("\\p{Lu}?\\p{Ll}+|[0-9]+|\\p{Lu}+(?!\\p{Ll})|\\p{Emoji_Presentation}|\\p{Extended_Pictographic}|\\p{L}+", "gu");
function words(str) {
  return Array.from(str.match(CASE_SPLIT_PATTERN) ?? []);
}

// node_modules/es-toolkit/dist/string/camelCase.mjs
function camelCase(str) {
  const words$1 = words(str);
  if (words$1.length === 0) return "";
  const [first, ...rest3] = words$1;
  return `${first.toLowerCase()}${rest3.map((word) => capitalize(word)).join("")}`;
}

// node_modules/es-toolkit/dist/compat/predicate/isArray.mjs
function isArray(value) {
  return Array.isArray(value);
}

// node_modules/es-toolkit/dist/string/snakeCase.mjs
function snakeCase(str) {
  return words(str).map((word) => word.toLowerCase()).join("_");
}

// node_modules/es-toolkit/dist/compat/predicate/isPlainObject.mjs
function isPlainObject2(object) {
  if (typeof object !== "object") return false;
  if (object == null) return false;
  if (Object.getPrototypeOf(object) === null) return true;
  if (Object.prototype.toString.call(object) !== "[object Object]") {
    const tag = object[Symbol.toStringTag];
    if (tag == null) return false;
    if (!Object.getOwnPropertyDescriptor(object, Symbol.toStringTag)?.writable) return false;
    return object.toString() === `[object ${tag}]`;
  }
  let proto = object;
  while (Object.getPrototypeOf(proto) !== null) proto = Object.getPrototypeOf(proto);
  return Object.getPrototypeOf(object) === proto;
}

// node_modules/es-toolkit/dist/predicate/isArrayBuffer.mjs
function isArrayBuffer(value) {
  return value instanceof ArrayBuffer;
}

// node_modules/es-toolkit/dist/predicate/isDate.mjs
function isDate(value) {
  return value instanceof Date;
}

// node_modules/es-toolkit/dist/_internal/isEqualsSameValueZero.mjs
function isEqualsSameValueZero(value, other) {
  return value === other || Number.isNaN(value) && Number.isNaN(other);
}

// node_modules/es-toolkit/dist/predicate/isEqualWith.mjs
function isEqualWith(a, b, areValuesEqual) {
  return isEqualWithImpl(a, b, void 0, void 0, void 0, void 0, areValuesEqual);
}
function isEqualWithImpl(a, b, property2, aParent, bParent, stack, areValuesEqual) {
  const result2 = areValuesEqual(a, b, property2, aParent, bParent, stack);
  if (result2 !== void 0) return result2;
  if (typeof a === typeof b) switch (typeof a) {
    case "bigint":
    case "string":
    case "boolean":
    case "symbol":
    case "undefined":
      return a === b;
    case "number":
      return a === b || Object.is(a, b);
    case "function":
      return a === b;
    case "object":
      return areObjectsEqual(a, b, stack, areValuesEqual);
  }
  return areObjectsEqual(a, b, stack, areValuesEqual);
}
function areObjectsEqual(a, b, stack, areValuesEqual) {
  if (Object.is(a, b)) return true;
  let aTag = getTag(a);
  let bTag = getTag(b);
  if (aTag === "[object Arguments]") aTag = objectTag;
  if (bTag === "[object Arguments]") bTag = objectTag;
  if (aTag !== bTag) return false;
  switch (aTag) {
    case stringTag:
      return a.toString() === b.toString();
    case numberTag:
      return isEqualsSameValueZero(a.valueOf(), b.valueOf());
    case booleanTag:
    case dateTag:
    case symbolTag:
      return Object.is(a.valueOf(), b.valueOf());
    case regexpTag:
      return a.source === b.source && a.flags === b.flags;
    case functionTag:
      return a === b;
  }
  stack = stack ?? /* @__PURE__ */ new Map();
  const aStack = stack.get(a);
  const bStack = stack.get(b);
  if (aStack != null && bStack != null) return aStack === b;
  stack.set(a, b);
  stack.set(b, a);
  try {
    switch (aTag) {
      case mapTag:
        if (a.size !== b.size) return false;
        for (const [key2, value] of a.entries()) if (!b.has(key2) || !isEqualWithImpl(value, b.get(key2), key2, a, b, stack, areValuesEqual)) return false;
        return true;
      case setTag: {
        if (a.size !== b.size) return false;
        const aValues = Array.from(a.values());
        const bValues = Array.from(b.values());
        for (let i = 0; i < aValues.length; i++) {
          const aValue = aValues[i];
          const index = bValues.findIndex((bValue) => {
            return isEqualWithImpl(aValue, bValue, void 0, a, b, stack, areValuesEqual);
          });
          if (index === -1) return false;
          bValues.splice(index, 1);
        }
        return true;
      }
      case arrayTag:
      case uint8ArrayTag:
      case uint8ClampedArrayTag:
      case uint16ArrayTag:
      case uint32ArrayTag:
      case bigUint64ArrayTag:
      case int8ArrayTag:
      case int16ArrayTag:
      case int32ArrayTag:
      case bigInt64ArrayTag:
      case float32ArrayTag:
      case float64ArrayTag:
        if (isBuffer(a) !== isBuffer(b)) return false;
        if (a.length !== b.length) return false;
        for (let i = 0; i < a.length; i++) if (!isEqualWithImpl(a[i], b[i], i, a, b, stack, areValuesEqual)) return false;
        return true;
      case arrayBufferTag:
        if (a.byteLength !== b.byteLength) return false;
        return areObjectsEqual(new Uint8Array(a), new Uint8Array(b), stack, areValuesEqual);
      case dataViewTag:
        if (a.byteLength !== b.byteLength || a.byteOffset !== b.byteOffset) return false;
        return areObjectsEqual(new Uint8Array(a), new Uint8Array(b), stack, areValuesEqual);
      case errorTag:
        return a.name === b.name && a.message === b.message;
      case objectTag: {
        if (!(areObjectsEqual(a.constructor, b.constructor, stack, areValuesEqual) || isPlainObject(a) && isPlainObject(b))) return false;
        const aKeys = [...Object.keys(a), ...getSymbols(a)];
        const bKeys = [...Object.keys(b), ...getSymbols(b)];
        if (aKeys.length !== bKeys.length) return false;
        for (let i = 0; i < aKeys.length; i++) {
          const propKey = aKeys[i];
          const aProp = a[propKey];
          if (!Object.hasOwn(b, propKey)) return false;
          const bProp = b[propKey];
          if (!isEqualWithImpl(aProp, bProp, propKey, a, b, stack, areValuesEqual)) return false;
        }
        return true;
      }
      default:
        return false;
    }
  } finally {
    stack.delete(a);
    stack.delete(b);
  }
}

// node_modules/es-toolkit/dist/predicate/isEqual.mjs
function isEqual(a, b) {
  return isEqualWith(a, b, noop);
}

// node_modules/es-toolkit/dist/predicate/isFunction.mjs
function isFunction(value) {
  return typeof value === "function";
}

// node_modules/es-toolkit/dist/predicate/isLength.mjs
function isLength(value) {
  return Number.isSafeInteger(value) && value >= 0;
}

// node_modules/es-toolkit/dist/predicate/isMap.mjs
function isMap(value) {
  return value instanceof Map;
}

// node_modules/es-toolkit/dist/predicate/isNil.mjs
function isNil(x) {
  return x == null;
}

// node_modules/es-toolkit/dist/predicate/isNull.mjs
function isNull(x) {
  return x === null;
}

// node_modules/es-toolkit/dist/predicate/isRegExp.mjs
function isRegExp(value) {
  return value instanceof RegExp;
}

// node_modules/es-toolkit/dist/predicate/isSet.mjs
function isSet(value) {
  return value instanceof Set;
}

// node_modules/es-toolkit/dist/predicate/isSymbol.mjs
function isSymbol2(value) {
  return typeof value === "symbol";
}

// node_modules/es-toolkit/dist/predicate/isUndefined.mjs
function isUndefined(x) {
  return x === void 0;
}

// node_modules/es-toolkit/dist/predicate/isWeakMap.mjs
function isWeakMap(value) {
  return value instanceof WeakMap;
}

// node_modules/es-toolkit/dist/predicate/isWeakSet.mjs
function isWeakSet(value) {
  return value instanceof WeakSet;
}

// node_modules/es-toolkit/dist/string/deburr.mjs
var deburrMap = /* @__PURE__ */ new Map([
  ["Æ", "Ae"],
  ["Ð", "D"],
  ["Ø", "O"],
  ["Þ", "Th"],
  ["ß", "ss"],
  ["æ", "ae"],
  ["ð", "d"],
  ["ø", "o"],
  ["þ", "th"],
  ["Đ", "D"],
  ["đ", "d"],
  ["Ħ", "H"],
  ["ħ", "h"],
  ["ı", "i"],
  ["Ĳ", "IJ"],
  ["ĳ", "ij"],
  ["ĸ", "k"],
  ["Ŀ", "L"],
  ["ŀ", "l"],
  ["Ł", "L"],
  ["ł", "l"],
  ["ŉ", "'n"],
  ["Ŋ", "N"],
  ["ŋ", "n"],
  ["Œ", "Oe"],
  ["œ", "oe"],
  ["Ŧ", "T"],
  ["ŧ", "t"],
  ["ſ", "s"]
]);
function deburr(str) {
  str = str.normalize("NFD");
  let result2 = "";
  for (let i = 0; i < str.length; i++) {
    const char = str[i];
    if (char >= "̀" && char <= "ͯ" || char >= "︠" && char <= "︣") continue;
    result2 += deburrMap.get(char) ?? char;
  }
  return result2;
}

// node_modules/es-toolkit/dist/string/escape.mjs
var htmlEscapes = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
};
function escape(str) {
  return str.replace(/[&<>"']/g, (match) => htmlEscapes[match]);
}

// node_modules/es-toolkit/dist/string/escapeRegExp.mjs
function escapeRegExp(str) {
  return str.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
}

// node_modules/es-toolkit/dist/string/kebabCase.mjs
function kebabCase(str) {
  return words(str).map((word) => word.toLowerCase()).join("-");
}

// node_modules/es-toolkit/dist/string/lowerCase.mjs
function lowerCase(str) {
  return words(str).map((word) => word.toLowerCase()).join(" ");
}

// node_modules/es-toolkit/dist/string/lowerFirst.mjs
function lowerFirst(str) {
  return str.substring(0, 1).toLowerCase() + str.substring(1);
}

// node_modules/es-toolkit/dist/string/pad.mjs
function pad(str, length, chars = " ") {
  return str.padStart(Math.floor((length - str.length) / 2) + str.length, chars).padEnd(length, chars);
}

// node_modules/es-toolkit/dist/string/trimEnd.mjs
function trimEnd(str, chars) {
  if (chars === void 0) return str.trimEnd();
  let endIndex = str.length;
  switch (typeof chars) {
    case "string":
      if (chars.length !== 1) throw new Error(`The 'chars' parameter should be a single character string.`);
      while (endIndex > 0 && str[endIndex - 1] === chars) endIndex--;
      break;
    case "object":
      while (endIndex > 0 && chars.includes(str[endIndex - 1])) endIndex--;
  }
  return str.substring(0, endIndex);
}

// node_modules/es-toolkit/dist/string/trimStart.mjs
function trimStart(str, chars) {
  if (chars === void 0) return str.trimStart();
  let startIndex = 0;
  switch (typeof chars) {
    case "string":
      while (startIndex < str.length && str[startIndex] === chars) startIndex++;
      break;
    case "object":
      while (startIndex < str.length && chars.includes(str[startIndex])) startIndex++;
  }
  return str.substring(startIndex);
}

// node_modules/es-toolkit/dist/string/trim.mjs
function trim(str, chars) {
  if (chars === void 0) return str.trim();
  return trimStart(trimEnd(str, chars), chars);
}

// node_modules/es-toolkit/dist/string/unescape.mjs
var htmlUnescapes = {
  "&amp;": "&",
  "&lt;": "<",
  "&gt;": ">",
  "&quot;": '"',
  "&#39;": "'"
};
function unescape(str) {
  return str.replace(/&(?:amp|lt|gt|quot|#(0+)?39);/g, (match) => htmlUnescapes[match] || "'");
}

// node_modules/es-toolkit/dist/string/upperCase.mjs
function upperCase(str) {
  const words$1 = words(str);
  let result2 = "";
  for (let i = 0; i < words$1.length; i++) {
    result2 += words$1[i].toUpperCase();
    if (i < words$1.length - 1) result2 += " ";
  }
  return result2;
}

// node_modules/es-toolkit/dist/string/upperFirst.mjs
function upperFirst(str) {
  return str.substring(0, 1).toUpperCase() + str.substring(1);
}

// node_modules/es-toolkit/dist/compat/array/castArray.mjs
function castArray(value) {
  if (arguments.length === 0) return [];
  return Array.isArray(value) ? value : [value];
}

// node_modules/es-toolkit/dist/compat/predicate/isArrayLike.mjs
function isArrayLike(value) {
  return value != null && typeof value !== "function" && isLength(value.length);
}

// node_modules/es-toolkit/dist/compat/_internal/toArray.mjs
function toArray(value) {
  return Array.isArray(value) ? value : Array.from(value);
}

// node_modules/es-toolkit/dist/compat/array/chunk.mjs
function chunk2(arr, size2 = 1) {
  size2 = Math.max(Math.floor(size2), 0);
  if (size2 === 0 || !isArrayLike(arr)) return [];
  return chunk(toArray(arr), size2);
}

// node_modules/es-toolkit/dist/compat/array/compact.mjs
function compact2(arr) {
  if (!isArrayLike(arr)) return [];
  return compact(Array.from(arr));
}

// node_modules/es-toolkit/dist/compat/array/concat.mjs
function concat(...values2) {
  return flatten(values2);
}

// node_modules/es-toolkit/dist/compat/util/toString.mjs
function toString(value) {
  if (value == null) return "";
  if (typeof value === "string") return value;
  if (Array.isArray(value)) return value.map(toString).join(",");
  const result2 = String(value);
  if (result2 === "0" && Object.is(Number(value), -0)) return "-0";
  return result2;
}

// node_modules/es-toolkit/dist/compat/_internal/toKey.mjs
function toKey(value) {
  if (typeof value === "string" || typeof value === "symbol") return value;
  if (Object.is(value?.valueOf?.(), -0)) return "-0";
  return String(value);
}

// node_modules/es-toolkit/dist/compat/util/toPath.mjs
function toPath(deepKey) {
  if (Array.isArray(deepKey)) return deepKey.map(toKey);
  if (typeof deepKey === "symbol") return [deepKey];
  deepKey = toString(deepKey);
  const result2 = [];
  const length = deepKey.length;
  if (length === 0) return result2;
  let index = 0;
  let key2 = "";
  let quoteChar = "";
  let bracket = false;
  if (deepKey.charCodeAt(0) === 46) {
    result2.push("");
    index++;
  }
  while (index < length) {
    const char = deepKey[index];
    if (quoteChar) if (char === "\\" && index + 1 < length) {
      index++;
      key2 += deepKey[index];
    } else if (char === quoteChar) quoteChar = "";
    else key2 += char;
    else if (bracket) if (char === '"' || char === "'") quoteChar = char;
    else if (char === "]") {
      bracket = false;
      result2.push(key2);
      key2 = "";
    } else key2 += char;
    else if (char === "[") {
      bracket = true;
      if (key2) {
        result2.push(key2);
        key2 = "";
      }
    } else if (char === ".") {
      if (key2) {
        result2.push(key2);
        key2 = "";
      }
    } else key2 += char;
    index++;
  }
  if (key2) result2.push(key2);
  return result2;
}

// node_modules/es-toolkit/dist/compat/_internal/isDeepKey.mjs
function isDeepKey(key2) {
  switch (typeof key2) {
    case "number":
    case "symbol":
      return false;
    case "string":
      return key2.includes(".") || key2.includes("[") || key2.includes("]");
  }
}

// node_modules/es-toolkit/dist/compat/object/get.mjs
function get(object, path, defaultValue) {
  if (object == null) return defaultValue;
  switch (typeof path) {
    case "string": {
      if (isUnsafeProperty(path)) return defaultValue;
      const result2 = object[path];
      if (result2 === void 0) if (isDeepKey(path)) return get(object, toPath(path), defaultValue);
      else return defaultValue;
      return result2;
    }
    case "number":
    case "symbol": {
      if (typeof path === "number") path = toKey(path);
      const result2 = object[path];
      if (result2 === void 0) return defaultValue;
      return result2;
    }
    default: {
      if (Array.isArray(path)) return getWithPath(object, path, defaultValue);
      if (Object.is(path?.valueOf(), -0)) path = "-0";
      else path = String(path);
      if (isUnsafeProperty(path)) return defaultValue;
      const result2 = object[path];
      if (result2 === void 0) return defaultValue;
      return result2;
    }
  }
}
function getWithPath(object, path, defaultValue) {
  if (path.length === 0) return defaultValue;
  let current = object;
  for (let index = 0; index < path.length; index++) {
    if (current == null) return defaultValue;
    if (isUnsafeProperty(path[index])) return defaultValue;
    current = current[path[index]];
  }
  if (current === void 0) return defaultValue;
  return current;
}

// node_modules/es-toolkit/dist/compat/object/property.mjs
function property(path) {
  return function(object) {
    return get(object, path);
  };
}

// node_modules/es-toolkit/dist/compat/predicate/isObject.mjs
function isObject(value) {
  return value !== null && (typeof value === "object" || typeof value === "function");
}

// node_modules/es-toolkit/dist/compat/predicate/isMatchWith.mjs
function isMatchWith(target, source, compare) {
  if (typeof compare !== "function") return isMatchWith(target, source, () => void 0);
  return isMatchWithInternal(target, source, function doesMatch(objValue, srcValue, key2, object, source2, stack) {
    const isEqual2 = compare(objValue, srcValue, key2, object, source2, stack);
    if (isEqual2 !== void 0) return Boolean(isEqual2);
    return isMatchWithInternal(objValue, srcValue, doesMatch, stack);
  }, /* @__PURE__ */ new Map());
}
function isMatchWithInternal(target, source, compare, stack) {
  if (source === target) return true;
  switch (typeof source) {
    case "object":
      return isObjectMatch(target, source, compare, stack);
    case "function":
      if (Object.keys(source).length > 0) return isMatchWithInternal(target, { ...source }, compare, stack);
      return isEqualsSameValueZero(target, source);
    default:
      if (!isObject(target)) return isEqualsSameValueZero(target, source);
      if (typeof source === "string") return source === "";
      return true;
  }
}
function isObjectMatch(target, source, compare, stack) {
  if (source == null) return true;
  if (Array.isArray(source)) return isArrayMatch(target, source, compare, stack);
  if (source instanceof Map) return isMapMatch(target, source, compare, stack);
  if (source instanceof Set) return isSetMatch(target, source, compare, stack);
  const keys2 = Object.keys(source);
  if (target == null || isPrimitive(target)) return keys2.length === 0;
  if (keys2.length === 0) return true;
  if (stack?.has(source)) return stack.get(source) === target;
  stack?.set(source, target);
  try {
    for (let i = 0; i < keys2.length; i++) {
      const key2 = keys2[i];
      if (!isPrimitive(target) && !(key2 in target)) return false;
      if (source[key2] === void 0 && target[key2] !== void 0) return false;
      if (source[key2] === null && target[key2] !== null) return false;
      if (!compare(target[key2], source[key2], key2, target, source, stack)) return false;
    }
    return true;
  } finally {
    stack?.delete(source);
  }
}
function isMapMatch(target, source, compare, stack) {
  if (source.size === 0) return true;
  if (!(target instanceof Map)) return false;
  for (const [key2, sourceValue] of source.entries()) if (compare(target.get(key2), sourceValue, key2, target, source, stack) === false) return false;
  return true;
}
function isArrayMatch(target, source, compare, stack) {
  if (source.length === 0) return true;
  if (!Array.isArray(target)) return false;
  const countedIndex = /* @__PURE__ */ new Set();
  for (let i = 0; i < source.length; i++) {
    const sourceItem = source[i];
    let found = false;
    for (let j = 0; j < target.length; j++) {
      if (countedIndex.has(j)) continue;
      const targetItem = target[j];
      let matches2 = false;
      if (compare(targetItem, sourceItem, i, target, source, stack)) matches2 = true;
      if (matches2) {
        countedIndex.add(j);
        found = true;
        break;
      }
    }
    if (!found) return false;
  }
  return true;
}
function isSetMatch(target, source, compare, stack) {
  if (source.size === 0) return true;
  if (!(target instanceof Set)) return false;
  return isArrayMatch([...target], [...source], compare, stack);
}

// node_modules/es-toolkit/dist/compat/predicate/isMatch.mjs
function isMatch(target, source) {
  return isMatchWith(target, source, () => void 0);
}

// node_modules/es-toolkit/dist/compat/predicate/matches.mjs
function matches(source) {
  source = cloneDeep(source);
  return (target) => {
    return isMatch(target, source);
  };
}

// node_modules/es-toolkit/dist/compat/object/cloneDeepWith.mjs
function cloneDeepWith2(obj, customizer) {
  return cloneDeepWith(obj, (value, key2, object, stack) => {
    const cloned = customizer?.(value, key2, object, stack);
    if (cloned !== void 0) return cloned;
    if (typeof obj !== "object") return;
    if (getTag(obj) === "[object Object]" && typeof obj.constructor !== "function") {
      const result2 = {};
      stack.set(obj, result2);
      copyProperties(result2, obj, object, stack);
      return result2;
    }
    switch (Object.prototype.toString.call(obj)) {
      case numberTag:
      case stringTag:
      case booleanTag: {
        const result2 = new obj.constructor(obj?.valueOf());
        copyProperties(result2, obj);
        return result2;
      }
      case argumentsTag: {
        const result2 = {};
        copyProperties(result2, obj);
        result2.length = obj.length;
        result2[Symbol.iterator] = obj[Symbol.iterator];
        return result2;
      }
      default:
        return;
    }
  });
}

// node_modules/es-toolkit/dist/compat/object/cloneDeep.mjs
function cloneDeep2(obj) {
  return cloneDeepWith2(obj);
}

// node_modules/es-toolkit/dist/compat/predicate/isArguments.mjs
function isArguments(value) {
  return value !== null && typeof value === "object" && getTag(value) === "[object Arguments]";
}

// node_modules/es-toolkit/dist/compat/_internal/isIndex.mjs
var IS_UNSIGNED_INTEGER = /^(?:0|[1-9]\d*)$/;
function isIndex(value, length = Number.MAX_SAFE_INTEGER) {
  switch (typeof value) {
    case "number":
      return Number.isInteger(value) && value >= 0 && value < length;
    case "symbol":
      return false;
    case "string":
      return IS_UNSIGNED_INTEGER.test(value);
  }
}

// node_modules/es-toolkit/dist/compat/object/has.mjs
function has(object, path) {
  let resolvedPath;
  if (Array.isArray(path)) resolvedPath = path;
  else if (typeof path === "string" && isDeepKey(path) && object?.[path] == null) resolvedPath = toPath(path);
  else resolvedPath = [path];
  if (resolvedPath.length === 0) return false;
  let current = object;
  for (let i = 0; i < resolvedPath.length; i++) {
    const key2 = resolvedPath[i];
    if (current == null || !Object.hasOwn(current, key2)) {
      if (!((Array.isArray(current) || isArguments(current)) && isIndex(key2) && key2 < current.length)) return false;
    }
    current = current[key2];
  }
  return true;
}

// node_modules/es-toolkit/dist/compat/predicate/matchesProperty.mjs
function matchesProperty(property2, source) {
  switch (typeof property2) {
    case "object":
      if (Object.is(property2?.valueOf(), -0)) property2 = "-0";
      break;
    case "number":
      property2 = toKey(property2);
      break;
  }
  source = cloneDeep2(source);
  return function(target) {
    const result2 = get(target, property2);
    if (result2 === void 0) return has(target, property2);
    if (source === void 0) return result2 === void 0;
    return isMatch(result2, source);
  };
}

// node_modules/es-toolkit/dist/compat/util/iteratee.mjs
function iteratee(value) {
  if (value == null) return identity;
  switch (typeof value) {
    case "function":
      return value;
    case "object":
      if (Array.isArray(value) && value.length === 2) return matchesProperty(value[0], value[1]);
      return matches(value);
    case "string":
    case "symbol":
    case "number":
      return property(value);
  }
}

// node_modules/es-toolkit/dist/compat/array/countBy.mjs
function countBy2(collection, iteratee$1) {
  if (collection == null) return {};
  const array = isArrayLike(collection) ? Array.from(collection) : Object.values(collection);
  const mapper = iteratee(iteratee$1 ?? void 0);
  const result2 = /* @__PURE__ */ Object.create(null);
  for (let i = 0; i < array.length; i++) {
    const item = array[i];
    const key2 = mapper(item);
    result2[key2] = (result2[key2] ?? 0) + 1;
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/predicate/isObjectLike.mjs
function isObjectLike(value) {
  return typeof value === "object" && value !== null;
}

// node_modules/es-toolkit/dist/compat/predicate/isArrayLikeObject.mjs
function isArrayLikeObject(value) {
  return isObjectLike(value) && isArrayLike(value);
}

// node_modules/es-toolkit/dist/compat/array/difference.mjs
function difference2(arr, ...values2) {
  if (!isArrayLikeObject(arr)) return [];
  const arr1 = toArray(arr);
  const arr2 = [];
  for (let i = 0; i < values2.length; i++) {
    const value = values2[i];
    if (isArrayLikeObject(value)) arr2.push(...Array.from(value));
  }
  return difference(arr1, arr2);
}

// node_modules/es-toolkit/dist/compat/array/last.mjs
function last2(array) {
  if (!isArrayLike(array)) return;
  return last(toArray(array));
}

// node_modules/es-toolkit/dist/compat/_internal/flattenArrayLike.mjs
function flattenArrayLike(values2) {
  const result2 = [];
  for (let i = 0; i < values2.length; i++) {
    const arrayLike = values2[i];
    if (!isArrayLikeObject(arrayLike)) continue;
    for (let j = 0; j < arrayLike.length; j++) result2.push(arrayLike[j]);
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/array/differenceBy.mjs
function differenceBy2(arr, ..._values) {
  if (!isArrayLikeObject(arr)) return [];
  const iteratee$1 = last2(_values);
  const values2 = flattenArrayLike(_values);
  if (isArrayLikeObject(iteratee$1)) return difference(Array.from(arr), values2);
  return differenceBy(Array.from(arr), values2, iteratee(iteratee$1));
}

// node_modules/es-toolkit/dist/compat/array/differenceWith.mjs
function differenceWith2(array, ...values2) {
  if (!isArrayLikeObject(array)) return [];
  const comparator = last2(values2);
  const flattenedValues = flattenArrayLike(values2);
  if (typeof comparator === "function") return differenceWith(Array.from(array), flattenedValues, comparator);
  return difference(Array.from(array), flattenedValues);
}

// node_modules/es-toolkit/dist/compat/array/drop.mjs
function drop2(collection, itemsCount = 1, guard) {
  if (!isArrayLike(collection)) return [];
  itemsCount = guard ? 1 : toInteger(itemsCount);
  return drop(toArray(collection), itemsCount);
}

// node_modules/es-toolkit/dist/compat/array/dropRight.mjs
function dropRight2(collection, itemsCount = 1, guard) {
  if (!isArrayLike(collection)) return [];
  itemsCount = guard ? 1 : toInteger(itemsCount);
  return dropRight(toArray(collection), itemsCount);
}

// node_modules/es-toolkit/dist/compat/array/dropRightWhile.mjs
function dropRightWhile2(arr, predicate = identity) {
  if (!isArrayLike(arr)) return [];
  return dropRightWhileImpl(Array.from(arr), predicate);
}
function dropRightWhileImpl(arr, predicate) {
  switch (typeof predicate) {
    case "function":
      return dropRightWhile(arr, (item, index, arr2) => Boolean(predicate(item, index, arr2)));
    case "object":
      if (Array.isArray(predicate) && predicate.length === 2) {
        const key2 = predicate[0];
        const value = predicate[1];
        return dropRightWhile(arr, matchesProperty(key2, value));
      } else return dropRightWhile(arr, matches(predicate));
    case "symbol":
    case "number":
    case "string":
      return dropRightWhile(arr, property(predicate));
  }
}

// node_modules/es-toolkit/dist/compat/array/dropWhile.mjs
function dropWhile2(arr, predicate = identity) {
  if (!isArrayLike(arr)) return [];
  return dropWhileImpl(toArray(arr), predicate);
}
function dropWhileImpl(arr, predicate) {
  switch (typeof predicate) {
    case "function":
      return dropWhile(arr, (item, index, arr2) => Boolean(predicate(item, index, arr2)));
    case "object":
      if (Array.isArray(predicate) && predicate.length === 2) {
        const key2 = predicate[0];
        const value = predicate[1];
        return dropWhile(arr, matchesProperty(key2, value));
      } else return dropWhile(arr, matches(predicate));
    case "number":
    case "symbol":
    case "string":
      return dropWhile(arr, property(predicate));
  }
}

// node_modules/es-toolkit/dist/compat/array/forEach.mjs
function forEach(collection, callback = identity) {
  if (!collection) return collection;
  const keys2 = isArrayLike(collection) || Array.isArray(collection) ? range(0, collection.length) : Object.keys(collection);
  for (let i = 0; i < keys2.length; i++) {
    const key2 = keys2[i];
    const value = collection[key2];
    if (callback(value, key2, collection) === false) break;
  }
  return collection;
}

// node_modules/es-toolkit/dist/compat/array/forEachRight.mjs
function forEachRight2(collection, callback = identity) {
  if (!collection) return collection;
  const keys2 = isArrayLike(collection) ? range(0, collection.length) : Object.keys(collection);
  for (let i = keys2.length - 1; i >= 0; i--) {
    const key2 = keys2[i];
    const value = collection[key2];
    if (callback(value, key2, collection) === false) break;
  }
  return collection;
}

// node_modules/es-toolkit/dist/compat/_internal/isIterateeCall.mjs
function isIterateeCall(value, index, object) {
  if (!isObject(object)) return false;
  if (typeof index === "number" && isArrayLike(object) && isIndex(index) && index < object.length || typeof index === "string" && index in object) return isEqualsSameValueZero(object[index], value);
  return false;
}

// node_modules/es-toolkit/dist/compat/array/every.mjs
function every(source, doesMatch, guard) {
  if (!source) return true;
  if (guard && isIterateeCall(source, doesMatch, guard)) doesMatch = void 0;
  if (!doesMatch) doesMatch = identity;
  let predicate;
  switch (typeof doesMatch) {
    case "function":
      predicate = doesMatch;
      break;
    case "object":
      if (Array.isArray(doesMatch) && doesMatch.length === 2) {
        const key2 = doesMatch[0];
        const value = doesMatch[1];
        predicate = matchesProperty(key2, value);
      } else predicate = matches(doesMatch);
      break;
    case "symbol":
    case "number":
    case "string":
      predicate = property(doesMatch);
  }
  if (!isArrayLike(source)) {
    const keys2 = Object.keys(source);
    for (let i = 0; i < keys2.length; i++) {
      const key2 = keys2[i];
      const value = source[key2];
      if (!predicate(value, key2, source)) return false;
    }
    return true;
  }
  for (let i = 0; i < source.length; i++) if (!predicate(source[i], i, source)) return false;
  return true;
}

// node_modules/es-toolkit/dist/compat/predicate/isString.mjs
function isString2(value) {
  return typeof value === "string" || value instanceof String;
}

// node_modules/es-toolkit/dist/compat/array/fill.mjs
function fill2(array, value, start2 = 0, end = array ? array.length : 0) {
  if (!isArrayLike(array)) return [];
  if (isString2(array)) return array;
  start2 = Math.floor(start2);
  end = Math.floor(end);
  if (!start2) start2 = 0;
  if (!end) end = 0;
  return fill(array, value, start2, end);
}

// node_modules/es-toolkit/dist/compat/array/filter.mjs
function filter(source, predicate = identity) {
  if (!source) return [];
  predicate = iteratee(predicate);
  if (!Array.isArray(source)) {
    const result3 = [];
    const keys2 = Object.keys(source);
    const length2 = isArrayLike(source) ? source.length : keys2.length;
    for (let i = 0; i < length2; i++) {
      const key2 = keys2[i];
      const value = source[key2];
      if (predicate(value, key2, source)) result3.push(value);
    }
    return result3;
  }
  const result2 = [];
  const length = source.length;
  for (let i = 0; i < length; i++) {
    const value = source[i];
    if (predicate(value, i, source)) result2.push(value);
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/array/find.mjs
function find(source, _doesMatch = identity, fromIndex = 0) {
  if (!source) return;
  if (fromIndex < 0) fromIndex = Math.max(source.length + fromIndex, 0);
  const doesMatch = iteratee(_doesMatch);
  if (!Array.isArray(source)) {
    const keys2 = Object.keys(source);
    for (let i = fromIndex; i < keys2.length; i++) {
      const key2 = keys2[i];
      const value = source[key2];
      if (doesMatch(value, key2, source)) return value;
    }
    return;
  }
  return source.slice(fromIndex).find(doesMatch);
}

// node_modules/es-toolkit/dist/compat/function/identity.mjs
function identity2(x) {
  return x;
}

// node_modules/es-toolkit/dist/compat/array/findIndex.mjs
function findIndex(arr, doesMatch = identity2, fromIndex = 0) {
  if (!arr) return -1;
  if (fromIndex < 0) fromIndex = Math.max(arr.length + fromIndex, 0);
  const subArray = Array.from(arr).slice(fromIndex);
  let index = -1;
  switch (typeof doesMatch) {
    case "function":
      index = subArray.findIndex(doesMatch);
      break;
    case "object":
      if (Array.isArray(doesMatch) && doesMatch.length === 2) {
        const key2 = doesMatch[0];
        const value = doesMatch[1];
        index = subArray.findIndex(matchesProperty(key2, value));
      } else index = subArray.findIndex(matches(doesMatch));
      break;
    case "number":
    case "symbol":
    case "string":
      index = subArray.findIndex(property(doesMatch));
  }
  return index === -1 ? -1 : index + fromIndex;
}

// node_modules/es-toolkit/dist/compat/array/findLast.mjs
function findLast(source, _doesMatch = identity, fromIndex) {
  if (!source) return;
  const length = Array.isArray(source) ? source.length : Object.keys(source).length;
  fromIndex = toInteger(fromIndex ?? length - 1);
  if (fromIndex < 0) fromIndex = Math.max(length + fromIndex, 0);
  else fromIndex = Math.min(fromIndex, length - 1);
  const doesMatch = iteratee(_doesMatch);
  if (!Array.isArray(source)) {
    const keys2 = Object.keys(source);
    for (let i = fromIndex; i >= 0; i--) {
      const key2 = keys2[i];
      const value = source[key2];
      if (doesMatch(value, key2, source)) return value;
    }
    return;
  }
  return source.slice(0, fromIndex + 1).findLast(doesMatch);
}

// node_modules/es-toolkit/dist/compat/array/findLastIndex.mjs
function findLastIndex(arr, doesMatch = identity, fromIndex = arr ? arr.length - 1 : 0) {
  if (!arr) return -1;
  if (fromIndex < 0) fromIndex = Math.max(arr.length + fromIndex, 0);
  else fromIndex = Math.min(fromIndex, arr.length - 1);
  const subArray = toArray(arr).slice(0, fromIndex + 1);
  switch (typeof doesMatch) {
    case "function":
      return subArray.findLastIndex(doesMatch);
    case "object":
      if (Array.isArray(doesMatch) && doesMatch.length === 2) {
        const key2 = doesMatch[0];
        const value = doesMatch[1];
        return subArray.findLastIndex(matchesProperty(key2, value));
      } else return subArray.findLastIndex(matches(doesMatch));
    case "number":
    case "symbol":
    case "string":
      return subArray.findLastIndex(property(doesMatch));
  }
}

// node_modules/es-toolkit/dist/compat/array/head.mjs
function head2(arr) {
  if (!isArrayLike(arr)) return;
  return head(toArray(arr));
}

// node_modules/es-toolkit/dist/compat/array/flatten.mjs
function flatten2(value, depth = 1) {
  const result2 = [];
  const flooredDepth = Math.floor(depth);
  if (!isArrayLike(value)) return result2;
  const recursive = (arr, currentDepth) => {
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i];
      if (currentDepth < flooredDepth && (Array.isArray(item) || Boolean(item?.[Symbol.isConcatSpreadable]) || item !== null && typeof item === "object" && Object.prototype.toString.call(item) === "[object Arguments]")) if (Array.isArray(item)) recursive(item, currentDepth + 1);
      else recursive(Array.from(item), currentDepth + 1);
      else result2.push(item);
    }
  };
  recursive(Array.from(value), 0);
  return result2;
}

// node_modules/es-toolkit/dist/compat/array/flattenDepth.mjs
function flattenDepth(array, depth = 1) {
  return flatten2(array, depth);
}

// node_modules/es-toolkit/dist/compat/array/map.mjs
function map(collection, _iteratee) {
  if (!collection) return [];
  const keys2 = isArrayLike(collection) || Array.isArray(collection) ? range(0, collection.length) : Object.keys(collection);
  const iteratee$1 = iteratee(_iteratee ?? identity);
  const result2 = new Array(keys2.length);
  for (let i = 0; i < keys2.length; i++) {
    const key2 = keys2[i];
    const value = collection[key2];
    result2[i] = iteratee$1(value, key2, collection);
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/array/flatMap.mjs
function flatMap2(collection, iteratee2) {
  if (isNil(collection)) return [];
  return flattenDepth(isNil(iteratee2) ? map(collection) : map(collection, iteratee2), 1);
}

// node_modules/es-toolkit/dist/compat/array/flatMapDepth.mjs
function flatMapDepth(collection, iteratee$1 = identity, depth = 1) {
  if (collection == null) return [];
  return flatten2(map(collection, iteratee(iteratee$1)), depth);
}

// node_modules/es-toolkit/dist/compat/array/flatMapDeep.mjs
function flatMapDeep2(collection, iteratee2) {
  return flatMapDepth(collection, iteratee2, Infinity);
}

// node_modules/es-toolkit/dist/compat/array/flattenDeep.mjs
function flattenDeep2(value) {
  return flattenDepth(value, Infinity);
}

// node_modules/es-toolkit/dist/compat/array/groupBy.mjs
function groupBy2(source, _getKeyFromItem) {
  if (source == null) return {};
  return groupBy(isArrayLike(source) ? Array.from(source) : Object.values(source), iteratee(_getKeyFromItem ?? identity));
}

// node_modules/es-toolkit/dist/compat/array/includes.mjs
function includes(source, target, fromIndex, guard) {
  if (source == null) return false;
  if (guard || !fromIndex) fromIndex = 0;
  else fromIndex = toInteger(fromIndex);
  if (isString2(source)) {
    if (fromIndex > source.length || target instanceof RegExp) return false;
    if (fromIndex < 0) fromIndex = Math.max(0, source.length + fromIndex);
    return source.includes(target, fromIndex);
  }
  if (Array.isArray(source)) return source.includes(target, fromIndex);
  const keys2 = Object.keys(source);
  if (fromIndex < 0) fromIndex = Math.max(0, keys2.length + fromIndex);
  for (let i = fromIndex; i < keys2.length; i++) if (isEqualsSameValueZero(Reflect.get(source, keys2[i]), target)) return true;
  return false;
}

// node_modules/es-toolkit/dist/compat/array/indexOf.mjs
function indexOf(array, searchElement, fromIndex) {
  if (!isArrayLike(array)) return -1;
  if (Number.isNaN(searchElement)) {
    fromIndex = fromIndex ?? 0;
    if (fromIndex < 0) fromIndex = Math.max(0, array.length + fromIndex);
    for (let i = fromIndex; i < array.length; i++) if (Number.isNaN(array[i])) return i;
    return -1;
  }
  return Array.from(array).indexOf(searchElement, fromIndex);
}

// node_modules/es-toolkit/dist/compat/array/initial.mjs
function initial2(arr) {
  if (!isArrayLike(arr)) return [];
  return initial(Array.from(arr));
}

// node_modules/es-toolkit/dist/compat/array/intersection.mjs
function intersection2(...arrays) {
  if (arrays.length === 0) return [];
  if (!isArrayLikeObject(arrays[0])) return [];
  let result2 = uniq(Array.from(arrays[0]));
  for (let i = 1; i < arrays.length; i++) {
    const array = arrays[i];
    if (!isArrayLikeObject(array)) return [];
    result2 = intersection(result2, Array.from(array));
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/array/intersectionBy.mjs
function intersectionBy2(array, ...values2) {
  if (!isArrayLikeObject(array)) return [];
  const lastValue = last(values2);
  if (lastValue === void 0) return Array.from(array);
  let result2 = uniq(Array.from(array));
  const count = isArrayLikeObject(lastValue) ? values2.length : values2.length - 1;
  for (let i = 0; i < count; ++i) {
    const value = values2[i];
    if (!isArrayLikeObject(value)) return [];
    if (isArrayLikeObject(lastValue)) result2 = intersectionBy(result2, Array.from(value), identity);
    else if (typeof lastValue === "function") result2 = intersectionBy(result2, Array.from(value), (value2) => lastValue(value2));
    else if (typeof lastValue === "string") result2 = intersectionBy(result2, Array.from(value), property(lastValue));
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/array/uniq.mjs
function uniq2(arr) {
  if (!isArrayLike(arr)) return [];
  return uniq(Array.from(arr));
}

// node_modules/es-toolkit/dist/compat/array/intersectionWith.mjs
function intersectionWith2(firstArr, ...otherArrs) {
  if (firstArr == null) return [];
  const _comparator = last2(otherArrs);
  let comparator = isEqualsSameValueZero;
  let uniq$1 = uniq2;
  if (typeof _comparator === "function") {
    comparator = _comparator;
    uniq$1 = uniqPreserve0;
    otherArrs.pop();
  }
  let result2 = uniq$1(Array.from(firstArr));
  for (let i = 0; i < otherArrs.length; ++i) {
    const otherArr = otherArrs[i];
    if (otherArr == null) return [];
    result2 = intersectionWith(result2, Array.from(otherArr), comparator);
  }
  return result2;
}
function uniqPreserve0(arr) {
  const result2 = [];
  const added = /* @__PURE__ */ new Set();
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    if (added.has(item)) continue;
    result2.push(item);
    added.add(item);
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/array/invokeMap.mjs
function invokeMap(collection, path, ...args) {
  if (isNil(collection)) return [];
  const values2 = isArrayLike(collection) ? Array.from(collection) : Object.values(collection);
  const result2 = [];
  for (let i = 0; i < values2.length; i++) {
    const value = values2[i];
    if (isFunction(path)) {
      result2.push(path.apply(value, args));
      continue;
    }
    const method2 = get(value, path);
    let thisContext = value;
    if (Array.isArray(path)) {
      const pathExceptLast = path.slice(0, -1);
      if (pathExceptLast.length > 0) thisContext = get(value, pathExceptLast);
    } else if (typeof path === "string" && path.includes(".")) thisContext = get(value, path.split(".").slice(0, -1).join("."));
    result2.push(method2 == null ? void 0 : method2.apply(thisContext, args));
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/array/join.mjs
function join(array, separator) {
  if (!isArrayLike(array)) return "";
  return Array.from(array).join(separator);
}

// node_modules/es-toolkit/dist/compat/array/reduce.mjs
function reduce(collection, iteratee2 = identity, accumulator) {
  if (!collection) return accumulator;
  let keys2;
  let startIndex = 0;
  if (isArrayLike(collection)) {
    keys2 = range(0, collection.length);
    if (accumulator == null && collection.length > 0) {
      accumulator = collection[0];
      startIndex += 1;
    }
  } else {
    keys2 = Object.keys(collection);
    if (accumulator == null) {
      accumulator = collection[keys2[0]];
      startIndex += 1;
    }
  }
  for (let i = startIndex; i < keys2.length; i++) {
    const key2 = keys2[i];
    const value = collection[key2];
    accumulator = iteratee2(accumulator, value, key2, collection);
  }
  return accumulator;
}

// node_modules/es-toolkit/dist/compat/array/keyBy.mjs
function keyBy2(collection, iteratee$1) {
  if (!isArrayLike(collection) && !isObjectLike(collection)) return {};
  const keyFn = iteratee(iteratee$1 ?? identity);
  return reduce(collection, (result2, value) => {
    const key2 = keyFn(value);
    result2[key2] = value;
    return result2;
  }, {});
}

// node_modules/es-toolkit/dist/compat/array/lastIndexOf.mjs
function lastIndexOf(array, searchElement, fromIndex) {
  if (!isArrayLike(array) || array.length === 0) return -1;
  const length = array.length;
  let index = fromIndex ?? length - 1;
  if (fromIndex != null) index = index < 0 ? Math.max(length + index, 0) : Math.min(index, length - 1);
  if (Number.isNaN(searchElement)) {
    for (let i = index; i >= 0; i--) if (Number.isNaN(array[i])) return i;
  }
  return Array.from(array).lastIndexOf(searchElement, index);
}

// node_modules/es-toolkit/dist/compat/array/nth.mjs
function nth(array, n = 0) {
  if (!isArrayLikeObject(array) || array.length === 0) return;
  n = toInteger(n);
  if (n < 0) n += array.length;
  return array[n];
}

// node_modules/es-toolkit/dist/compat/_internal/compareValues.mjs
function getPriority(a) {
  if (typeof a === "symbol") return 1;
  if (a === null) return 2;
  if (a === void 0) return 3;
  if (a !== a) return 4;
  return 0;
}
var compareValues2 = (a, b, order) => {
  if (a !== b) {
    const aPriority = getPriority(a);
    const bPriority = getPriority(b);
    if (aPriority === bPriority && aPriority === 0) {
      if (a < b) return order === "desc" ? 1 : -1;
      if (a > b) return order === "desc" ? -1 : 1;
    }
    return order === "desc" ? bPriority - aPriority : aPriority - bPriority;
  }
  return 0;
};

// node_modules/es-toolkit/dist/compat/_internal/isKey.mjs
var regexIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
var regexIsPlainProp = /^\w*$/;
function isKey(value, object) {
  if (Array.isArray(value)) return false;
  if (typeof value === "number" || typeof value === "boolean" || value == null || isSymbol(value)) return true;
  return typeof value === "string" && (regexIsPlainProp.test(value) || !regexIsDeepProp.test(value)) || object != null && Object.hasOwn(object, value);
}

// node_modules/es-toolkit/dist/compat/array/orderBy.mjs
function orderBy2(collection, criteria, orders, guard) {
  if (collection == null) return [];
  orders = guard ? void 0 : orders;
  if (!Array.isArray(collection)) collection = Object.values(collection);
  if (!Array.isArray(criteria)) criteria = criteria == null ? [null] : [criteria];
  if (criteria.length === 0) criteria = [null];
  if (!Array.isArray(orders)) orders = orders == null ? [] : [orders];
  orders = orders.map((order) => String(order));
  const getValueByNestedPath = (object, path) => {
    let target = object;
    for (let i = 0; i < path.length && target != null; ++i) target = target[path[i]];
    return target;
  };
  const getValueByCriterion = (criterion, object) => {
    if (object == null || criterion == null) return object;
    if (typeof criterion === "object" && "key" in criterion) {
      if (Object.hasOwn(object, criterion.key)) return object[criterion.key];
      return getValueByNestedPath(object, criterion.path);
    }
    if (typeof criterion === "function") return criterion(object);
    if (Array.isArray(criterion)) return getValueByNestedPath(object, criterion);
    if (typeof object === "object") return object[criterion];
    return object;
  };
  const preparedCriteria = criteria.map((criterion) => {
    if (Array.isArray(criterion) && criterion.length === 1) criterion = criterion[0];
    if (criterion == null || typeof criterion === "function" || Array.isArray(criterion) || isKey(criterion)) return criterion;
    return {
      key: criterion,
      path: toPath(criterion)
    };
  });
  return collection.map((item) => ({
    original: item,
    criteria: preparedCriteria.map((criterion) => getValueByCriterion(criterion, item))
  })).slice().sort((a, b) => {
    for (let i = 0; i < preparedCriteria.length; i++) {
      const comparedResult = compareValues2(a.criteria[i], b.criteria[i], orders[i]);
      if (comparedResult !== 0) return comparedResult;
    }
    return 0;
  }).map((item) => item.original);
}

// node_modules/es-toolkit/dist/compat/array/partition.mjs
function partition2(source, predicate = identity) {
  if (!source) return [[], []];
  const collection = isArrayLike(source) ? source : Object.values(source);
  predicate = iteratee(predicate);
  const matched = [];
  const unmatched = [];
  for (let i = 0; i < collection.length; i++) {
    const value = collection[i];
    if (predicate(value)) matched.push(value);
    else unmatched.push(value);
  }
  return [matched, unmatched];
}

// node_modules/es-toolkit/dist/compat/array/pull.mjs
function pull2(arr, ...valuesToRemove) {
  return pull(arr, valuesToRemove);
}

// node_modules/es-toolkit/dist/compat/array/pullAll.mjs
function pullAll(arr, valuesToRemove = []) {
  return pull(arr, Array.from(valuesToRemove));
}

// node_modules/es-toolkit/dist/compat/array/pullAllBy.mjs
function pullAllBy(arr, valuesToRemove, _getValue) {
  const getValue = iteratee(_getValue);
  const valuesSet = new Set(Array.from(valuesToRemove).map((x) => getValue(x)));
  let resultIndex = 0;
  for (let i = 0; i < arr.length; i++) {
    const value = getValue(arr[i]);
    if (valuesSet.has(value)) continue;
    if (!Object.hasOwn(arr, i)) {
      delete arr[resultIndex++];
      continue;
    }
    arr[resultIndex++] = arr[i];
  }
  arr.length = resultIndex;
  return arr;
}

// node_modules/es-toolkit/dist/compat/_internal/copyArray.mjs
function copyArray(source, array) {
  const length = source.length;
  if (array == null) array = Array(length);
  for (let i = 0; i < length; i++) array[i] = source[i];
  return array;
}

// node_modules/es-toolkit/dist/compat/array/pullAllWith.mjs
function pullAllWith(array, values2, comparator) {
  if (array?.length == null || values2?.length == null) return array;
  if (array === values2) values2 = copyArray(values2);
  let resultLength = 0;
  if (comparator == null) comparator = (a, b) => isEqualsSameValueZero(a, b);
  const valuesArray = Array.isArray(values2) ? values2 : Array.from(values2);
  const hasUndefined = valuesArray.includes(void 0);
  for (let i = 0; i < array.length; i++) {
    if (i in array) {
      if (!valuesArray.some((value) => comparator(array[i], value))) array[resultLength++] = array[i];
      continue;
    }
    if (!hasUndefined) delete array[resultLength++];
  }
  array.length = resultLength;
  return array;
}

// node_modules/es-toolkit/dist/compat/object/at.mjs
function at2(object, ...paths) {
  if (paths.length === 0) return [];
  const allPaths = [];
  for (let i = 0; i < paths.length; i++) {
    const path = paths[i];
    if (!isArrayLike(path) || isString2(path)) {
      allPaths.push(path);
      continue;
    }
    for (let j = 0; j < path.length; j++) allPaths.push(path[j]);
  }
  const result2 = [];
  for (let i = 0; i < allPaths.length; i++) result2.push(get(object, allPaths[i]));
  return result2;
}

// node_modules/es-toolkit/dist/compat/object/unset.mjs
function unset(obj, path) {
  if (obj == null) return true;
  switch (typeof path) {
    case "symbol":
    case "number":
    case "object":
      if (Array.isArray(path)) return unsetWithPath(obj, path);
      if (typeof path === "number") path = toKey(path);
      else if (typeof path === "object") if (Object.is(path?.valueOf(), -0)) path = "-0";
      else path = String(path);
      if (isUnsafeProperty(path)) return false;
      if (obj?.[path] === void 0) return true;
      try {
        delete obj[path];
        return true;
      } catch {
        return false;
      }
    case "string":
      if (obj?.[path] === void 0 && isDeepKey(path)) return unsetWithPath(obj, toPath(path));
      if (isUnsafeProperty(path)) return false;
      try {
        delete obj[path];
        return true;
      } catch {
        return false;
      }
  }
}
function unsetWithPath(obj, path) {
  const parent = path.length === 1 ? obj : get(obj, path.slice(0, -1));
  const lastKey = path[path.length - 1];
  if (parent?.[lastKey] === void 0) return true;
  if (isUnsafeProperty(lastKey)) return false;
  try {
    delete parent[lastKey];
    return true;
  } catch {
    return false;
  }
}

// node_modules/es-toolkit/dist/compat/array/pullAt.mjs
function pullAt2(array, ..._indices) {
  const indices = flattenDepth(_indices, 1);
  if (!array) return Array(indices.length);
  const result2 = at2(array, indices);
  const indicesToPull = indices.map((index) => isIndex(index, array.length) ? Number(index) : index).sort((a, b) => b - a);
  for (const index of new Set(indicesToPull)) {
    if (isIndex(index, array.length)) {
      Array.prototype.splice.call(array, index, 1);
      continue;
    }
    if (isKey(index, array)) {
      delete array[toKey(index)];
      continue;
    }
    unset(array, isArray(index) ? index : toPath(index));
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/array/reduceRight.mjs
function reduceRight(collection, iteratee2 = identity, accumulator) {
  if (!collection) return accumulator;
  let keys2;
  let startIndex;
  if (isArrayLike(collection)) {
    keys2 = range(0, collection.length).reverse();
    if (accumulator == null && collection.length > 0) {
      accumulator = collection[collection.length - 1];
      startIndex = 1;
    } else startIndex = 0;
  } else {
    keys2 = Object.keys(collection).reverse();
    if (accumulator == null) {
      accumulator = collection[keys2[0]];
      startIndex = 1;
    } else startIndex = 0;
  }
  for (let i = startIndex; i < keys2.length; i++) {
    const key2 = keys2[i];
    const value = collection[key2];
    accumulator = iteratee2(accumulator, value, key2, collection);
  }
  return accumulator;
}

// node_modules/es-toolkit/dist/compat/function/negate.mjs
function negate2(func) {
  if (typeof func !== "function") throw new TypeError("Expected a function");
  return function(...args) {
    return !func.apply(this, args);
  };
}

// node_modules/es-toolkit/dist/compat/array/reject.mjs
function reject(source, predicate = identity) {
  return filter(source, negate2(iteratee(predicate)));
}

// node_modules/es-toolkit/dist/compat/array/remove.mjs
function remove2(arr, shouldRemoveElement = identity) {
  return remove(arr, iteratee(shouldRemoveElement));
}

// node_modules/es-toolkit/dist/compat/array/reverse.mjs
function reverse(array) {
  if (array == null) return array;
  return array.reverse();
}

// node_modules/es-toolkit/dist/compat/array/sample.mjs
function sample2(collection) {
  if (collection == null) return;
  if (isArrayLike(collection)) return sample(toArray(collection));
  return sample(Object.values(collection));
}

// node_modules/es-toolkit/dist/compat/math/clamp.mjs
function clamp2(value, bound1, bound2) {
  if (bound2 === void 0) {
    bound2 = bound1;
    bound1 = void 0;
  }
  if (bound2 !== void 0) {
    bound2 = toNumber(bound2);
    value = Math.min(value, Number.isNaN(bound2) ? 0 : bound2);
  }
  if (bound1 !== void 0) {
    bound1 = toNumber(bound1);
    value = Math.max(value, Number.isNaN(bound1) ? 0 : bound1);
  }
  return value;
}

// node_modules/es-toolkit/dist/compat/predicate/isMap.mjs
function isMap2(value) {
  return isMap(value);
}

// node_modules/es-toolkit/dist/compat/util/toArray.mjs
function toArray2(value) {
  if (value == null) return [];
  if (isArrayLike(value) || isMap2(value)) return Array.from(value);
  if (typeof value === "object") return Object.values(value);
  return [];
}

// node_modules/es-toolkit/dist/compat/array/sampleSize.mjs
function sampleSize2(collection, size2, guard) {
  const arrayCollection = toArray2(collection);
  if (guard ? isIterateeCall(collection, size2, guard) : size2 === void 0) size2 = 1;
  else size2 = clamp2(toInteger(size2), 0, arrayCollection.length);
  return sampleSize(arrayCollection, size2);
}

// node_modules/es-toolkit/dist/compat/object/values.mjs
function values(object) {
  if (object == null) return [];
  return Object.values(object);
}

// node_modules/es-toolkit/dist/compat/predicate/isNil.mjs
function isNil2(x) {
  return x == null;
}

// node_modules/es-toolkit/dist/compat/array/shuffle.mjs
function shuffle2(collection) {
  if (isNil2(collection)) return [];
  if (isArray(collection)) return shuffle(collection);
  if (isArrayLike(collection)) return shuffle(Array.from(collection));
  if (isObjectLike(collection)) return shuffle(values(collection));
  return [];
}

// node_modules/es-toolkit/dist/compat/array/size.mjs
function size(target) {
  if (isNil(target)) return 0;
  if (target instanceof Map || target instanceof Set) return target.size;
  return Object.keys(target).length;
}

// node_modules/es-toolkit/dist/compat/array/slice.mjs
function slice(array, start2, end) {
  if (!isArrayLike(array)) return [];
  const length = array.length;
  if (end === void 0) end = length;
  else if (typeof end !== "number" && isIterateeCall(array, start2, end)) {
    start2 = 0;
    end = length;
  }
  start2 = toInteger(start2);
  end = toInteger(end);
  if (start2 < 0) start2 = Math.max(length + start2, 0);
  else start2 = Math.min(start2, length);
  if (end < 0) end = Math.max(length + end, 0);
  else end = Math.min(end, length);
  const resultLength = Math.max(end - start2, 0);
  const result2 = new Array(resultLength);
  for (let i = 0; i < resultLength; ++i) result2[i] = array[start2 + i];
  return result2;
}

// node_modules/es-toolkit/dist/compat/array/some.mjs
function some(source, predicate, guard) {
  if (!source) return false;
  if (guard != null) predicate = void 0;
  if (predicate == null) predicate = identity;
  const values2 = Array.isArray(source) ? source : Object.values(source);
  switch (typeof predicate) {
    case "function":
      if (!Array.isArray(source)) {
        const keys2 = Object.keys(source);
        for (let i = 0; i < keys2.length; i++) {
          const key2 = keys2[i];
          const value = source[key2];
          if (predicate(value, key2, source)) return true;
        }
        return false;
      }
      for (let i = 0; i < source.length; i++) if (predicate(source[i], i, source)) return true;
      return false;
    case "object":
      if (Array.isArray(predicate) && predicate.length === 2) {
        const key2 = predicate[0];
        const value = predicate[1];
        const matchFunc = matchesProperty(key2, value);
        if (Array.isArray(source)) {
          for (let i = 0; i < source.length; i++) if (matchFunc(source[i])) return true;
          return false;
        }
        return values2.some(matchFunc);
      } else {
        const matchFunc = matches(predicate);
        if (Array.isArray(source)) {
          for (let i = 0; i < source.length; i++) if (matchFunc(source[i])) return true;
          return false;
        }
        return values2.some(matchFunc);
      }
    case "number":
    case "symbol":
    case "string": {
      const propFunc = property(predicate);
      if (Array.isArray(source)) {
        for (let i = 0; i < source.length; i++) if (propFunc(source[i])) return true;
        return false;
      }
      return values2.some(propFunc);
    }
  }
}

// node_modules/es-toolkit/dist/compat/array/sortBy.mjs
function sortBy2(collection, ...criteria) {
  const length = criteria.length;
  if (length > 1 && isIterateeCall(collection, criteria[0], criteria[1])) criteria = [];
  else if (length > 2 && isIterateeCall(criteria[0], criteria[1], criteria[2])) criteria = [criteria[0]];
  return orderBy2(collection, flatten(criteria), ["asc"]);
}

// node_modules/es-toolkit/dist/compat/predicate/isNaN.mjs
function isNaN(value) {
  return Number.isNaN(value);
}

// node_modules/es-toolkit/dist/compat/array/sortedIndexBy.mjs
var MAX_ARRAY_INDEX = 4294967294;
function sortedIndexBy(array, value, iteratee$1 = identity2, retHighest) {
  if (isNil2(array) || array.length === 0) return 0;
  let low = 0;
  let high = array.length;
  const iterateeFunction = iteratee(iteratee$1);
  const transformedValue = iterateeFunction(value);
  const valIsNaN = isNaN(transformedValue);
  const valIsNull = isNull(transformedValue);
  const valIsSymbol = isSymbol(transformedValue);
  const valIsUndefined = isUndefined(transformedValue);
  while (low < high) {
    let setLow;
    const mid = Math.floor((low + high) / 2);
    const computed2 = iterateeFunction(array[mid]);
    const othIsDefined = !isUndefined(computed2);
    const othIsNull = isNull(computed2);
    const othIsReflexive = !isNaN(computed2);
    const othIsSymbol = isSymbol(computed2);
    if (valIsNaN) setLow = retHighest || othIsReflexive;
    else if (valIsUndefined) setLow = othIsReflexive && (retHighest || othIsDefined);
    else if (valIsNull) setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
    else if (valIsSymbol) setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
    else if (othIsNull || othIsSymbol) setLow = false;
    else setLow = retHighest ? computed2 <= transformedValue : computed2 < transformedValue;
    if (setLow) low = mid + 1;
    else high = mid;
  }
  return Math.min(high, MAX_ARRAY_INDEX);
}

// node_modules/es-toolkit/dist/compat/predicate/isNumber.mjs
function isNumber2(value) {
  return typeof value === "number" || value instanceof Number;
}

// node_modules/es-toolkit/dist/compat/array/sortedIndex.mjs
var HALF_MAX_ARRAY_LENGTH = 2147483647;
function sortedIndex(array, value) {
  if (isNil(array)) return 0;
  let low = 0;
  let high = array.length;
  if (isNumber2(value) && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
    while (low < high) {
      const mid = low + high >>> 1;
      const compute = array[mid];
      if (!isNull(compute) && !isSymbol2(compute) && compute < value) low = mid + 1;
      else high = mid;
    }
    return high;
  }
  return sortedIndexBy(array, value, (value2) => value2);
}

// node_modules/es-toolkit/dist/compat/array/sortedIndexOf.mjs
function sortedIndexOf(array, value) {
  if (!array?.length) return -1;
  const index = sortedIndex(array, value);
  if (index < array.length && isEqualsSameValueZero(array[index], value)) return index;
  return -1;
}

// node_modules/es-toolkit/dist/compat/array/sortedLastIndexBy.mjs
function sortedLastIndexBy(array, value, iteratee2) {
  return sortedIndexBy(array, value, iteratee2, true);
}

// node_modules/es-toolkit/dist/compat/array/sortedLastIndex.mjs
var HALF_MAX_ARRAY_LENGTH2 = 2147483647;
function sortedLastIndex(array, value) {
  if (isNil(array)) return 0;
  let high = array.length;
  if (!isNumber2(value) || Number.isNaN(value) || high > HALF_MAX_ARRAY_LENGTH2) return sortedLastIndexBy(array, value, (value2) => value2);
  let low = 0;
  while (low < high) {
    const mid = low + high >>> 1;
    const compute = array[mid];
    if (!isNull(compute) && !isSymbol2(compute) && compute <= value) low = mid + 1;
    else high = mid;
  }
  return high;
}

// node_modules/es-toolkit/dist/compat/array/sortedLastIndexOf.mjs
function sortedLastIndexOf(array, value) {
  if (!array?.length) return -1;
  const index = sortedLastIndex(array, value) - 1;
  if (index >= 0 && isEqualsSameValueZero(array[index], value)) return index;
  return -1;
}

// node_modules/es-toolkit/dist/compat/array/tail.mjs
function tail2(arr) {
  if (!isArrayLike(arr)) return [];
  return tail(toArray(arr));
}

// node_modules/es-toolkit/dist/compat/array/take.mjs
function take2(arr, count = 1, guard) {
  count = guard ? 1 : toInteger(count);
  if (count < 1 || !isArrayLike(arr)) return [];
  return take(toArray(arr), count);
}

// node_modules/es-toolkit/dist/compat/array/takeRight.mjs
function takeRight2(arr, count = 1, guard) {
  count = guard ? 1 : toInteger(count);
  if (count <= 0 || !isArrayLike(arr)) return [];
  return takeRight(toArray(arr), count);
}

// node_modules/es-toolkit/dist/compat/array/takeRightWhile.mjs
function takeRightWhile2(_array, predicate) {
  if (!isArrayLikeObject(_array)) return [];
  const array = toArray(_array);
  const index = array.findLastIndex(negate(iteratee(predicate ?? identity)));
  return array.slice(index + 1);
}

// node_modules/es-toolkit/dist/compat/array/takeWhile.mjs
function takeWhile2(array, predicate) {
  if (!isArrayLikeObject(array)) return [];
  const _array = toArray(array);
  const index = _array.findIndex(negate2(iteratee(predicate ?? identity2)));
  return index === -1 ? _array : _array.slice(0, index);
}

// node_modules/es-toolkit/dist/compat/array/union.mjs
function union2(...arrays) {
  return uniq(flatMapDepth(arrays.filter(isArrayLikeObject), (v) => Array.from(v), 1));
}

// node_modules/es-toolkit/dist/compat/array/unionBy.mjs
function unionBy2(...values2) {
  const lastValue = last(values2);
  const flattened = flattenArrayLike(values2);
  if (isArrayLikeObject(lastValue) || lastValue == null) return uniq(flattened);
  return uniqBy(flattened, ary(iteratee(lastValue), 1));
}

// node_modules/es-toolkit/dist/compat/array/unionWith.mjs
function unionWith2(...values2) {
  const lastValue = last(values2);
  const flattened = flattenArrayLike(values2);
  if (isArrayLikeObject(lastValue) || lastValue == null) return uniq(flattened);
  return uniqWith(flattened, lastValue);
}

// node_modules/es-toolkit/dist/compat/array/uniqBy.mjs
function uniqBy2(array, iteratee$1 = identity) {
  if (!isArrayLikeObject(array)) return [];
  return uniqBy(Array.from(array), ary(iteratee(iteratee$1), 1));
}

// node_modules/es-toolkit/dist/compat/array/uniqWith.mjs
function uniqWith2(arr, comparator) {
  if (!isArrayLike(arr)) return [];
  if (typeof comparator !== "function") return uniq2(Array.from(arr));
  return uniqWith(Array.from(arr), (kept, candidate) => comparator(candidate, kept));
}

// node_modules/es-toolkit/dist/compat/array/unzip.mjs
function unzip2(array) {
  if (!isArrayLikeObject(array) || !array.length) return [];
  array = isArray(array) ? array : Array.from(array);
  array = array.filter((item) => isArrayLikeObject(item));
  return unzip(array);
}

// node_modules/es-toolkit/dist/compat/array/unzipWith.mjs
function unzipWith2(array, iteratee2) {
  if (!isArrayLikeObject(array) || !array.length) return [];
  const unzipped = isArray(array) ? unzip(array) : unzip(Array.from(array, (value) => Array.from(value)));
  if (!iteratee2) return unzipped;
  const result2 = new Array(unzipped.length);
  for (let i = 0; i < unzipped.length; i++) {
    const value = unzipped[i];
    result2[i] = iteratee2(...value);
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/array/without.mjs
function without2(array, ...values2) {
  if (!isArrayLikeObject(array)) return [];
  return without(Array.from(array), ...values2);
}

// node_modules/es-toolkit/dist/compat/array/xor.mjs
function xor2(...arrays) {
  const itemCounts = /* @__PURE__ */ new Map();
  for (let i = 0; i < arrays.length; i++) {
    const array = arrays[i];
    if (!isArrayLikeObject(array)) continue;
    const itemSet = new Set(toArray2(array));
    for (const item of itemSet) if (!itemCounts.has(item)) itemCounts.set(item, 1);
    else itemCounts.set(item, itemCounts.get(item) + 1);
  }
  const result2 = [];
  for (const [item, count] of itemCounts) if (count === 1) result2.push(item);
  return result2;
}

// node_modules/es-toolkit/dist/compat/array/xorBy.mjs
function xorBy2(...values2) {
  const lastValue = last2(values2);
  let mapper = identity;
  if (!isArrayLikeObject(lastValue) && lastValue != null) {
    mapper = iteratee(lastValue);
    values2 = values2.slice(0, -1);
  }
  const arrays = values2.filter(isArrayLikeObject);
  return differenceBy2(unionBy2(...arrays, mapper), unionBy2(...windowed(arrays, 2).map(([arr1, arr2]) => intersectionBy2(arr1, arr2, mapper)), mapper), mapper);
}

// node_modules/es-toolkit/dist/compat/array/xorWith.mjs
function xorWith2(...values2) {
  const lastValue = last2(values2);
  let comparator = (a, b) => a === b;
  if (typeof lastValue === "function") {
    comparator = lastValue;
    values2 = values2.slice(0, -1);
  }
  const arrays = values2.filter(isArrayLikeObject);
  return differenceWith2(unionWith2(...arrays, comparator), unionWith2(...windowed(arrays, 2).map(([arr1, arr2]) => intersectionWith2(arr1, arr2, comparator)), comparator), comparator);
}

// node_modules/es-toolkit/dist/compat/array/zip.mjs
function zip2(...arrays) {
  if (!arrays.length) return [];
  return zip(...arrays.filter((group) => isArrayLikeObject(group)));
}

// node_modules/es-toolkit/dist/compat/_internal/assignValue.mjs
var assignValue = (object, key2, value) => {
  const objValue = object[key2];
  if (!(Object.hasOwn(object, key2) && isEqualsSameValueZero(objValue, value)) || value === void 0 && !(key2 in object)) object[key2] = value;
};

// node_modules/es-toolkit/dist/compat/array/zipObject.mjs
function zipObject2(keys2 = [], values2 = []) {
  const result2 = {};
  for (let i = 0; i < keys2.length; i++) assignValue(result2, keys2[i], values2[i]);
  return result2;
}

// node_modules/es-toolkit/dist/compat/object/updateWith.mjs
function updateWith(obj, path, updater, customizer) {
  if (obj == null && !isObject(obj)) return obj;
  let resolvedPath;
  if (isKey(path, obj)) resolvedPath = [path];
  else if (Array.isArray(path)) resolvedPath = path;
  else resolvedPath = toPath(path);
  const updateValue = updater(get(obj, resolvedPath));
  let current = obj;
  for (let i = 0; i < resolvedPath.length && current != null; i++) {
    const key2 = toKey(resolvedPath[i]);
    if (isUnsafeProperty(key2)) continue;
    let newValue;
    if (i === resolvedPath.length - 1) newValue = updateValue;
    else {
      const objValue = current[key2];
      const customizerResult = customizer?.(objValue, key2, obj);
      newValue = customizerResult !== void 0 ? customizerResult : isObject(objValue) ? objValue : isIndex(resolvedPath[i + 1]) ? [] : {};
    }
    assignValue(current, key2, newValue);
    current = current[key2];
  }
  return obj;
}

// node_modules/es-toolkit/dist/compat/object/set.mjs
function set(obj, path, value) {
  return updateWith(obj, path, () => value, () => void 0);
}

// node_modules/es-toolkit/dist/compat/array/zipObjectDeep.mjs
function zipObjectDeep(keys2, values2) {
  const result2 = {};
  if (!isArrayLike(keys2)) return result2;
  if (!isArrayLike(values2)) values2 = [];
  const zipped = zip(Array.from(keys2), Array.from(values2));
  for (let i = 0; i < zipped.length; i++) {
    const [key2, value] = zipped[i];
    if (key2 != null) set(result2, key2, value);
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/array/zipWith.mjs
function zipWith2(...combine) {
  let iteratee2 = combine.pop();
  if (!isFunction(iteratee2)) {
    combine.push(iteratee2);
    iteratee2 = void 0;
  }
  if (!combine?.length) return [];
  const result2 = unzip2(combine);
  if (iteratee2 == null) return result2;
  return result2.map((group) => iteratee2(...group));
}

// node_modules/es-toolkit/dist/compat/function/after.mjs
function after2(n, func) {
  if (typeof func !== "function") throw new TypeError("Expected a function");
  n = toInteger(n);
  return function(...args) {
    if (--n < 1) return func.apply(this, args);
  };
}

// node_modules/es-toolkit/dist/compat/function/ary.mjs
function ary2(func, n = func.length, guard) {
  if (guard) n = func.length;
  if (Number.isNaN(n) || n < 0) n = 0;
  return ary(func, n);
}

// node_modules/es-toolkit/dist/compat/function/attempt.mjs
function attempt2(func, ...args) {
  try {
    return func(...args);
  } catch (e) {
    return e instanceof Error ? e : new Error(e);
  }
}

// node_modules/es-toolkit/dist/compat/function/before.mjs
function before2(n, func) {
  if (typeof func !== "function") throw new TypeError("Expected a function");
  let result2;
  n = toInteger(n);
  return function(...args) {
    if (--n > 0) result2 = func.apply(this, args);
    if (n <= 1 && func) func = void 0;
    return result2;
  };
}

// node_modules/es-toolkit/dist/compat/function/bind.mjs
function bind(func, thisObj, ...partialArgs) {
  const bound = function(...providedArgs) {
    const args = [];
    let startIndex = 0;
    for (let i = 0; i < partialArgs.length; i++) {
      const arg = partialArgs[i];
      if (arg === bind.placeholder) args.push(providedArgs[startIndex++]);
      else args.push(arg);
    }
    for (let i = startIndex; i < providedArgs.length; i++) args.push(providedArgs[i]);
    if (this instanceof bound) return new func(...args);
    return func.apply(thisObj, args);
  };
  return bound;
}
bind.placeholder = /* @__PURE__ */ Symbol("bind.placeholder");

// node_modules/es-toolkit/dist/compat/function/bindKey.mjs
function bindKey(object, key2, ...partialArgs) {
  const bound = function(...providedArgs) {
    const args = [];
    let startIndex = 0;
    for (let i = 0; i < partialArgs.length; i++) {
      const arg = partialArgs[i];
      if (arg === bindKey.placeholder) args.push(providedArgs[startIndex++]);
      else args.push(arg);
    }
    for (let i = startIndex; i < providedArgs.length; i++) args.push(providedArgs[i]);
    if (this instanceof bound) return new object[key2](...args);
    return object[key2].apply(object, args);
  };
  return bound;
}
bindKey.placeholder = /* @__PURE__ */ Symbol("bindKey.placeholder");

// node_modules/es-toolkit/dist/compat/function/curry.mjs
function curry2(func, arity = func.length, guard) {
  arity = guard ? func.length : arity;
  arity = Number.parseInt(arity, 10);
  if (Number.isNaN(arity) || arity < 1) arity = 0;
  const wrapper = function(...partialArgs) {
    const holders = partialArgs.filter((item) => item === curry2.placeholder);
    const length = partialArgs.length - holders.length;
    if (length < arity) return makeCurry(func, arity - length, partialArgs);
    if (this instanceof wrapper) return new func(...partialArgs);
    return func.apply(this, partialArgs);
  };
  wrapper.placeholder = curryPlaceholder;
  return wrapper;
}
function makeCurry(func, arity, partialArgs) {
  function wrapper(...providedArgs) {
    const holders = providedArgs.filter((item) => item === curry2.placeholder);
    const length = providedArgs.length - holders.length;
    providedArgs = composeArgs(providedArgs, partialArgs);
    if (length < arity) return makeCurry(func, arity - length, providedArgs);
    if (this instanceof wrapper) return new func(...providedArgs);
    return func.apply(this, providedArgs);
  }
  wrapper.placeholder = curryPlaceholder;
  return wrapper;
}
function composeArgs(providedArgs, partialArgs) {
  const args = [];
  let startIndex = 0;
  for (let i = 0; i < partialArgs.length; i++) {
    const arg = partialArgs[i];
    if (arg === curry2.placeholder && startIndex < providedArgs.length) args.push(providedArgs[startIndex++]);
    else args.push(arg);
  }
  for (let i = startIndex; i < providedArgs.length; i++) args.push(providedArgs[i]);
  return args;
}
var curryPlaceholder = /* @__PURE__ */ Symbol("curry.placeholder");
curry2.placeholder = curryPlaceholder;

// node_modules/es-toolkit/dist/compat/function/curryRight.mjs
function curryRight2(func, arity = func.length, guard) {
  arity = guard ? func.length : arity;
  arity = Number.parseInt(arity, 10);
  if (Number.isNaN(arity) || arity < 1) arity = 0;
  const wrapper = function(...partialArgs) {
    const holders = partialArgs.filter((item) => item === curryRight2.placeholder);
    const length = partialArgs.length - holders.length;
    if (length < arity) return makeCurryRight(func, arity - length, partialArgs);
    if (this instanceof wrapper) return new func(...partialArgs);
    return func.apply(this, partialArgs);
  };
  wrapper.placeholder = curryRightPlaceholder;
  return wrapper;
}
function makeCurryRight(func, arity, partialArgs) {
  function wrapper(...providedArgs) {
    const holders = providedArgs.filter((item) => item === curryRight2.placeholder);
    const length = providedArgs.length - holders.length;
    providedArgs = composeArgs2(providedArgs, partialArgs);
    if (length < arity) return makeCurryRight(func, arity - length, providedArgs);
    if (this instanceof wrapper) return new func(...providedArgs);
    return func.apply(this, providedArgs);
  }
  wrapper.placeholder = curryRightPlaceholder;
  return wrapper;
}
function composeArgs2(providedArgs, partialArgs) {
  const placeholderLength = partialArgs.filter((arg) => arg === curryRight2.placeholder).length;
  const rangeLength = Math.max(providedArgs.length - placeholderLength, 0);
  const args = [];
  let providedIndex = 0;
  for (let i = 0; i < rangeLength; i++) args.push(providedArgs[providedIndex++]);
  for (let i = 0; i < partialArgs.length; i++) {
    const arg = partialArgs[i];
    if (arg === curryRight2.placeholder) if (providedIndex < providedArgs.length) args.push(providedArgs[providedIndex++]);
    else args.push(arg);
    else args.push(arg);
  }
  return args;
}
var curryRightPlaceholder = /* @__PURE__ */ Symbol("curryRight.placeholder");
curryRight2.placeholder = curryRightPlaceholder;

// node_modules/es-toolkit/dist/compat/function/debounce.mjs
function debounce2(func, debounceMs = 0, options = {}) {
  if (typeof options !== "object") options = {};
  const { leading = false, trailing = true, maxWait } = options;
  const edges = Array(2);
  if (leading) edges[0] = "leading";
  if (trailing) edges[1] = "trailing";
  let result2 = void 0;
  let pendingAt = null;
  const _debounced = debounce(function(...args) {
    result2 = func.apply(this, args);
    pendingAt = null;
  }, debounceMs, { edges });
  const debounced = function(...args) {
    if (maxWait != null) {
      if (pendingAt === null) pendingAt = Date.now();
      if (Date.now() - pendingAt >= maxWait) {
        result2 = func.apply(this, args);
        pendingAt = Date.now();
        _debounced.cancel();
        _debounced.schedule();
        return result2;
      }
    }
    _debounced.apply(this, args);
    return result2;
  };
  const flush = () => {
    _debounced.flush();
    return result2;
  };
  debounced.cancel = _debounced.cancel;
  debounced.flush = flush;
  return debounced;
}

// node_modules/es-toolkit/dist/compat/function/defer.mjs
function defer(func, ...args) {
  if (typeof func !== "function") throw new TypeError("Expected a function");
  return setTimeout(func, 1, ...args);
}

// node_modules/es-toolkit/dist/compat/function/delay.mjs
function delay2(func, wait, ...args) {
  if (typeof func !== "function") throw new TypeError("Expected a function");
  return setTimeout(func, toNumber(wait) || 0, ...args);
}

// node_modules/es-toolkit/dist/compat/function/flip.mjs
function flip(func) {
  return function(...args) {
    return func.apply(this, args.reverse());
  };
}

// node_modules/es-toolkit/dist/compat/function/flow.mjs
function flow2(...funcs) {
  const flattenFuncs = flatten(funcs, 1);
  if (flattenFuncs.some((func) => typeof func !== "function")) throw new TypeError("Expected a function");
  return flow(...flattenFuncs);
}

// node_modules/es-toolkit/dist/compat/function/flowRight.mjs
function flowRight2(...funcs) {
  const flattenFuncs = flatten(funcs, 1);
  if (flattenFuncs.some((func) => typeof func !== "function")) throw new TypeError("Expected a function");
  return flowRight(...flattenFuncs);
}

// node_modules/es-toolkit/dist/compat/function/memoize.mjs
function memoize2(func, resolver) {
  if (typeof func !== "function" || resolver != null && typeof resolver !== "function") throw new TypeError("Expected a function");
  const memoized = function(...args) {
    const key2 = resolver ? resolver.apply(this, args) : args[0];
    const cache = memoized.cache;
    if (cache.has(key2)) return cache.get(key2);
    const result2 = func.apply(this, args);
    memoized.cache = cache.set(key2, result2) || cache;
    return result2;
  };
  memoized.cache = new (memoize2.Cache || Map)();
  return memoized;
}
memoize2.Cache = Map;

// node_modules/es-toolkit/dist/compat/function/nthArg.mjs
function nthArg(n = 0) {
  return function(...args) {
    return args.at(toInteger(n));
  };
}

// node_modules/es-toolkit/dist/compat/function/once.mjs
function once2(func) {
  return once(func);
}

// node_modules/es-toolkit/dist/compat/function/overArgs.mjs
function overArgs(func, ..._transforms) {
  if (typeof func !== "function") throw new TypeError("Expected a function");
  const transforms = _transforms.flat();
  return function(...args) {
    const length = Math.min(args.length, transforms.length);
    const transformedArgs = [...args];
    for (let i = 0; i < length; i++) transformedArgs[i] = iteratee(transforms[i] ?? identity).call(this, args[i]);
    return func.apply(this, transformedArgs);
  };
}

// node_modules/es-toolkit/dist/compat/function/partial.mjs
function partial2(func, ...partialArgs) {
  return partialImpl(func, partial2.placeholder, ...partialArgs);
}
partial2.placeholder = /* @__PURE__ */ Symbol("compat.partial.placeholder");

// node_modules/es-toolkit/dist/compat/function/partialRight.mjs
function partialRight2(func, ...partialArgs) {
  return partialRightImpl(func, partialRight2.placeholder, ...partialArgs);
}
partialRight2.placeholder = /* @__PURE__ */ Symbol("compat.partialRight.placeholder");

// node_modules/es-toolkit/dist/compat/function/rearg.mjs
function rearg(func, ...indices) {
  const flattenIndices = flatten2(indices);
  return function(...args) {
    const reorderedArgs = flattenIndices.map((i) => args[i]).slice(0, args.length);
    for (let i = reorderedArgs.length; i < args.length; i++) reorderedArgs.push(args[i]);
    return func.apply(this, reorderedArgs);
  };
}

// node_modules/es-toolkit/dist/compat/function/rest.mjs
function rest2(func, start2 = func.length - 1) {
  start2 = Number.parseInt(start2, 10);
  if (Number.isNaN(start2) || start2 < 0) start2 = func.length - 1;
  return rest(func, start2);
}

// node_modules/es-toolkit/dist/compat/function/spread.mjs
function spread2(func, argsIndex = 0) {
  argsIndex = Number.parseInt(argsIndex, 10);
  if (Number.isNaN(argsIndex) || argsIndex < 0) argsIndex = 0;
  return function(...args) {
    const array = args[argsIndex];
    const params = args.slice(0, argsIndex);
    if (array) params.push(...array);
    return func.apply(this, params);
  };
}

// node_modules/es-toolkit/dist/compat/function/throttle.mjs
function throttle2(func, throttleMs = 0, options = {}) {
  const { leading = true, trailing = true } = options;
  return debounce2(func, throttleMs, {
    leading,
    maxWait: throttleMs,
    trailing
  });
}

// node_modules/es-toolkit/dist/compat/function/unary.mjs
function unary2(func) {
  return ary2(func, 1);
}

// node_modules/es-toolkit/dist/compat/function/wrap.mjs
function wrap(value, wrapper) {
  return function(...args) {
    return (isFunction(wrapper) ? wrapper : identity).apply(this, [value, ...args]);
  };
}

// node_modules/es-toolkit/dist/compat/math/add.mjs
function add(value, other) {
  if (value === void 0 && other === void 0) return 0;
  if (value === void 0 || other === void 0) return value ?? other;
  if (typeof value === "string" || typeof other === "string") {
    value = toString(value);
    other = toString(other);
  } else {
    value = toNumber(value);
    other = toNumber(other);
  }
  return value + other;
}

// node_modules/es-toolkit/dist/compat/_internal/decimalAdjust.mjs
function decimalAdjust(type, number, precision = 0) {
  number = Number(number);
  if (Object.is(number, -0)) number = "-0";
  precision = Math.min(Number.parseInt(precision, 10), 292);
  if (precision) {
    const [magnitude, exponent = 0] = number.toString().split("e");
    let adjustedValue = Math[type](Number(`${magnitude}e${Number(exponent) + precision}`));
    if (Object.is(adjustedValue, -0)) adjustedValue = "-0";
    const [newMagnitude, newExponent = 0] = adjustedValue.toString().split("e");
    return Number(`${newMagnitude}e${Number(newExponent) - precision}`);
  }
  return Math[type](Number(number));
}

// node_modules/es-toolkit/dist/compat/math/ceil.mjs
function ceil(number, precision = 0) {
  return decimalAdjust("ceil", number, precision);
}

// node_modules/es-toolkit/dist/compat/math/divide.mjs
function divide(value, other) {
  if (value === void 0 && other === void 0) return 1;
  if (value === void 0 || other === void 0) return value ?? other;
  if (typeof value === "string" || typeof other === "string") {
    value = toString(value);
    other = toString(other);
  } else {
    value = toNumber(value);
    other = toNumber(other);
  }
  return value / other;
}

// node_modules/es-toolkit/dist/compat/math/floor.mjs
function floor(number, precision = 0) {
  return decimalAdjust("floor", number, precision);
}

// node_modules/es-toolkit/dist/compat/math/inRange.mjs
function inRange2(value, minimum, maximum) {
  if (!minimum) minimum = 0;
  if (maximum != null && !maximum) maximum = 0;
  if (minimum != null && typeof minimum !== "number") minimum = Number(minimum);
  if (maximum == null && minimum === 0) return false;
  if (maximum != null && typeof maximum !== "number") maximum = Number(maximum);
  if (maximum != null && minimum > maximum) [minimum, maximum] = [maximum, minimum];
  if (minimum === maximum) return false;
  return inRange(value, minimum, maximum);
}

// node_modules/es-toolkit/dist/compat/math/max.mjs
function max(items) {
  if (!items || items.length === 0) return;
  let maxResult = void 0;
  for (let i = 0; i < items.length; i++) {
    const current = items[i];
    if (current == null || Number.isNaN(current) || typeof current === "symbol") continue;
    if (maxResult === void 0 || current > maxResult) maxResult = current;
  }
  return maxResult;
}

// node_modules/es-toolkit/dist/compat/math/maxBy.mjs
function maxBy2(items, iteratee$1) {
  if (items == null) return;
  return maxBy(Array.from(items), iteratee(iteratee$1 ?? identity));
}

// node_modules/es-toolkit/dist/compat/math/sumBy.mjs
function sumBy2(array, iteratee$1) {
  if (!array || !array.length) return 0;
  if (iteratee$1 != null) iteratee$1 = iteratee(iteratee$1);
  let result2 = void 0;
  for (let i = 0; i < array.length; i++) {
    const current = iteratee$1 ? iteratee$1(array[i]) : array[i];
    if (current !== void 0) if (result2 === void 0) result2 = current;
    else result2 += current;
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/math/sum.mjs
function sum2(array) {
  return sumBy2(array);
}

// node_modules/es-toolkit/dist/compat/math/mean.mjs
function mean2(nums) {
  const length = nums ? nums.length : 0;
  return length === 0 ? NaN : sum2(nums) / length;
}

// node_modules/es-toolkit/dist/compat/math/meanBy.mjs
function meanBy2(items, iteratee$1) {
  if (items == null) return NaN;
  return meanBy(Array.from(items), iteratee(iteratee$1 ?? identity));
}

// node_modules/es-toolkit/dist/compat/math/min.mjs
function min(items) {
  if (!items || items.length === 0) return;
  let minResult = void 0;
  for (let i = 0; i < items.length; i++) {
    const current = items[i];
    if (current == null || Number.isNaN(current) || typeof current === "symbol") continue;
    if (minResult === void 0 || current < minResult) minResult = current;
  }
  return minResult;
}

// node_modules/es-toolkit/dist/compat/math/minBy.mjs
function minBy2(items, iteratee$1) {
  if (items == null) return;
  return minBy(Array.from(items), iteratee(iteratee$1 ?? identity));
}

// node_modules/es-toolkit/dist/compat/math/multiply.mjs
function multiply(value, other) {
  if (value === void 0 && other === void 0) return 1;
  if (value === void 0 || other === void 0) return value ?? other;
  if (typeof value === "string" || typeof other === "string") {
    value = toString(value);
    other = toString(other);
  } else {
    value = toNumber(value);
    other = toNumber(other);
  }
  return value * other;
}

// node_modules/es-toolkit/dist/compat/math/parseInt.mjs
function parseInt2(string, radix = 0, guard) {
  if (guard) radix = 0;
  return Number.parseInt(string, radix);
}

// node_modules/es-toolkit/dist/compat/math/random.mjs
function random2(...args) {
  let minimum = 0;
  let maximum = 1;
  let floating = false;
  switch (args.length) {
    case 1:
      if (typeof args[0] === "boolean") floating = args[0];
      else maximum = args[0];
      break;
    case 2:
      if (typeof args[1] === "boolean") {
        maximum = args[0];
        floating = args[1];
      } else {
        minimum = args[0];
        maximum = args[1];
      }
    case 3:
      if (typeof args[2] === "object" && args[2] != null && args[2][args[1]] === args[0]) {
        minimum = 0;
        maximum = args[0];
        floating = false;
      } else {
        minimum = args[0];
        maximum = args[1];
        floating = args[2];
      }
  }
  if (typeof minimum !== "number") minimum = Number(minimum);
  if (typeof maximum !== "number") minimum = Number(maximum);
  if (!minimum) minimum = 0;
  if (!maximum) maximum = 0;
  if (minimum > maximum) [minimum, maximum] = [maximum, minimum];
  minimum = clamp2(minimum, -Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
  maximum = clamp2(maximum, -Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
  if (minimum === maximum) return minimum;
  if (floating) return random(minimum, maximum + 1);
  else return randomInt(minimum, maximum + 1);
}

// node_modules/es-toolkit/dist/compat/math/range.mjs
function range2(start2, end, step) {
  if (step && typeof step !== "number" && isIterateeCall(start2, end, step)) end = step = void 0;
  start2 = toFinite(start2);
  if (end === void 0) {
    end = start2;
    start2 = 0;
  } else end = toFinite(end);
  step = step === void 0 ? start2 < end ? 1 : -1 : toFinite(step);
  const length = Math.max(Math.ceil((end - start2) / (step || 1)), 0);
  const result2 = new Array(length);
  for (let index = 0; index < length; index++) {
    result2[index] = start2;
    start2 += step;
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/math/rangeRight.mjs
function rangeRight2(start2, end, step) {
  if (step && typeof step !== "number" && isIterateeCall(start2, end, step)) end = step = void 0;
  start2 = toFinite(start2);
  if (end === void 0) {
    end = start2;
    start2 = 0;
  } else end = toFinite(end);
  step = step === void 0 ? start2 < end ? 1 : -1 : toFinite(step);
  const length = Math.max(Math.ceil((end - start2) / (step || 1)), 0);
  const result2 = new Array(length);
  for (let index = length - 1; index >= 0; index--) {
    result2[index] = start2;
    start2 += step;
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/math/round.mjs
function round2(number, precision = 0) {
  return decimalAdjust("round", number, precision);
}

// node_modules/es-toolkit/dist/compat/math/subtract.mjs
function subtract(value, other) {
  if (value === void 0 && other === void 0) return 0;
  if (value === void 0 || other === void 0) return value ?? other;
  if (typeof value === "string" || typeof other === "string") {
    value = toString(value);
    other = toString(other);
  } else {
    value = toNumber(value);
    other = toNumber(other);
  }
  return value - other;
}

// node_modules/es-toolkit/dist/compat/function/noop.mjs
function noop2(..._) {
}

// node_modules/es-toolkit/dist/compat/predicate/isTypedArray.mjs
function isTypedArray2(x) {
  return isTypedArray(x);
}

// node_modules/es-toolkit/dist/compat/util/times.mjs
function times(n, getValue) {
  n = toInteger(n);
  if (n < 1 || !Number.isSafeInteger(n)) return [];
  const result2 = new Array(n);
  for (let i = 0; i < n; i++) result2[i] = typeof getValue === "function" ? getValue(i) : i;
  return result2;
}

// node_modules/es-toolkit/dist/compat/_internal/isPrototype.mjs
function isPrototype(value) {
  const constructor = value?.constructor;
  return value === (typeof constructor === "function" ? constructor.prototype : Object.prototype);
}

// node_modules/es-toolkit/dist/compat/object/keys.mjs
function keys(object) {
  if (isArrayLike(object)) return arrayLikeKeys(object);
  const result2 = Object.keys(Object(object));
  if (!isPrototype(object)) return result2;
  return result2.filter((key2) => key2 !== "constructor");
}
function arrayLikeKeys(object) {
  const indices = times(object.length, (index) => `${index}`);
  const filteredKeys = new Set(indices);
  if (isBuffer(object)) {
    filteredKeys.add("offset");
    filteredKeys.add("parent");
  }
  if (isTypedArray2(object)) {
    filteredKeys.add("buffer");
    filteredKeys.add("byteLength");
    filteredKeys.add("byteOffset");
  }
  const inheritedKeys = Object.keys(object).filter((key2) => !filteredKeys.has(key2));
  if (Array.isArray(object)) return [...indices, ...inheritedKeys];
  return [...indices.filter((index) => Object.hasOwn(object, index)), ...inheritedKeys];
}

// node_modules/es-toolkit/dist/compat/object/assign.mjs
function assign(object, ...sources) {
  for (let i = 0; i < sources.length; i++) assignImpl(object, sources[i]);
  return object;
}
function assignImpl(object, source) {
  const keys$1 = keys(source);
  for (let i = 0; i < keys$1.length; i++) {
    const key2 = keys$1[i];
    if (!(key2 in object) || !isEqualsSameValueZero(object[key2], source[key2])) object[key2] = source[key2];
  }
}

// node_modules/es-toolkit/dist/compat/object/keysIn.mjs
function keysIn(object) {
  if (object == null) return [];
  switch (typeof object) {
    case "object":
    case "function":
      if (isArrayLike(object)) return arrayLikeKeysIn(object);
      if (isPrototype(object)) return prototypeKeysIn(object);
      return keysInImpl(object);
    default:
      return keysInImpl(Object(object));
  }
}
function keysInImpl(object) {
  const result2 = [];
  for (const key2 in object) result2.push(key2);
  return result2;
}
function prototypeKeysIn(object) {
  return keysInImpl(object).filter((key2) => key2 !== "constructor");
}
function arrayLikeKeysIn(object) {
  const indices = times(object.length, (index) => `${index}`);
  const filteredKeys = new Set(indices);
  if (isBuffer(object)) {
    filteredKeys.add("offset");
    filteredKeys.add("parent");
  }
  if (isTypedArray2(object)) {
    filteredKeys.add("buffer");
    filteredKeys.add("byteLength");
    filteredKeys.add("byteOffset");
  }
  const inheritedKeys = keysInImpl(object).filter((key2) => !filteredKeys.has(key2));
  if (Array.isArray(object)) return [...indices, ...inheritedKeys];
  return [...indices.filter((index) => Object.hasOwn(object, index)), ...inheritedKeys];
}

// node_modules/es-toolkit/dist/compat/object/assignIn.mjs
function assignIn(object, ...sources) {
  for (let i = 0; i < sources.length; i++) assignInImpl(object, sources[i]);
  return object;
}
function assignInImpl(object, source) {
  const keys2 = keysIn(source);
  for (let i = 0; i < keys2.length; i++) {
    const key2 = keys2[i];
    if (!(key2 in object) || !isEqualsSameValueZero(object[key2], source[key2])) object[key2] = source[key2];
  }
}

// node_modules/es-toolkit/dist/compat/object/assignInWith.mjs
function assignInWith(object, ...sources) {
  let getValueToAssign = sources[sources.length - 1];
  if (typeof getValueToAssign === "function") sources.pop();
  else getValueToAssign = void 0;
  for (let i = 0; i < sources.length; i++) assignInWithImpl(object, sources[i], getValueToAssign);
  return object;
}
function assignInWithImpl(object, source, getValueToAssign) {
  const keys2 = keysIn(source);
  for (let i = 0; i < keys2.length; i++) {
    const key2 = keys2[i];
    const objValue = object[key2];
    const srcValue = source[key2];
    const newValue = getValueToAssign?.(objValue, srcValue, key2, object, source) ?? srcValue;
    if (!(key2 in object) || !isEqualsSameValueZero(objValue, newValue)) object[key2] = newValue;
  }
}

// node_modules/es-toolkit/dist/compat/object/assignWith.mjs
function assignWith(object, ...sources) {
  let getValueToAssign = sources[sources.length - 1];
  if (typeof getValueToAssign === "function") sources.pop();
  else getValueToAssign = void 0;
  for (let i = 0; i < sources.length; i++) assignWithImpl(object, sources[i], getValueToAssign);
  return object;
}
function assignWithImpl(object, source, getValueToAssign) {
  const keys$1 = keys(source);
  for (let i = 0; i < keys$1.length; i++) {
    const key2 = keys$1[i];
    const objValue = object[key2];
    const srcValue = source[key2];
    const newValue = getValueToAssign?.(objValue, srcValue, key2, object, source) ?? srcValue;
    if (!(key2 in object) || !isEqualsSameValueZero(objValue, newValue)) object[key2] = newValue;
  }
}

// node_modules/es-toolkit/dist/compat/object/clone.mjs
function clone2(obj) {
  if (isPrimitive(obj)) return obj;
  const tag = getTag(obj);
  if (!isCloneableObject2(obj)) return {};
  if (isArray(obj)) {
    const result3 = Array.from(obj);
    if (obj.length > 0 && typeof obj[0] === "string" && Object.hasOwn(obj, "index")) {
      result3.index = obj.index;
      result3.input = obj.input;
    }
    return result3;
  }
  if (isTypedArray2(obj)) {
    const typedArray = obj;
    const Ctor = typedArray.constructor;
    return new Ctor(typedArray.buffer, typedArray.byteOffset, typedArray.length);
  }
  if (tag === "[object ArrayBuffer]") return new ArrayBuffer(obj.byteLength);
  if (tag === "[object DataView]") {
    const dataView = obj;
    const buffer = dataView.buffer;
    const byteOffset = dataView.byteOffset;
    const byteLength = dataView.byteLength;
    const clonedBuffer = new ArrayBuffer(byteLength);
    const srcView = new Uint8Array(buffer, byteOffset, byteLength);
    new Uint8Array(clonedBuffer).set(srcView);
    return new DataView(clonedBuffer);
  }
  if (tag === "[object Boolean]" || tag === "[object Number]" || tag === "[object String]") {
    const Ctor = obj.constructor;
    const clone3 = new Ctor(obj.valueOf());
    if (tag === "[object String]") cloneStringObjectProperties(clone3, obj);
    else copyOwnProperties(clone3, obj);
    return clone3;
  }
  if (tag === "[object Date]") return new Date(Number(obj));
  if (tag === "[object RegExp]") {
    const regExp = obj;
    const clone3 = new RegExp(regExp.source, regExp.flags);
    clone3.lastIndex = regExp.lastIndex;
    return clone3;
  }
  if (tag === "[object Symbol]") return Object(Symbol.prototype.valueOf.call(obj));
  if (tag === "[object Map]") {
    const map2 = obj;
    const result3 = /* @__PURE__ */ new Map();
    map2.forEach((obj2, key2) => {
      result3.set(key2, obj2);
    });
    return result3;
  }
  if (tag === "[object Set]") {
    const set3 = obj;
    const result3 = /* @__PURE__ */ new Set();
    set3.forEach((obj2) => {
      result3.add(obj2);
    });
    return result3;
  }
  if (tag === "[object Arguments]") {
    const args = obj;
    const result3 = {};
    copyOwnProperties(result3, args);
    result3.length = args.length;
    result3[Symbol.iterator] = args[Symbol.iterator];
    return result3;
  }
  const result2 = {};
  copyPrototype(result2, obj);
  copyOwnProperties(result2, obj);
  copySymbolProperties(result2, obj);
  return result2;
}
function isCloneableObject2(object) {
  switch (getTag(object)) {
    case argumentsTag:
    case arrayTag:
    case arrayBufferTag:
    case dataViewTag:
    case booleanTag:
    case dateTag:
    case float32ArrayTag:
    case float64ArrayTag:
    case int8ArrayTag:
    case int16ArrayTag:
    case int32ArrayTag:
    case mapTag:
    case numberTag:
    case objectTag:
    case regexpTag:
    case setTag:
    case stringTag:
    case symbolTag:
    case uint8ArrayTag:
    case uint8ClampedArrayTag:
    case uint16ArrayTag:
    case uint32ArrayTag:
      return true;
    default:
      return false;
  }
}
function copyOwnProperties(target, source) {
  for (const key2 in source) if (Object.hasOwn(source, key2)) target[key2] = source[key2];
}
function copySymbolProperties(target, source) {
  const symbols = Object.getOwnPropertySymbols(source);
  for (let i = 0; i < symbols.length; i++) {
    const symbol = symbols[i];
    if (Object.prototype.propertyIsEnumerable.call(source, symbol)) target[symbol] = source[symbol];
  }
}
function cloneStringObjectProperties(target, source) {
  const stringLength = source.valueOf().length;
  for (const key2 in source) if (Object.hasOwn(source, key2) && (Number.isNaN(Number(key2)) || Number(key2) >= stringLength)) target[key2] = source[key2];
}
function copyPrototype(target, source) {
  const proto = Object.getPrototypeOf(source);
  if (proto !== null) {
    if (typeof source.constructor === "function") Object.setPrototypeOf(target, proto);
  }
}

// node_modules/es-toolkit/dist/compat/object/cloneWith.mjs
function cloneWith(value, customizer) {
  if (!customizer) return clone2(value);
  const result2 = customizer(value);
  if (result2 !== void 0) return result2;
  return clone2(value);
}

// node_modules/es-toolkit/dist/compat/object/create.mjs
function create(prototype, properties) {
  const proto = isObject(prototype) ? Object.create(prototype) : {};
  if (properties != null) {
    const propsKeys = keys(properties);
    for (let i = 0; i < propsKeys.length; i++) {
      const key2 = propsKeys[i];
      const propsValue = properties[key2];
      assignValue(proto, key2, propsValue);
    }
  }
  return proto;
}

// node_modules/es-toolkit/dist/compat/object/defaults.mjs
function defaults(object, ...sources) {
  object = Object(object);
  const objectProto = Object.prototype;
  let length = sources.length;
  const guard = length > 2 ? sources[2] : void 0;
  if (guard && isIterateeCall(sources[0], sources[1], guard)) length = 1;
  for (let i = 0; i < length; i++) {
    if (isNil(sources[i])) continue;
    const source = sources[i];
    const keys2 = Object.keys(source);
    for (let j = 0; j < keys2.length; j++) {
      const key2 = keys2[j];
      const value = object[key2];
      if (value === void 0 || !Object.hasOwn(object, key2) && isEqualsSameValueZero(value, objectProto[key2])) object[key2] = source[key2];
    }
  }
  return object;
}

// node_modules/es-toolkit/dist/compat/object/defaultsDeep.mjs
function defaultsDeep(target, ...sources) {
  target = Object(target);
  for (let i = 0; i < sources.length; i++) {
    const source = sources[i];
    if (source != null) defaultsDeepRecursive(target, source, /* @__PURE__ */ new WeakMap());
  }
  return target;
}
function defaultsDeepRecursive(target, source, stack) {
  for (const key2 in source) {
    const sourceValue = source[key2];
    const targetValue = target[key2];
    if (targetValue === void 0 || !Object.hasOwn(target, key2)) {
      target[key2] = handleMissingProperty(sourceValue, stack);
      continue;
    }
    if (stack.get(sourceValue) === targetValue) continue;
    handleExistingProperty(targetValue, sourceValue, stack);
  }
}
function handleMissingProperty(sourceValue, stack) {
  if (stack.has(sourceValue)) return stack.get(sourceValue);
  if (isPlainObject2(sourceValue)) {
    const newObj = {};
    stack.set(sourceValue, newObj);
    defaultsDeepRecursive(newObj, sourceValue, stack);
    return newObj;
  }
  return sourceValue;
}
function handleExistingProperty(targetValue, sourceValue, stack) {
  if (isPlainObject2(targetValue) && isPlainObject2(sourceValue)) {
    stack.set(sourceValue, targetValue);
    defaultsDeepRecursive(targetValue, sourceValue, stack);
    return;
  }
  if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
    stack.set(sourceValue, targetValue);
    mergeArrays(targetValue, sourceValue, stack);
  }
}
function mergeArrays(targetArray, sourceArray, stack) {
  const minLength = Math.min(sourceArray.length, targetArray.length);
  for (let i = 0; i < minLength; i++) if (isPlainObject2(targetArray[i]) && isPlainObject2(sourceArray[i])) defaultsDeepRecursive(targetArray[i], sourceArray[i], stack);
  for (let i = minLength; i < sourceArray.length; i++) targetArray.push(sourceArray[i]);
}

// node_modules/es-toolkit/dist/compat/object/findKey.mjs
function findKey2(obj, predicate) {
  if (!isObject(obj)) return;
  return findKey(obj, iteratee(predicate ?? identity2));
}

// node_modules/es-toolkit/dist/compat/object/findLastKey.mjs
function findLastKey(obj, predicate) {
  if (!isObject(obj)) return;
  const iteratee$1 = iteratee(predicate ?? identity2);
  return Object.keys(obj).findLast((key2) => iteratee$1(obj[key2], key2, obj));
}

// node_modules/es-toolkit/dist/compat/object/forIn.mjs
function forIn(object, iteratee2 = identity) {
  if (object == null) return object;
  for (const key2 in object) if (iteratee2(object[key2], key2, object) === false) break;
  return object;
}

// node_modules/es-toolkit/dist/compat/object/forInRight.mjs
function forInRight(object, iteratee2 = identity) {
  if (object == null) return object;
  const keys2 = [];
  for (const key2 in object) keys2.push(key2);
  for (let i = keys2.length - 1; i >= 0; i--) {
    const key2 = keys2[i];
    if (iteratee2(object[key2], key2, object) === false) break;
  }
  return object;
}

// node_modules/es-toolkit/dist/compat/object/forOwn.mjs
function forOwn(object, iteratee2 = identity) {
  if (object == null) return object;
  const iterable = Object(object);
  const keys$1 = keys(object);
  for (let i = 0; i < keys$1.length; ++i) {
    const key2 = keys$1[i];
    if (iteratee2(iterable[key2], key2, iterable) === false) break;
  }
  return object;
}

// node_modules/es-toolkit/dist/compat/object/forOwnRight.mjs
function forOwnRight(object, iteratee2 = identity) {
  if (object == null) return object;
  const iterable = Object(object);
  const keys$1 = keys(object);
  for (let i = keys$1.length - 1; i >= 0; --i) {
    const key2 = keys$1[i];
    if (iteratee2(iterable[key2], key2, iterable) === false) break;
  }
  return object;
}

// node_modules/es-toolkit/dist/compat/object/fromPairs.mjs
function fromPairs(pairs) {
  if (!isArrayLike(pairs)) return {};
  const result2 = {};
  for (let i = 0; i < pairs.length; i++) {
    const [key2, value] = pairs[i];
    result2[key2] = value;
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/object/functions.mjs
function functions(object) {
  if (object == null) return [];
  return keys(object).filter((key2) => typeof object[key2] === "function");
}

// node_modules/es-toolkit/dist/compat/object/functionsIn.mjs
function functionsIn(object) {
  if (object == null) return [];
  const result2 = [];
  for (const key2 in object) if (isFunction(object[key2])) result2.push(key2);
  return result2;
}

// node_modules/es-toolkit/dist/compat/object/hasIn.mjs
function hasIn(object, path) {
  if (object == null) return false;
  let resolvedPath;
  if (Array.isArray(path)) resolvedPath = path;
  else if (typeof path === "string" && isDeepKey(path) && object[path] == null) resolvedPath = toPath(path);
  else resolvedPath = [path];
  if (resolvedPath.length === 0) return false;
  let current = object;
  for (let i = 0; i < resolvedPath.length; i++) {
    const key2 = resolvedPath[i];
    if (current == null || !(key2 in Object(current))) {
      if (!((Array.isArray(current) || isArguments(current)) && isIndex(key2) && key2 < current.length)) return false;
    }
    current = current[key2];
  }
  return true;
}

// node_modules/es-toolkit/dist/compat/object/invert.mjs
function invert2(obj) {
  return invert(obj);
}

// node_modules/es-toolkit/dist/compat/object/invertBy.mjs
function invertBy(object, iteratee$1) {
  const result2 = {};
  if (isNil(object)) return result2;
  if (iteratee$1 == null) iteratee$1 = identity;
  const keys2 = Object.keys(object);
  const getString = iteratee(iteratee$1);
  for (let i = 0; i < keys2.length; i++) {
    const key2 = keys2[i];
    const value = object[key2];
    const valueStr = getString(value);
    if (Array.isArray(result2[valueStr])) result2[valueStr].push(key2);
    else result2[valueStr] = [key2];
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/object/mapKeys.mjs
function mapKeys2(object, getNewKey = identity) {
  if (object == null) return {};
  return mapKeys(object, iteratee(getNewKey));
}

// node_modules/es-toolkit/dist/compat/object/mapValues.mjs
function mapValues2(object, getNewValue = identity) {
  if (object == null) return {};
  return mapValues(object, iteratee(getNewValue));
}

// node_modules/es-toolkit/dist/compat/object/mergeWith.mjs
function mergeWith2(object, ...otherArgs) {
  const sources = otherArgs.slice(0, -1);
  const merge3 = otherArgs[otherArgs.length - 1];
  let result2 = object;
  for (let i = 0; i < sources.length; i++) {
    const source = sources[i];
    result2 = mergeWithDeep(result2, source, merge3, /* @__PURE__ */ new Map());
  }
  return result2;
}
function mergeWithDeep(target, source, merge3, stack) {
  if (isPrimitive(target)) target = Object(target);
  if (source == null || typeof source !== "object") return target;
  if (stack.has(source)) return clone(stack.get(source));
  stack.set(source, target);
  if (Array.isArray(source)) {
    source = source.slice();
    for (let i = 0; i < source.length; i++) source[i] = source[i] ?? void 0;
  }
  const sourceKeys = [...Object.keys(source), ...getSymbols(source)];
  for (let i = 0; i < sourceKeys.length; i++) {
    const key2 = sourceKeys[i];
    if (isUnsafeProperty(key2)) continue;
    let sourceValue = source[key2];
    let targetValue = target[key2];
    if (isArguments(sourceValue)) sourceValue = { ...sourceValue };
    if (isArguments(targetValue)) targetValue = { ...targetValue };
    if (isBuffer(sourceValue)) sourceValue = cloneDeep2(sourceValue);
    if (Array.isArray(sourceValue)) if (Array.isArray(targetValue)) {
      const cloned = [];
      const targetKeys = Reflect.ownKeys(targetValue);
      for (let i2 = 0; i2 < targetKeys.length; i2++) {
        const targetKey = targetKeys[i2];
        cloned[targetKey] = targetValue[targetKey];
      }
      targetValue = cloned;
    } else if (isArrayLikeObject(targetValue)) {
      const cloned = [];
      for (let i2 = 0; i2 < targetValue.length; i2++) cloned[i2] = targetValue[i2];
      targetValue = cloned;
    } else targetValue = [];
    const merged = merge3(targetValue, sourceValue, key2, target, source, stack);
    if (merged !== void 0) target[key2] = merged;
    else if (Array.isArray(sourceValue)) target[key2] = mergeWithDeep(targetValue, sourceValue, merge3, stack);
    else if (isObjectLike(targetValue) && isObjectLike(sourceValue) && (isPlainObject2(targetValue) || isPlainObject2(sourceValue) || isTypedArray2(targetValue) || isTypedArray2(sourceValue))) target[key2] = mergeWithDeep(targetValue, sourceValue, merge3, stack);
    else if (targetValue == null && isPlainObject2(sourceValue)) target[key2] = mergeWithDeep({}, sourceValue, merge3, stack);
    else if (targetValue == null && isTypedArray2(sourceValue)) target[key2] = cloneDeep2(sourceValue);
    else if (targetValue === void 0 || sourceValue !== void 0) target[key2] = sourceValue;
  }
  return target;
}

// node_modules/es-toolkit/dist/compat/object/merge.mjs
function merge2(object, ...sources) {
  return mergeWith2(object, ...sources, noop);
}

// node_modules/es-toolkit/dist/compat/_internal/getSymbolsIn.mjs
function getSymbolsIn(object) {
  const result2 = [];
  while (object) {
    result2.push(...getSymbols(object));
    object = Object.getPrototypeOf(object);
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/object/omit.mjs
function omit2(obj, ...keysArr) {
  if (obj == null) return {};
  keysArr = flatten2(keysArr);
  const result2 = cloneInOmit(obj, keysArr);
  for (let i = 0; i < keysArr.length; i++) {
    let keys2 = keysArr[i];
    switch (typeof keys2) {
      case "object":
        if (!Array.isArray(keys2)) keys2 = Array.from(keys2);
        for (let j = 0; j < keys2.length; j++) {
          const key2 = keys2[j];
          unset(result2, key2);
        }
        break;
      case "string":
      case "symbol":
      case "number":
        unset(result2, keys2);
        break;
    }
  }
  return result2;
}
function cloneInOmit(obj, keys2) {
  if (keys2.some((key2) => Array.isArray(key2) || isDeepKey(key2))) return deepCloneInOmit(obj);
  return shallowCloneInOmit(obj);
}
function shallowCloneInOmit(obj) {
  const result2 = {};
  const keysToCopy = [...keysIn(obj), ...getSymbolsIn(obj)];
  for (let i = 0; i < keysToCopy.length; i++) {
    const key2 = keysToCopy[i];
    result2[key2] = obj[key2];
  }
  return result2;
}
function deepCloneInOmit(obj) {
  const result2 = {};
  const keysToCopy = [...keysIn(obj), ...getSymbolsIn(obj)];
  for (let i = 0; i < keysToCopy.length; i++) {
    const key2 = keysToCopy[i];
    result2[key2] = cloneDeepWith2(obj[key2], (valueToClone) => {
      if (isPlainObject2(valueToClone)) return;
      return valueToClone;
    });
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/object/omitBy.mjs
function omitBy2(object, shouldOmit) {
  if (object == null) return {};
  const result2 = {};
  const predicate = iteratee(shouldOmit ?? identity2);
  const keys2 = [...keysIn(object), ...getSymbolsIn(object)];
  for (let i = 0; i < keys2.length; i++) {
    const key2 = isSymbol(keys2[i]) ? keys2[i] : keys2[i].toString();
    const value = object[key2];
    if (!predicate(value, key2, object)) result2[key2] = value;
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/object/pick.mjs
function pick2(obj, ...keysArr) {
  if (isNil2(obj)) return {};
  const result2 = {};
  for (let i = 0; i < keysArr.length; i++) {
    let keys2 = keysArr[i];
    switch (typeof keys2) {
      case "object":
        if (!Array.isArray(keys2)) if (isArrayLike(keys2)) keys2 = Array.from(keys2);
        else keys2 = [keys2];
        break;
      case "string":
      case "symbol":
      case "number":
        keys2 = [keys2];
        break;
    }
    for (const key2 of keys2) {
      const value = get(obj, key2);
      if (value === void 0 && !has(obj, key2)) continue;
      if (typeof key2 === "string" && Object.hasOwn(obj, key2)) result2[key2] = value;
      else set(result2, key2, value);
    }
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/object/pickBy.mjs
function pickBy2(obj, shouldPick) {
  if (obj == null) return {};
  const predicate = iteratee(shouldPick ?? identity2);
  const result2 = {};
  const keys2 = isArrayLike(obj) ? range(0, obj.length) : [...keysIn(obj), ...getSymbolsIn(obj)];
  for (let i = 0; i < keys2.length; i++) {
    const key2 = isSymbol(keys2[i]) ? keys2[i] : keys2[i].toString();
    const value = obj[key2];
    if (predicate(value, key2, obj)) result2[key2] = value;
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/object/propertyOf.mjs
function propertyOf(object) {
  return function(path) {
    return get(object, path);
  };
}

// node_modules/es-toolkit/dist/compat/object/result.mjs
function result(object, path, defaultValue) {
  if (isKey(path, object)) path = [path];
  else if (!Array.isArray(path)) path = toPath(toString(path));
  const pathLength = Math.max(path.length, 1);
  for (let index = 0; index < pathLength; index++) {
    const value = object == null ? void 0 : object[toKey(path[index])];
    if (value === void 0) return typeof defaultValue === "function" ? defaultValue.call(object) : defaultValue;
    object = typeof value === "function" ? value.call(object) : value;
  }
  return object;
}

// node_modules/es-toolkit/dist/compat/object/setWith.mjs
function setWith(obj, path, value, customizer) {
  let customizerFn;
  if (typeof customizer === "function") customizerFn = customizer;
  else customizerFn = () => void 0;
  return updateWith(obj, path, () => value, customizerFn);
}

// node_modules/es-toolkit/dist/compat/object/toDefaulted.mjs
function toDefaulted(object, ...sources) {
  return defaults(cloneDeep2(object), ...sources);
}

// node_modules/es-toolkit/dist/compat/_internal/mapToEntries.mjs
function mapToEntries(map2) {
  const arr = new Array(map2.size);
  const keys2 = map2.keys();
  const values2 = map2.values();
  for (let i = 0; i < arr.length; i++) arr[i] = [keys2.next().value, values2.next().value];
  return arr;
}

// node_modules/es-toolkit/dist/compat/_internal/setToEntries.mjs
function setToEntries(set3) {
  const arr = new Array(set3.size);
  const values2 = set3.values();
  for (let i = 0; i < arr.length; i++) {
    const value = values2.next().value;
    arr[i] = [value, value];
  }
  return arr;
}

// node_modules/es-toolkit/dist/compat/object/toPairs.mjs
function toPairs(object) {
  if (object == null) return [];
  if (object instanceof Set) return setToEntries(object);
  if (object instanceof Map) return mapToEntries(object);
  const keys$1 = keys(object);
  const result2 = new Array(keys$1.length);
  for (let i = 0; i < keys$1.length; i++) {
    const key2 = keys$1[i];
    result2[i] = [key2, object[key2]];
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/object/toPairsIn.mjs
function toPairsIn(object) {
  if (object == null) return [];
  if (object instanceof Set) return setToEntries(object);
  if (object instanceof Map) return mapToEntries(object);
  const keys2 = keysIn(object);
  const result2 = new Array(keys2.length);
  for (let i = 0; i < keys2.length; i++) {
    const key2 = keys2[i];
    result2[i] = [key2, object[key2]];
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/predicate/isBuffer.mjs
function isBuffer2(x) {
  return isBuffer(x);
}

// node_modules/es-toolkit/dist/compat/object/transform.mjs
function transform(object, iteratee$1 = identity, accumulator) {
  const isArrayOrBufferOrTypedArray = Array.isArray(object) || isBuffer2(object) || isTypedArray2(object);
  iteratee$1 = iteratee(iteratee$1);
  if (accumulator == null) if (isArrayOrBufferOrTypedArray) accumulator = [];
  else if (isObject(object) && isFunction(object.constructor)) accumulator = Object.create(Object.getPrototypeOf(object));
  else accumulator = {};
  if (object == null) return accumulator;
  forEach(object, (value, key2, object2) => iteratee$1(accumulator, value, key2, object2));
  return accumulator;
}

// node_modules/es-toolkit/dist/compat/object/update.mjs
function update(obj, path, updater) {
  return updateWith(obj, path, updater, () => void 0);
}

// node_modules/es-toolkit/dist/compat/object/valuesIn.mjs
function valuesIn(object) {
  const keys2 = keysIn(object);
  const result2 = new Array(keys2.length);
  for (let i = 0; i < keys2.length; i++) result2[i] = object[keys2[i]];
  return result2;
}

// node_modules/es-toolkit/dist/compat/predicate/isFunction.mjs
function isFunction2(value) {
  return typeof value === "function";
}

// node_modules/es-toolkit/dist/compat/predicate/isLength.mjs
function isLength2(value) {
  return Number.isSafeInteger(value) && value >= 0;
}

// node_modules/es-toolkit/dist/compat/predicate/isNative.mjs
var functionToString = Function.prototype.toString;
var IS_NATIVE_FUNCTION_REGEXP = RegExp(`^${functionToString.call(Object.prototype.hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?")}$`);
function isNative(value) {
  if (typeof value !== "function") return false;
  if (globalThis?.["__core-js_shared__"] != null) throw new Error("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");
  return IS_NATIVE_FUNCTION_REGEXP.test(functionToString.call(value));
}

// node_modules/es-toolkit/dist/compat/predicate/isNull.mjs
function isNull2(value) {
  return value === null;
}

// node_modules/es-toolkit/dist/compat/predicate/isUndefined.mjs
function isUndefined2(x) {
  return isUndefined(x);
}

// node_modules/es-toolkit/dist/compat/predicate/conformsTo.mjs
function conformsTo(target, source) {
  if (source == null) return true;
  if (target == null) return Object.keys(source).length === 0;
  const keys2 = Object.keys(source);
  for (let i = 0; i < keys2.length; i++) {
    const key2 = keys2[i];
    const predicate = source[key2];
    const value = target[key2];
    if (value === void 0 && !(key2 in target)) return false;
    if (typeof predicate === "function" && !predicate(value)) return false;
  }
  return true;
}

// node_modules/es-toolkit/dist/compat/predicate/conforms.mjs
function conforms(source) {
  source = cloneDeep(source);
  return function(object) {
    return conformsTo(object, source);
  };
}

// node_modules/es-toolkit/dist/compat/predicate/isArrayBuffer.mjs
function isArrayBuffer2(value) {
  return isArrayBuffer(value);
}

// node_modules/es-toolkit/dist/compat/predicate/isBoolean.mjs
function isBoolean2(value) {
  return typeof value === "boolean" || value instanceof Boolean;
}

// node_modules/es-toolkit/dist/compat/predicate/isDate.mjs
function isDate2(value) {
  return isDate(value);
}

// node_modules/es-toolkit/dist/compat/predicate/isElement.mjs
function isElement(value) {
  return isObjectLike(value) && value.nodeType === 1 && !isPlainObject2(value);
}

// node_modules/es-toolkit/dist/compat/predicate/isEmpty.mjs
function isEmpty(value) {
  if (value == null) return true;
  if (isArrayLike(value)) {
    if (typeof value.splice !== "function" && typeof value !== "string" && !isBuffer(value) && !isTypedArray2(value) && !isArguments(value)) return false;
    return value.length === 0;
  }
  if (typeof value === "object") {
    if (value instanceof Map || value instanceof Set) return value.size === 0;
    const keys2 = Object.keys(value);
    if (isPrototype(value)) return keys2.filter((x) => x !== "constructor").length === 0;
    return keys2.length === 0;
  }
  return true;
}

// node_modules/es-toolkit/dist/compat/predicate/isEqualWith.mjs
function isEqualWith2(a, b, areValuesEqual) {
  if (typeof areValuesEqual !== "function") areValuesEqual = () => void 0;
  return isEqualWith(a, b, (...args) => {
    const result2 = areValuesEqual(...args);
    if (result2 !== void 0) return Boolean(result2);
    if (a instanceof Map && b instanceof Map) return isEqualWith2(Array.from(a), Array.from(b), after(2, areValuesEqual));
    if (a instanceof Set && b instanceof Set) return isEqualWith2(Array.from(a), Array.from(b), after(2, areValuesEqual));
  });
}

// node_modules/es-toolkit/dist/compat/predicate/isError.mjs
function isError2(value) {
  return getTag(value) === "[object Error]";
}

// node_modules/es-toolkit/dist/compat/predicate/isFinite.mjs
function isFinite(value) {
  return Number.isFinite(value);
}

// node_modules/es-toolkit/dist/compat/predicate/isInteger.mjs
function isInteger(value) {
  return Number.isInteger(value);
}

// node_modules/es-toolkit/dist/compat/predicate/isRegExp.mjs
function isRegExp2(value) {
  return isRegExp(value);
}

// node_modules/es-toolkit/dist/compat/predicate/isSafeInteger.mjs
function isSafeInteger(value) {
  return Number.isSafeInteger(value);
}

// node_modules/es-toolkit/dist/compat/predicate/isSet.mjs
function isSet2(value) {
  return isSet(value);
}

// node_modules/es-toolkit/dist/compat/predicate/isWeakMap.mjs
function isWeakMap2(value) {
  return isWeakMap(value);
}

// node_modules/es-toolkit/dist/compat/predicate/isWeakSet.mjs
function isWeakSet2(value) {
  return isWeakSet(value);
}

// node_modules/es-toolkit/dist/compat/string/capitalize.mjs
function capitalize2(str) {
  return capitalize(toString(str));
}

// node_modules/es-toolkit/dist/compat/util/bindAll.mjs
function bindAll(object, ...methodNames) {
  if (object == null) return object;
  if (!isObject(object)) return object;
  if (isArray(object) && methodNames.length === 0) return object;
  const methods = [];
  for (let i = 0; i < methodNames.length; i++) {
    const name = methodNames[i];
    if (isArray(name)) methods.push(...name);
    else if (name && typeof name === "object" && "length" in name) methods.push(...Array.from(name));
    else methods.push(name);
  }
  if (methods.length === 0) return object;
  for (let i = 0; i < methods.length; i++) {
    const key2 = methods[i];
    const stringKey = toString(key2);
    const func = object[stringKey];
    if (isFunction(func)) object[stringKey] = func.bind(object);
  }
  return object;
}

// node_modules/es-toolkit/dist/compat/string/deburr.mjs
function deburr2(str) {
  return deburr(toString(str));
}

// node_modules/es-toolkit/dist/compat/_internal/normalizeForCase.mjs
function normalizeForCase(str) {
  if (typeof str !== "string") str = toString(str);
  return str.replace(/['\u2019]/g, "");
}

// node_modules/es-toolkit/dist/compat/string/camelCase.mjs
function camelCase2(str) {
  return camelCase(normalizeForCase(deburr2(str)));
}

// node_modules/es-toolkit/dist/compat/string/endsWith.mjs
function endsWith(str, target, position) {
  if (str == null || target == null) return false;
  if (position == null) position = str.length;
  return str.endsWith(target, position);
}

// node_modules/es-toolkit/dist/compat/string/escape.mjs
function escape2(string) {
  return escape(toString(string));
}

// node_modules/es-toolkit/dist/compat/string/escapeRegExp.mjs
function escapeRegExp2(str) {
  return escapeRegExp(toString(str));
}

// node_modules/es-toolkit/dist/compat/string/kebabCase.mjs
function kebabCase2(str) {
  return kebabCase(normalizeForCase(deburr2(str)));
}

// node_modules/es-toolkit/dist/compat/string/lowerCase.mjs
function lowerCase2(str) {
  return lowerCase(normalizeForCase(deburr2(str)));
}

// node_modules/es-toolkit/dist/compat/string/lowerFirst.mjs
function lowerFirst2(str) {
  return lowerFirst(toString(str));
}

// node_modules/es-toolkit/dist/compat/string/pad.mjs
function pad2(str, length, chars) {
  return pad(toString(str), length, chars);
}

// node_modules/es-toolkit/dist/compat/string/padEnd.mjs
function padEnd(str, length = 0, chars = " ") {
  return toString(str).padEnd(length, chars);
}

// node_modules/es-toolkit/dist/compat/string/padStart.mjs
function padStart(str, length = 0, chars = " ") {
  return toString(str).padStart(length, chars);
}

// node_modules/es-toolkit/dist/compat/_internal/MAX_SAFE_INTEGER.mjs
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;

// node_modules/es-toolkit/dist/compat/string/repeat.mjs
function repeat(str, n, guard) {
  if (guard ? isIterateeCall(str, n, guard) : n === void 0) n = 1;
  else n = toInteger(n);
  if (n < 1 || n > MAX_SAFE_INTEGER) return "";
  return toString(str).repeat(n);
}

// node_modules/es-toolkit/dist/compat/string/replace.mjs
function replace(target, pattern, replacement) {
  if (arguments.length < 3) return toString(target);
  return toString(target).replace(pattern, replacement);
}

// node_modules/es-toolkit/dist/compat/string/snakeCase.mjs
function snakeCase2(str) {
  return snakeCase(normalizeForCase(deburr2(str)));
}

// node_modules/es-toolkit/dist/compat/string/split.mjs
function split(string, separator, limit) {
  return toString(string).split(separator, limit);
}

// node_modules/es-toolkit/dist/compat/string/startCase.mjs
function startCase2(str) {
  const words$1 = words(normalizeForCase(deburr2(str)).trim());
  let result2 = "";
  for (let i = 0; i < words$1.length; i++) {
    const word = words$1[i];
    if (result2) result2 += " ";
    if (word === word.toUpperCase()) result2 += word;
    else result2 += word[0].toUpperCase() + word.slice(1).toLowerCase();
  }
  return result2;
}

// node_modules/es-toolkit/dist/compat/string/startsWith.mjs
function startsWith(str, target, position) {
  if (str == null || target == null) return false;
  if (position == null) position = 0;
  return str.startsWith(target, position);
}

// node_modules/es-toolkit/dist/compat/string/template.mjs
var esTemplateRegExp = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
var unEscapedRegExp = /['\n\r\u2028\u2029\\]/g;
var noMatchExp = /($^)/;
var escapeMap = /* @__PURE__ */ new Map([
  ["\\", "\\"],
  ["'", "'"],
  ["\n", "n"],
  ["\r", "r"],
  ["\u2028", "u2028"],
  ["\u2029", "u2029"]
]);
function escapeString(match) {
  return `\\${escapeMap.get(match)}`;
}
var defaultInterpolateRegExp = /<%=([\s\S]+?)%>/g;
var templateSettings = {
  escape: /<%-([\s\S]+?)%>/g,
  evaluate: /<%([\s\S]+?)%>/g,
  interpolate: defaultInterpolateRegExp,
  variable: "",
  imports: { _: {
    escape: escape2,
    template
  } }
};
function template(string, options, guard) {
  string = toString(string);
  if (guard) options = templateSettings;
  options = defaults({ ...options }, templateSettings);
  const delimitersRegExp = new RegExp([
    options.escape?.source ?? noMatchExp.source,
    options.interpolate?.source ?? noMatchExp.source,
    options.interpolate === defaultInterpolateRegExp ? esTemplateRegExp.source : noMatchExp.source,
    options.evaluate?.source ?? noMatchExp.source,
    "$"
  ].join("|"), "g");
  let lastIndex = 0;
  let isEvaluated = false;
  let source = `__p += ''`;
  for (const match of string.matchAll(delimitersRegExp)) {
    const [fullMatch, escapeValue, interpolateValue, esTemplateValue, evaluateValue] = match;
    const { index } = match;
    source += ` + '${string.slice(lastIndex, index).replace(unEscapedRegExp, escapeString)}'`;
    if (escapeValue) source += ` + _.escape(${escapeValue})`;
    if (interpolateValue) source += ` + ((${interpolateValue}) == null ? '' : ${interpolateValue})`;
    else if (esTemplateValue) source += ` + ((${esTemplateValue}) == null ? '' : ${esTemplateValue})`;
    if (evaluateValue) {
      source += `;
${evaluateValue};
 __p += ''`;
      isEvaluated = true;
    }
    lastIndex = index + fullMatch.length;
  }
  const imports = defaults({ ...options.imports }, templateSettings.imports);
  const importsKeys = Object.keys(imports);
  const importValues = Object.values(imports);
  const sourceURL = `//# sourceURL=${options.sourceURL ? String(options.sourceURL).replace(/[\r\n]/g, " ") : `es-toolkit.templateSource[${Date.now()}]`}
`;
  const compiledFunction = `function(${options.variable || "obj"}) {
    let __p = '';
    ${options.variable ? "" : "if (obj == null) { obj = {}; }"}
    ${isEvaluated ? `function print() { __p += Array.prototype.join.call(arguments, ''); }` : ""}
    ${options.variable ? source : `with(obj) {
${source}
}`}
    return __p;
  }`;
  const result2 = attempt2(() => new Function(...importsKeys, `${sourceURL}return ${compiledFunction}`)(...importValues));
  result2.source = compiledFunction;
  if (result2 instanceof Error) throw result2;
  return result2;
}

// node_modules/es-toolkit/dist/compat/string/toLower.mjs
function toLower(value) {
  return toString(value).toLowerCase();
}

// node_modules/es-toolkit/dist/compat/string/toUpper.mjs
function toUpper(value) {
  return toString(value).toUpperCase();
}

// node_modules/es-toolkit/dist/compat/string/trim.mjs
function trim2(str, chars, guard) {
  if (str == null) return "";
  if (guard != null || chars == null) return str.toString().trim();
  switch (typeof chars) {
    case "object":
      if (Array.isArray(chars)) return trim(str, chars.flatMap((x) => x.toString().split("")));
      else return trim(str, chars.toString().split(""));
    default:
      return trim(str, chars.toString().split(""));
  }
}

// node_modules/es-toolkit/dist/compat/string/trimEnd.mjs
function trimEnd2(str, chars, guard) {
  if (str == null) return "";
  if (guard != null || chars == null) return str.toString().trimEnd();
  return trimEnd(str, chars.toString().split(""));
}

// node_modules/es-toolkit/dist/compat/string/trimStart.mjs
function trimStart2(str, chars, guard) {
  if (str == null) return "";
  if (guard != null || chars == null) return str.toString().trimStart();
  return trimStart(str, chars.toString().split(""));
}

// node_modules/es-toolkit/dist/compat/string/truncate.mjs
var regexMultiByte = /[\u200d\ud800-\udfff\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff\ufe0e\ufe0f]/;
function truncate(string, options) {
  string = string != null ? `${string}` : "";
  let length = 30;
  let omission = "...";
  if (isObject(options)) {
    length = parseLength(options.length);
    omission = "omission" in options ? `${options.omission}` : "...";
  }
  let i = string.length;
  const lengthOmission = Array.from(omission).length;
  const lengthBase = Math.max(length - lengthOmission, 0);
  let strArray = void 0;
  if (regexMultiByte.test(string)) {
    strArray = Array.from(string);
    i = strArray.length;
  }
  if (length >= i) return string;
  if (i <= lengthOmission) return omission;
  let base = strArray === void 0 ? string.slice(0, lengthBase) : strArray?.slice(0, lengthBase).join("");
  const separator = options?.separator;
  if (!separator) {
    base += omission;
    return base;
  }
  const search = separator instanceof RegExp ? separator.source : separator;
  const flags = "u" + (separator instanceof RegExp ? separator.flags.replace("u", "") : "");
  const withoutSeparator = new RegExp(`(?<result>.*(?:(?!${search}).))(?:${search})`, flags).exec(base);
  return (!withoutSeparator?.groups ? base : withoutSeparator.groups.result) + omission;
}
function parseLength(length) {
  if (length == null) return 30;
  if (length <= 0) return 0;
  return length;
}

// node_modules/es-toolkit/dist/compat/string/unescape.mjs
function unescape2(str) {
  return unescape(toString(str));
}

// node_modules/es-toolkit/dist/compat/string/upperCase.mjs
function upperCase2(str) {
  return upperCase(normalizeForCase(deburr2(str)));
}

// node_modules/es-toolkit/dist/compat/string/upperFirst.mjs
function upperFirst2(str) {
  return upperFirst(toString(str));
}

// node_modules/es-toolkit/dist/compat/string/words.mjs
var rNonCharLatin = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\xd7\\xf7";
var rUnicodeUpper = "\\p{Lu}";
var rUnicodeLower = "\\p{Ll}";
var rMisc = "(?:[\\p{Lm}\\p{Lo}]\\p{M}*)";
var rNumber = "\\d";
var rUnicodeOptContrLower = "(?:['’](?:d|ll|m|re|s|t|ve))?";
var rUnicodeOptContrUpper = "(?:['’](?:D|LL|M|RE|S|T|VE))?";
var rUnicodeBreak = `[\\p{Z}\\p{P}${rNonCharLatin}]`;
var rUnicodeMiscUpper = `(?:${rUnicodeUpper}|${rMisc})`;
var rUnicodeMiscLower = `(?:${rUnicodeLower}|${rMisc})`;
var rUnicodeWord = RegExp([
  `${rUnicodeUpper}?${rUnicodeLower}+${rUnicodeOptContrLower}(?=${rUnicodeBreak}|${rUnicodeUpper}|$)`,
  `${rUnicodeMiscUpper}+${rUnicodeOptContrUpper}(?=${rUnicodeBreak}|${rUnicodeUpper}${rUnicodeMiscLower}|$)`,
  `${rUnicodeUpper}?${rUnicodeMiscLower}+${rUnicodeOptContrLower}`,
  `${rUnicodeUpper}+${rUnicodeOptContrUpper}`,
  `${rNumber}*(?:1ST|2ND|3RD|(?![123])${rNumber}TH)(?=\\b|[a-z_])`,
  `${rNumber}*(?:1st|2nd|3rd|(?![123])${rNumber}th)(?=\\b|[A-Z_])`,
  `${rNumber}+`,
  "\\p{Emoji_Presentation}",
  "\\p{Extended_Pictographic}"
].join("|"), "gu");
function words2(str, pattern = rUnicodeWord, guard) {
  const input = toString(str);
  if (guard) pattern = rUnicodeWord;
  if (typeof pattern === "number") pattern = pattern.toString();
  return Array.from(input.match(pattern) ?? []).filter((x) => x !== "");
}

// node_modules/es-toolkit/dist/compat/util/cond.mjs
function cond(pairs) {
  const length = pairs.length;
  const processedPairs = pairs.map((pair) => {
    const predicate = pair[0];
    const func = pair[1];
    if (!isFunction(func)) throw new TypeError("Expected a function");
    return [iteratee(predicate), func];
  });
  return function(...args) {
    for (let i = 0; i < length; i++) {
      const pair = processedPairs[i];
      const predicate = pair[0];
      const func = pair[1];
      if (predicate.apply(this, args)) return func.apply(this, args);
    }
  };
}

// node_modules/es-toolkit/dist/compat/util/constant.mjs
function constant(value) {
  return () => value;
}

// node_modules/es-toolkit/dist/compat/util/defaultTo.mjs
function defaultTo(value, defaultValue) {
  if (value == null || Number.isNaN(value)) return defaultValue;
  return value;
}

// node_modules/es-toolkit/dist/compat/util/gt.mjs
function gt(value, other) {
  if (typeof value === "string" && typeof other === "string") return value > other;
  return toNumber(value) > toNumber(other);
}

// node_modules/es-toolkit/dist/compat/util/gte.mjs
function gte(value, other) {
  if (typeof value === "string" && typeof other === "string") return value >= other;
  return toNumber(value) >= toNumber(other);
}

// node_modules/es-toolkit/dist/compat/util/invoke.mjs
function invoke(object, path, ...args) {
  args = args.flat(1);
  if (object == null) return;
  switch (typeof path) {
    case "string":
      if (typeof object === "object" && Object.hasOwn(object, path)) return invokeImpl(object, [path], args);
      return invokeImpl(object, toPath(path), args);
    case "number":
    case "symbol":
      return invokeImpl(object, [path], args);
    default:
      if (Array.isArray(path)) return invokeImpl(object, path, args);
      else return invokeImpl(object, [path], args);
  }
}
function invokeImpl(object, path, args) {
  const parent = get(object, path.slice(0, -1), object);
  if (parent == null) return;
  let lastKey = last2(path);
  const lastValue = lastKey?.valueOf();
  if (typeof lastValue === "number") lastKey = toKey(lastValue);
  else lastKey = String(lastKey);
  return get(parent, lastKey)?.apply(parent, args);
}

// node_modules/es-toolkit/dist/compat/util/lt.mjs
function lt(value, other) {
  if (typeof value === "string" && typeof other === "string") return value < other;
  return toNumber(value) < toNumber(other);
}

// node_modules/es-toolkit/dist/compat/util/lte.mjs
function lte(value, other) {
  if (typeof value === "string" && typeof other === "string") return value <= other;
  return toNumber(value) <= toNumber(other);
}

// node_modules/es-toolkit/dist/compat/util/method.mjs
function method(path, ...args) {
  return function(object) {
    return invoke(object, path, args);
  };
}

// node_modules/es-toolkit/dist/compat/util/methodOf.mjs
function methodOf(object, ...args) {
  return function(path) {
    return invoke(object, path, args);
  };
}

// node_modules/es-toolkit/dist/compat/util/now.mjs
function now() {
  return Date.now();
}

// node_modules/es-toolkit/dist/compat/util/over.mjs
function over(...iteratees) {
  if (iteratees.length === 1 && Array.isArray(iteratees[0])) iteratees = iteratees[0];
  const funcs = iteratees.map((item) => iteratee(item));
  return function(...args) {
    return funcs.map((func) => func.apply(this, args));
  };
}

// node_modules/es-toolkit/dist/compat/util/overEvery.mjs
function overEvery(...predicates) {
  return function(...values2) {
    for (let i = 0; i < predicates.length; ++i) {
      const predicate = predicates[i];
      if (!Array.isArray(predicate)) {
        if (!iteratee(predicate).apply(this, values2)) return false;
        continue;
      }
      for (let j = 0; j < predicate.length; ++j) if (!iteratee(predicate[j]).apply(this, values2)) return false;
    }
    return true;
  };
}

// node_modules/es-toolkit/dist/compat/util/overSome.mjs
function overSome(...predicates) {
  return function(...values2) {
    for (let i = 0; i < predicates.length; ++i) {
      const predicate = predicates[i];
      if (!Array.isArray(predicate)) {
        if (iteratee(predicate).apply(this, values2)) return true;
        continue;
      }
      for (let j = 0; j < predicate.length; ++j) if (iteratee(predicate[j]).apply(this, values2)) return true;
    }
    return false;
  };
}

// node_modules/es-toolkit/dist/compat/util/stubArray.mjs
function stubArray() {
  return [];
}

// node_modules/es-toolkit/dist/compat/util/stubFalse.mjs
function stubFalse() {
  return false;
}

// node_modules/es-toolkit/dist/compat/util/stubObject.mjs
function stubObject() {
  return {};
}

// node_modules/es-toolkit/dist/compat/util/stubString.mjs
function stubString() {
  return "";
}

// node_modules/es-toolkit/dist/compat/util/stubTrue.mjs
function stubTrue() {
  return true;
}

// node_modules/es-toolkit/dist/compat/_internal/MAX_ARRAY_LENGTH.mjs
var MAX_ARRAY_LENGTH = 4294967295;

// node_modules/es-toolkit/dist/compat/util/toLength.mjs
function toLength(value) {
  if (value == null) return 0;
  return clamp2(Math.floor(Number(value)), 0, MAX_ARRAY_LENGTH);
}

// node_modules/es-toolkit/dist/compat/util/toPlainObject.mjs
function toPlainObject(value) {
  const plainObject = {};
  const valueKeys = keysIn(value);
  for (let i = 0; i < valueKeys.length; i++) {
    const key2 = valueKeys[i];
    const objValue = value[key2];
    if (key2 === "__proto__") Object.defineProperty(plainObject, key2, {
      configurable: true,
      enumerable: true,
      value: objValue,
      writable: true
    });
    else plainObject[key2] = objValue;
  }
  return plainObject;
}

// node_modules/es-toolkit/dist/compat/util/toSafeInteger.mjs
function toSafeInteger(value) {
  if (value == null) return 0;
  return clamp2(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);
}

// node_modules/es-toolkit/dist/compat/util/uniqueId.mjs
var idCounter = 0;
function uniqueId(prefix = "") {
  return `${prefix}${++idCounter}`;
}

// node_modules/es-toolkit/dist/_virtual/_rolldown/runtime.mjs
var __defProp = Object.defineProperty;
var __exportAll = (all, no_symbols) => {
  let target = {};
  for (var name in all) __defProp(target, name, {
    get: all[name],
    enumerable: true
  });
  if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
  return target;
};

// node_modules/es-toolkit/dist/compat/compat.mjs
var compat_exports = __exportAll({
  add: () => add,
  after: () => after2,
  ary: () => ary2,
  assign: () => assign,
  assignIn: () => assignIn,
  assignInWith: () => assignInWith,
  assignWith: () => assignWith,
  at: () => at2,
  attempt: () => attempt2,
  before: () => before2,
  bind: () => bind,
  bindAll: () => bindAll,
  bindKey: () => bindKey,
  camelCase: () => camelCase2,
  capitalize: () => capitalize2,
  castArray: () => castArray,
  ceil: () => ceil,
  chunk: () => chunk2,
  clamp: () => clamp2,
  clone: () => clone2,
  cloneDeep: () => cloneDeep2,
  cloneDeepWith: () => cloneDeepWith2,
  cloneWith: () => cloneWith,
  compact: () => compact2,
  concat: () => concat,
  cond: () => cond,
  conforms: () => conforms,
  conformsTo: () => conformsTo,
  constant: () => constant,
  countBy: () => countBy2,
  create: () => create,
  curry: () => curry2,
  curryRight: () => curryRight2,
  debounce: () => debounce2,
  deburr: () => deburr2,
  defaultTo: () => defaultTo,
  defaults: () => defaults,
  defaultsDeep: () => defaultsDeep,
  defer: () => defer,
  delay: () => delay2,
  difference: () => difference2,
  differenceBy: () => differenceBy2,
  differenceWith: () => differenceWith2,
  divide: () => divide,
  drop: () => drop2,
  dropRight: () => dropRight2,
  dropRightWhile: () => dropRightWhile2,
  dropWhile: () => dropWhile2,
  each: () => forEach,
  eachRight: () => forEachRight2,
  endsWith: () => endsWith,
  eq: () => isEqualsSameValueZero,
  escape: () => escape2,
  escapeRegExp: () => escapeRegExp2,
  every: () => every,
  extend: () => assignIn,
  extendWith: () => assignInWith,
  fill: () => fill2,
  filter: () => filter,
  find: () => find,
  findIndex: () => findIndex,
  findKey: () => findKey2,
  findLast: () => findLast,
  findLastIndex: () => findLastIndex,
  findLastKey: () => findLastKey,
  first: () => head2,
  flatMap: () => flatMap2,
  flatMapDeep: () => flatMapDeep2,
  flatMapDepth: () => flatMapDepth,
  flatten: () => flatten2,
  flattenDeep: () => flattenDeep2,
  flattenDepth: () => flattenDepth,
  flip: () => flip,
  floor: () => floor,
  flow: () => flow2,
  flowRight: () => flowRight2,
  forEach: () => forEach,
  forEachRight: () => forEachRight2,
  forIn: () => forIn,
  forInRight: () => forInRight,
  forOwn: () => forOwn,
  forOwnRight: () => forOwnRight,
  fromPairs: () => fromPairs,
  functions: () => functions,
  functionsIn: () => functionsIn,
  get: () => get,
  groupBy: () => groupBy2,
  gt: () => gt,
  gte: () => gte,
  has: () => has,
  hasIn: () => hasIn,
  head: () => head2,
  identity: () => identity2,
  inRange: () => inRange2,
  includes: () => includes,
  indexOf: () => indexOf,
  initial: () => initial2,
  intersection: () => intersection2,
  intersectionBy: () => intersectionBy2,
  intersectionWith: () => intersectionWith2,
  invert: () => invert2,
  invertBy: () => invertBy,
  invoke: () => invoke,
  invokeMap: () => invokeMap,
  isArguments: () => isArguments,
  isArray: () => isArray,
  isArrayBuffer: () => isArrayBuffer2,
  isArrayLike: () => isArrayLike,
  isArrayLikeObject: () => isArrayLikeObject,
  isBoolean: () => isBoolean2,
  isBuffer: () => isBuffer2,
  isDate: () => isDate2,
  isElement: () => isElement,
  isEmpty: () => isEmpty,
  isEqual: () => isEqual,
  isEqualWith: () => isEqualWith2,
  isError: () => isError2,
  isFinite: () => isFinite,
  isFunction: () => isFunction2,
  isInteger: () => isInteger,
  isLength: () => isLength2,
  isMap: () => isMap2,
  isMatch: () => isMatch,
  isMatchWith: () => isMatchWith,
  isNaN: () => isNaN,
  isNative: () => isNative,
  isNil: () => isNil2,
  isNull: () => isNull2,
  isNumber: () => isNumber2,
  isObject: () => isObject,
  isObjectLike: () => isObjectLike,
  isPlainObject: () => isPlainObject2,
  isRegExp: () => isRegExp2,
  isSafeInteger: () => isSafeInteger,
  isSet: () => isSet2,
  isString: () => isString2,
  isSymbol: () => isSymbol,
  isTypedArray: () => isTypedArray2,
  isUndefined: () => isUndefined2,
  isWeakMap: () => isWeakMap2,
  isWeakSet: () => isWeakSet2,
  iteratee: () => iteratee,
  join: () => join,
  kebabCase: () => kebabCase2,
  keyBy: () => keyBy2,
  keys: () => keys,
  keysIn: () => keysIn,
  last: () => last2,
  lastIndexOf: () => lastIndexOf,
  lowerCase: () => lowerCase2,
  lowerFirst: () => lowerFirst2,
  lt: () => lt,
  lte: () => lte,
  map: () => map,
  mapKeys: () => mapKeys2,
  mapValues: () => mapValues2,
  matches: () => matches,
  matchesProperty: () => matchesProperty,
  max: () => max,
  maxBy: () => maxBy2,
  mean: () => mean2,
  meanBy: () => meanBy2,
  memoize: () => memoize2,
  merge: () => merge2,
  mergeWith: () => mergeWith2,
  method: () => method,
  methodOf: () => methodOf,
  min: () => min,
  minBy: () => minBy2,
  multiply: () => multiply,
  negate: () => negate2,
  noop: () => noop2,
  now: () => now,
  nth: () => nth,
  nthArg: () => nthArg,
  omit: () => omit2,
  omitBy: () => omitBy2,
  once: () => once2,
  orderBy: () => orderBy2,
  over: () => over,
  overArgs: () => overArgs,
  overEvery: () => overEvery,
  overSome: () => overSome,
  pad: () => pad2,
  padEnd: () => padEnd,
  padStart: () => padStart,
  parseInt: () => parseInt2,
  partial: () => partial2,
  partialRight: () => partialRight2,
  partition: () => partition2,
  pick: () => pick2,
  pickBy: () => pickBy2,
  property: () => property,
  propertyOf: () => propertyOf,
  pull: () => pull2,
  pullAll: () => pullAll,
  pullAllBy: () => pullAllBy,
  pullAllWith: () => pullAllWith,
  pullAt: () => pullAt2,
  random: () => random2,
  range: () => range2,
  rangeRight: () => rangeRight2,
  rearg: () => rearg,
  reduce: () => reduce,
  reduceRight: () => reduceRight,
  reject: () => reject,
  remove: () => remove2,
  repeat: () => repeat,
  replace: () => replace,
  rest: () => rest2,
  result: () => result,
  reverse: () => reverse,
  round: () => round2,
  sample: () => sample2,
  sampleSize: () => sampleSize2,
  set: () => set,
  setWith: () => setWith,
  shuffle: () => shuffle2,
  size: () => size,
  slice: () => slice,
  snakeCase: () => snakeCase2,
  some: () => some,
  sortBy: () => sortBy2,
  sortedIndex: () => sortedIndex,
  sortedIndexBy: () => sortedIndexBy,
  sortedIndexOf: () => sortedIndexOf,
  sortedLastIndex: () => sortedLastIndex,
  sortedLastIndexBy: () => sortedLastIndexBy,
  sortedLastIndexOf: () => sortedLastIndexOf,
  split: () => split,
  spread: () => spread2,
  startCase: () => startCase2,
  startsWith: () => startsWith,
  stubArray: () => stubArray,
  stubFalse: () => stubFalse,
  stubObject: () => stubObject,
  stubString: () => stubString,
  stubTrue: () => stubTrue,
  subtract: () => subtract,
  sum: () => sum2,
  sumBy: () => sumBy2,
  tail: () => tail2,
  take: () => take2,
  takeRight: () => takeRight2,
  takeRightWhile: () => takeRightWhile2,
  takeWhile: () => takeWhile2,
  template: () => template,
  templateSettings: () => templateSettings,
  throttle: () => throttle2,
  times: () => times,
  toArray: () => toArray2,
  toDefaulted: () => toDefaulted,
  toFinite: () => toFinite,
  toInteger: () => toInteger,
  toLength: () => toLength,
  toLower: () => toLower,
  toNumber: () => toNumber,
  toPairs: () => toPairs,
  toPairsIn: () => toPairsIn,
  toPath: () => toPath,
  toPlainObject: () => toPlainObject,
  toSafeInteger: () => toSafeInteger,
  toString: () => toString,
  toUpper: () => toUpper,
  transform: () => transform,
  trim: () => trim2,
  trimEnd: () => trimEnd2,
  trimStart: () => trimStart2,
  truncate: () => truncate,
  unary: () => unary2,
  unescape: () => unescape2,
  union: () => union2,
  unionBy: () => unionBy2,
  unionWith: () => unionWith2,
  uniq: () => uniq2,
  uniqBy: () => uniqBy2,
  uniqWith: () => uniqWith2,
  uniqueId: () => uniqueId,
  unset: () => unset,
  unzip: () => unzip2,
  unzipWith: () => unzipWith2,
  update: () => update,
  updateWith: () => updateWith,
  upperCase: () => upperCase2,
  upperFirst: () => upperFirst2,
  values: () => values,
  valuesIn: () => valuesIn,
  without: () => without2,
  words: () => words2,
  wrap: () => wrap,
  xor: () => xor2,
  xorBy: () => xorBy2,
  xorWith: () => xorWith2,
  zip: () => zip2,
  zipObject: () => zipObject2,
  zipObjectDeep: () => zipObjectDeep,
  zipWith: () => zipWith2
});

// node_modules/es-toolkit/dist/compat/toolkit.mjs
var toolkit = ((value) => {
  return value;
});
Object.assign(toolkit, compat_exports);
toolkit.partial.placeholder = toolkit;
toolkit.partialRight.placeholder = toolkit;

// node_modules/laravel-precognition/dist/form.js
var isFile2 = (value) => typeof File !== "undefined" && value instanceof File || value instanceof Blob || typeof FileList !== "undefined" && value instanceof FileList && value.length > 0;
var hasFiles = (data) => {
  if (data instanceof FormData) {
    return true;
  }
  return isFile2(data) || typeof data === "object" && data !== null && Object.values(data).some((value) => hasFiles(value));
};

// node_modules/laravel-precognition/dist/http/errors.js
var HttpResponseError = class extends Error {
  response;
  constructor(response) {
    super(`HTTP error ${response.status}`);
    this.name = "HttpResponseError";
    this.response = response;
  }
};
var HttpCancelledError = class extends Error {
  constructor(message = "Request was cancelled") {
    super(message);
    this.name = "HttpCancelledError";
  }
};
var HttpNetworkError = class extends Error {
  constructor(message = "Network error") {
    super(message);
    this.name = "HttpNetworkError";
  }
};

// node_modules/laravel-precognition/dist/http/url.js
function buildQueryString(params) {
  const searchParams = new URLSearchParams();
  Object.entries(params).forEach(([key2, value]) => {
    if (value === void 0 || value === null) {
      return;
    }
    if (Array.isArray(value)) {
      value.forEach((item) => searchParams.append(`${key2}[]`, String(item)));
    } else if (typeof value === "object") {
      searchParams.append(key2, JSON.stringify(value));
    } else {
      searchParams.append(key2, String(value));
    }
  });
  return searchParams.toString();
}
function buildUrl(url, baseURL2, params) {
  if (baseURL2 && !url.startsWith("http://") && !url.startsWith("https://")) {
    url = baseURL2.replace(/\/$/, "") + "/" + url.replace(/^\//, "");
  }
  if (params && Object.keys(params).length > 0) {
    const queryString = buildQueryString(params);
    if (queryString) {
      url += (url.includes("?") ? "&" : "?") + queryString;
    }
  }
  return url;
}

// node_modules/laravel-precognition/dist/http/fetchClient.js
function getAjaxHeader() {
  if (typeof window === "undefined") {
    return null;
  }
  return window.axios?.defaults?.headers?.common?.["X-Requested-With"] ?? null;
}
function toFormData(data, formData = new FormData(), parentKey = null) {
  for (const key2 in data) {
    if (Object.prototype.hasOwnProperty.call(data, key2)) {
      appendToFormData(formData, parentKey ? `${parentKey}[${key2}]` : key2, data[key2]);
    }
  }
  return formData;
}
function appendToFormData(formData, key2, value) {
  if (Array.isArray(value)) {
    return value.forEach((val, index) => appendToFormData(formData, `${key2}[${index}]`, val));
  } else if (value instanceof Date) {
    return formData.append(key2, value.toISOString());
  } else if (typeof File !== "undefined" && value instanceof File) {
    return formData.append(key2, value, value.name);
  } else if (value instanceof Blob) {
    return formData.append(key2, value);
  } else if (typeof value === "boolean") {
    return formData.append(key2, value ? "1" : "0");
  } else if (typeof value === "string") {
    return formData.append(key2, value);
  } else if (typeof value === "number") {
    return formData.append(key2, `${value}`);
  } else if (value === null || value === void 0) {
    return formData.append(key2, "");
  }
  toFormData(value, formData, key2);
}
function prepareBody(data, headers) {
  if (data === void 0 || data === null) {
    return void 0;
  }
  if (data instanceof FormData) {
    return data;
  }
  if (typeof data === "object" && hasFiles(data)) {
    return toFormData(data);
  }
  if (typeof data === "object" || headers["Content-Type"]?.includes("application/json")) {
    return JSON.stringify(data);
  }
  return String(data);
}
function parseHeaders(headers) {
  const result2 = {};
  headers.forEach((value, key2) => {
    result2[key2.toLowerCase()] = value;
  });
  return result2;
}
function createFetchClient(options = {}) {
  let xsrfCookieName = options.xsrfCookieName ?? "XSRF-TOKEN";
  let xsrfHeaderName = options.xsrfHeaderName ?? "X-XSRF-TOKEN";
  function getXsrfToken() {
    if (typeof document === "undefined") {
      return null;
    }
    const match = document.cookie.match(new RegExp("(^|;\\s*)" + xsrfCookieName + "=([^;]*)"));
    return match ? decodeURIComponent(match[2]) : null;
  }
  return {
    setXsrfCookieName(name) {
      xsrfCookieName = name;
    },
    setXsrfHeaderName(name) {
      xsrfHeaderName = name;
    },
    async request(config3) {
      const url = buildUrl(config3.url, config3.baseURL, config3.params);
      const method2 = config3.method.toUpperCase();
      const headers = {};
      const ajaxHeader = getAjaxHeader();
      if (ajaxHeader) {
        headers["X-Requested-With"] = ajaxHeader;
      }
      if (config3.data !== void 0 && !["GET", "DELETE"].includes(method2)) {
        if (!(config3.data instanceof FormData) && !hasFiles(config3.data)) {
          headers["Content-Type"] = "application/json";
        }
      }
      if (config3.headers) {
        Object.entries(config3.headers).forEach(([key2, value]) => {
          if (value !== void 0) {
            headers[key2] = String(value);
          }
        });
      }
      const xsrfToken = getXsrfToken();
      if (xsrfToken && !["GET", "HEAD", "OPTIONS"].includes(method2)) {
        headers[xsrfHeaderName] = xsrfToken;
      }
      let signal = config3.signal;
      let timeoutId;
      const timeout3 = config3.timeout ?? 3e4;
      if (timeout3 > 0 && !signal) {
        const controller = new AbortController();
        signal = controller.signal;
        timeoutId = setTimeout(() => controller.abort(), timeout3);
      }
      const body = ["GET", "DELETE"].includes(method2) ? void 0 : prepareBody(config3.data, headers);
      if (body instanceof FormData) {
        delete headers["Content-Type"];
      }
      try {
        const response = await fetch(url, {
          method: method2,
          headers,
          body,
          signal,
          credentials: config3.credentials ?? "same-origin"
        });
        if (timeoutId) {
          clearTimeout(timeoutId);
        }
        let data;
        const contentType = response.headers.get("content-type");
        if (contentType?.includes("application/json")) {
          data = await response.json();
        } else {
          data = await response.text();
        }
        const httpResponse = {
          status: response.status,
          data,
          headers: parseHeaders(response.headers)
        };
        if (!response.ok) {
          throw new HttpResponseError(httpResponse);
        }
        return httpResponse;
      } catch (error) {
        if (timeoutId) {
          clearTimeout(timeoutId);
        }
        if (error instanceof HttpResponseError) {
          throw error;
        }
        if (error instanceof DOMException && error.name === "AbortError") {
          throw new HttpCancelledError();
        }
        if (error instanceof TypeError) {
          throw new HttpNetworkError(error.message);
        }
        throw error;
      }
    }
  };
}
var fetchHttpClient = createFetchClient();

// node_modules/laravel-precognition/dist/client.js
var httpClient = fetchHttpClient;
var baseURL = void 0;
var timeout2 = void 0;
var credentials = "same-origin";
var requestFingerprintResolver = (config3) => `${config3.method}:${config3.baseURL ?? baseURL ?? ""}${config3.url}`;
var successResolver = (response) => response.status === 204 && response.headers["precognition-success"] === "true";
var abortControllers = {};
var client = {
  get: (url, data = {}, config3 = {}) => request(mergeConfig("get", url, data, config3)),
  post: (url, data = {}, config3 = {}) => request(mergeConfig("post", url, data, config3)),
  patch: (url, data = {}, config3 = {}) => request(mergeConfig("patch", url, data, config3)),
  put: (url, data = {}, config3 = {}) => request(mergeConfig("put", url, data, config3)),
  delete: (url, data = {}, config3 = {}) => request(mergeConfig("delete", url, data, config3)),
  useHttpClient(newHttpClient) {
    httpClient = newHttpClient;
    return client;
  },
  withBaseURL(url) {
    baseURL = url;
    return client;
  },
  withTimeout(duration) {
    timeout2 = duration;
    return client;
  },
  withCredentials(value) {
    credentials = typeof value === "string" ? value : value ? "include" : "omit";
    return client;
  },
  fingerprintRequestsUsing(callback) {
    requestFingerprintResolver = callback === null ? () => null : callback;
    return client;
  },
  determineSuccessUsing(callback) {
    successResolver = callback;
    return client;
  },
  withXsrfCookieName(name) {
    fetchHttpClient.setXsrfCookieName(name);
    return client;
  },
  withXsrfHeaderName(name) {
    fetchHttpClient.setXsrfHeaderName(name);
    return client;
  }
};
var mergeConfig = (method2, url, data, config3) => ({
  url,
  method: method2,
  ...config3,
  ...["get", "delete"].includes(method2) ? {
    params: merge2({}, data, config3?.params)
  } : {
    data: merge2({}, data, config3?.data)
  }
});
var request = (userConfig = {}) => {
  const config3 = [
    resolveConfig,
    abortMatchingRequests,
    refreshAbortController
  ].reduce((config4, callback) => callback(config4), userConfig);
  if ((config3.onBefore ?? (() => true))() === false) {
    return Promise.resolve(null);
  }
  (config3.onStart ?? (() => null))();
  return httpClient.request({
    method: config3.method,
    url: config3.url,
    baseURL: config3.baseURL ?? baseURL,
    data: config3.data,
    params: config3.params,
    headers: config3.headers,
    signal: config3.signal,
    timeout: config3.timeout,
    credentials
  }).then(async (response) => {
    if (config3.precognitive) {
      validatePrecognitionResponse(response);
    }
    const status2 = response.status;
    let payload = response;
    if (config3.precognitive && config3.onPrecognitionSuccess && successResolver(response)) {
      payload = await Promise.resolve(config3.onPrecognitionSuccess(response) ?? payload);
    }
    if (config3.onSuccess && isSuccess(status2)) {
      payload = await Promise.resolve(config3.onSuccess(payload) ?? payload);
    }
    const statusHandler = resolveStatusHandler(config3, status2) ?? ((response2) => response2);
    return statusHandler(payload) ?? payload;
  }, (error) => {
    if (isNotServerGeneratedError(error)) {
      return Promise.reject(error);
    }
    const httpError = error;
    if (config3.precognitive) {
      validatePrecognitionResponse(httpError.response);
    }
    const statusHandler = resolveStatusHandler(config3, httpError.response.status) ?? ((_, error2) => Promise.reject(error2));
    return statusHandler(httpError.response, httpError);
  }).finally(config3.onFinish ?? (() => null));
};
var resolveConfig = (config3) => {
  const only = config3.only ?? config3.validate;
  return {
    ...config3,
    timeout: config3.timeout ?? timeout2,
    precognitive: config3.precognitive !== false,
    fingerprint: typeof config3.fingerprint === "undefined" ? requestFingerprintResolver(config3, httpClient) : config3.fingerprint,
    headers: {
      ...config3.headers,
      "Accept": "application/json",
      "Content-Type": resolveContentType(config3),
      ...config3.precognitive !== false ? {
        Precognition: true
      } : {},
      ...only ? {
        "Precognition-Validate-Only": Array.from(only).join()
      } : {}
    }
  };
};
var isSuccess = (status2) => status2 >= 200 && status2 < 300;
var abortMatchingRequests = (config3) => {
  if (typeof config3.fingerprint !== "string") {
    return config3;
  }
  abortControllers[config3.fingerprint]?.abort();
  delete abortControllers[config3.fingerprint];
  return config3;
};
var refreshAbortController = (config3) => {
  if (typeof config3.fingerprint !== "string" || config3.signal || !config3.precognitive) {
    return config3;
  }
  abortControllers[config3.fingerprint] = new AbortController();
  return {
    ...config3,
    signal: abortControllers[config3.fingerprint].signal
  };
};
var validatePrecognitionResponse = (response) => {
  if (response.headers?.precognition !== "true") {
    throw Error("Did not receive a Precognition response. Ensure you have the Precognition middleware in place for the route.");
  }
};
var isNotServerGeneratedError = (error) => {
  return !(error instanceof HttpResponseError) || typeof error.response?.status !== "number";
};
var resolveStatusHandler = (config3, code) => ({
  401: config3.onUnauthorized,
  403: config3.onForbidden,
  404: config3.onNotFound,
  409: config3.onConflict,
  422: config3.onValidationError,
  423: config3.onLocked
})[code];
var resolveContentType = (config3) => config3.headers?.["Content-Type"] ?? config3.headers?.["Content-type"] ?? config3.headers?.["content-type"] ?? (hasFiles(config3.data) ? "multipart/form-data" : "application/json");

// node_modules/laravel-precognition/dist/validator.js
var expandWildcardPaths = (pattern, data) => {
  if (!pattern.includes("*")) {
    return [pattern];
  }
  const parts = pattern.split(".");
  let paths = [""];
  for (const part of parts) {
    if (part === "*") {
      const expanded = [];
      for (const path of paths) {
        const value = path ? get(data, path) : data;
        if (Array.isArray(value)) {
          for (let index = 0; index < value.length; index++) {
            expanded.push(path ? `${path}.${index}` : String(index));
          }
        } else if (value !== null && typeof value === "object") {
          for (const key2 of Object.keys(value)) {
            expanded.push(path ? `${path}.${key2}` : key2);
          }
        }
      }
      paths = expanded;
    } else {
      paths = paths.map((path) => path ? `${path}.${part}` : part);
    }
  }
  return paths;
};
var keyMatchesPattern = (key2, pattern) => {
  if (!pattern.includes("*")) {
    return key2 === pattern;
  }
  const regex = new RegExp("^" + pattern.replace(/\./g, "\\.").replace(/\*/g, "[^.]+") + "$");
  return regex.test(key2);
};
var omitByPattern = (obj, patterns) => {
  return Object.fromEntries(Object.entries(obj).filter(([key2]) => {
    return !patterns.some((pattern) => keyMatchesPattern(key2, pattern));
  }));
};
var createValidator = (callback, initialData = {}) => {
  const listeners = {
    errorsChanged: [],
    touchedChanged: [],
    validatingChanged: [],
    validatedChanged: []
  };
  let validateFiles = false;
  let validating = false;
  const setValidating = (value) => {
    if (value !== validating) {
      validating = value;
      return listeners.validatingChanged;
    }
    return [];
  };
  let validated = [];
  const setValidated = (value) => {
    const uniqueNames = [...new Set(value)];
    if (validated.length !== uniqueNames.length || !uniqueNames.every((name) => validated.includes(name))) {
      validated = uniqueNames;
      return listeners.validatedChanged;
    }
    return [];
  };
  const valid = () => validated.filter((name) => typeof errors[name] === "undefined");
  let touched = [];
  const setTouched = (value) => {
    const uniqueNames = [...new Set(value)];
    if (touched.length !== uniqueNames.length || !uniqueNames.every((name) => touched.includes(name))) {
      touched = uniqueNames;
      return listeners.touchedChanged;
    }
    return [];
  };
  let errors = {};
  const setErrors = (value) => {
    const prepared = toValidationErrors(value);
    if (!isEqual(errors, prepared)) {
      errors = prepared;
      return listeners.errorsChanged;
    }
    return [];
  };
  const forgetError = (name) => {
    const newErrors = { ...errors };
    delete newErrors[resolveName(name)];
    return setErrors(newErrors);
  };
  const hasErrors = () => Object.keys(errors).length > 0;
  let debounceTimeoutDuration = 1500;
  const setDebounceTimeout = (value) => {
    debounceTimeoutDuration = value;
    validator.cancel();
    validator = createValidator2();
  };
  let oldData = initialData;
  let validatingData = null;
  let oldTouched = [];
  let validatingTouched = null;
  const createValidator2 = () => debounce2((instanceConfig) => {
    callback({
      get: (url, data = {}, globalConfig = {}) => client.get(url, parseData(data), resolveConfig2(globalConfig, instanceConfig, data)),
      post: (url, data = {}, globalConfig = {}) => client.post(url, parseData(data), resolveConfig2(globalConfig, instanceConfig, data)),
      patch: (url, data = {}, globalConfig = {}) => client.patch(url, parseData(data), resolveConfig2(globalConfig, instanceConfig, data)),
      put: (url, data = {}, globalConfig = {}) => client.put(url, parseData(data), resolveConfig2(globalConfig, instanceConfig, data)),
      delete: (url, data = {}, globalConfig = {}) => client.delete(url, parseData(data), resolveConfig2(globalConfig, instanceConfig, data))
    }).catch((error) => {
      if (error instanceof HttpCancelledError) {
        return null;
      }
      if (error instanceof HttpResponseError && error.response?.status === 422) {
        return null;
      }
      return Promise.reject(error);
    });
  }, debounceTimeoutDuration, { leading: true, trailing: true });
  let validator = createValidator2();
  const resolveConfig2 = (globalConfig, instanceConfig, data = {}) => {
    const config3 = {
      ...globalConfig,
      ...instanceConfig
    };
    const only = Array.from(config3.only ?? config3.validate ?? touched);
    return {
      ...instanceConfig,
      ...merge2({}, globalConfig, instanceConfig),
      only,
      timeout: config3.timeout ?? 5e3,
      onValidationError: (response, error) => {
        [
          ...setValidated([...validated, ...only]),
          ...setErrors(merge2(omitByPattern({ ...errors }, only), response.data.errors))
        ].forEach((listener) => listener());
        return config3.onValidationError ? config3.onValidationError(response, error) : Promise.reject(error);
      },
      onSuccess: (response) => {
        setValidated([...validated, ...only]).forEach((listener) => listener());
        return config3.onSuccess ? config3.onSuccess(response) : response;
      },
      onPrecognitionSuccess: (response) => {
        [
          ...setValidated([...validated, ...only]),
          ...setErrors(omitByPattern({ ...errors }, only))
        ].forEach((listener) => listener());
        return config3.onPrecognitionSuccess ? config3.onPrecognitionSuccess(response) : response;
      },
      onBefore: () => {
        const hasWildcards = touched.some((name) => name.includes("*"));
        const expandedTouched = hasWildcards ? [...new Set(touched.flatMap((name) => expandWildcardPaths(name, data)))] : touched;
        if (config3.onBeforeValidation && config3.onBeforeValidation({ data, touched: expandedTouched }, { data: oldData, touched: oldTouched }) === false) {
          return false;
        }
        const beforeResult = (config3.onBefore || (() => true))();
        if (beforeResult === false) {
          return false;
        }
        if (hasWildcards) {
          setTouched(expandedTouched).forEach((listener) => listener());
        }
        validatingTouched = touched;
        validatingData = data;
        return true;
      },
      onStart: () => {
        setValidating(true).forEach((listener) => listener());
        (config3.onStart ?? (() => null))();
      },
      onFinish: () => {
        setValidating(false).forEach((listener) => listener());
        oldTouched = validatingTouched;
        oldData = validatingData;
        validatingTouched = validatingData = null;
        (config3.onFinish ?? (() => null))();
      }
    };
  };
  const validate = (name, value, config3) => {
    if (typeof name === "undefined") {
      const only = Array.from(config3?.only ?? config3?.validate ?? []);
      setTouched([...touched, ...only]).forEach((listener) => listener());
      validator(config3 ?? {});
      return;
    }
    if (isFile2(value) && !validateFiles) {
      console.warn('Precognition file validation is not active. Call the "validateFiles" function on your form to enable it.');
      return;
    }
    name = resolveName(name);
    if (name.includes("*") || get(oldData, name) !== value) {
      setTouched([name, ...touched]).forEach((listener) => listener());
      validator(config3 ?? {});
    }
  };
  const parseData = (data) => validateFiles === false ? forgetFiles(data) : data;
  const form = {
    touched: () => touched,
    validate(name, value, config3) {
      if (typeof name === "object" && !("target" in name)) {
        config3 = name;
        name = value = void 0;
      }
      validate(name, value, config3);
      return form;
    },
    touch(input) {
      const inputs = Array.isArray(input) ? input : [resolveName(input)];
      setTouched([...touched, ...inputs]).forEach((listener) => listener());
      return form;
    },
    validating: () => validating,
    valid,
    errors: () => errors,
    hasErrors,
    setErrors(value) {
      setErrors(value).forEach((listener) => listener());
      return form;
    },
    forgetError(name) {
      forgetError(name).forEach((listener) => listener());
      return form;
    },
    defaults(data) {
      initialData = data;
      oldData = data;
      return form;
    },
    reset(...names) {
      if (names.length === 0) {
        setTouched([]).forEach((listener) => listener());
      } else {
        const newTouched = [...touched];
        names.forEach((name) => {
          if (newTouched.includes(name)) {
            newTouched.splice(newTouched.indexOf(name), 1);
          }
          set(oldData, name, get(initialData, name));
        });
        setTouched(newTouched).forEach((listener) => listener());
      }
      return form;
    },
    setTimeout(value) {
      setDebounceTimeout(value);
      return form;
    },
    on(event, callback2) {
      listeners[event].push(callback2);
      return form;
    },
    validateFiles() {
      validateFiles = true;
      return form;
    },
    withoutFileValidation() {
      validateFiles = false;
      return form;
    }
  };
  return form;
};
var toSimpleValidationErrors = (errors) => {
  return Object.keys(errors).reduce((carry, key2) => ({
    ...carry,
    [key2]: Array.isArray(errors[key2]) ? errors[key2][0] : errors[key2]
  }), {});
};
var toValidationErrors = (errors) => {
  return Object.keys(errors).reduce((carry, key2) => ({
    ...carry,
    [key2]: typeof errors[key2] === "string" ? [errors[key2]] : errors[key2]
  }), {});
};
var resolveName = (name) => {
  return typeof name !== "string" ? name.target.name : name;
};
var forgetFiles = (data) => {
  const newData = { ...data };
  Object.keys(newData).forEach((name) => {
    const value = newData[name];
    if (value === null) {
      return;
    }
    if (isFile2(value)) {
      delete newData[name];
      return;
    }
    if (Array.isArray(value)) {
      newData[name] = Object.values(forgetFiles({ ...value }));
      return;
    }
    if (typeof value === "object") {
      newData[name] = forgetFiles(newData[name]);
      return;
    }
  });
  return newData;
};

// node_modules/@inertiajs/core/dist/index.js
var Config = class {
  config = {};
  defaults;
  constructor(defaults2) {
    this.defaults = defaults2;
  }
  extend(defaults2) {
    if (defaults2) {
      this.defaults = { ...this.defaults, ...defaults2 };
    }
    return this;
  }
  replace(newConfig) {
    this.config = newConfig;
  }
  get(key2) {
    return has(this.config, key2) ? get(this.config, key2) : get(this.defaults, key2);
  }
  set(keyOrValues, value) {
    if (typeof keyOrValues === "string") {
      set(this.config, keyOrValues, value);
    } else {
      Object.entries(keyOrValues).forEach(([key2, val]) => {
        set(this.config, key2, val);
      });
    }
  }
};
var config = new Config({
  form: {
    recentlySuccessfulDuration: 2e3,
    forceIndicesArrayFormatInFormData: true,
    withAllErrors: false
  },
  prefetch: {
    cacheFor: 3e4,
    hoverDelay: 75
  }
});
function debounce3(fn, delay3) {
  let timeoutID;
  return function(...args) {
    clearTimeout(timeoutID);
    timeoutID = setTimeout(() => fn.apply(this, args), delay3);
  };
}
function fireEvent(name, options) {
  return document.dispatchEvent(new CustomEvent(`inertia:${name}`, options));
}
var fireBeforeEvent = (visit) => {
  return fireEvent("before", { cancelable: true, detail: { visit } });
};
var fireErrorEvent = (errors) => {
  return fireEvent("error", { detail: { errors } });
};
var fireNetworkErrorEvent = (error) => {
  return fireEvent("networkError", { cancelable: true, detail: { error } });
};
var fireFinishEvent = (visit) => {
  return fireEvent("finish", { detail: { visit } });
};
var fireHttpExceptionEvent = (response) => {
  return fireEvent("httpException", { cancelable: true, detail: { response } });
};
var fireBeforeUpdateEvent = (page22) => {
  return fireEvent("beforeUpdate", { detail: { page: page22 } });
};
var fireNavigateEvent = (page22) => {
  return fireEvent("navigate", { detail: { page: page22 } });
};
var fireProgressEvent = (progress3) => {
  return fireEvent("progress", { detail: { progress: progress3 } });
};
var fireStartEvent = (visit) => {
  return fireEvent("start", { detail: { visit } });
};
var fireSuccessEvent = (page22) => {
  return fireEvent("success", { detail: { page: page22 } });
};
var firePrefetchedEvent = (response, visit) => {
  return fireEvent("prefetched", { detail: { fetchedAt: Date.now(), response, visit } });
};
var firePrefetchingEvent = (visit) => {
  return fireEvent("prefetching", { detail: { visit } });
};
var fireFlashEvent = (flash) => {
  return fireEvent("flash", { detail: { flash } });
};
var SessionStorage = class {
  static locationVisitKey = "inertiaLocationVisit";
  static set(key2, value) {
    if (typeof window !== "undefined") {
      window.sessionStorage.setItem(key2, JSON.stringify(value));
    }
  }
  static get(key2) {
    if (typeof window !== "undefined") {
      return JSON.parse(window.sessionStorage.getItem(key2) || "null");
    }
  }
  static merge(key2, value) {
    const existing = this.get(key2);
    if (existing === null) {
      this.set(key2, value);
    } else {
      this.set(key2, { ...existing, ...value });
    }
  }
  static remove(key2) {
    if (typeof window !== "undefined") {
      window.sessionStorage.removeItem(key2);
    }
  }
  static removeNested(key2, nestedKey) {
    const existing = this.get(key2);
    if (existing !== null) {
      delete existing[nestedKey];
      this.set(key2, existing);
    }
  }
  static exists(key2) {
    try {
      return this.get(key2) !== null;
    } catch (error) {
      return false;
    }
  }
  static clear() {
    if (typeof window !== "undefined") {
      window.sessionStorage.clear();
    }
  }
};
var encryptHistory = async (data) => {
  if (typeof window === "undefined") {
    throw new Error("Unable to encrypt history");
  }
  const iv = getIv();
  const storedKey = await getKeyFromSessionStorage();
  const key2 = await getOrCreateKey(storedKey);
  if (!key2) {
    throw new Error("Unable to encrypt history");
  }
  const encrypted = await encryptData(iv, key2, data);
  return encrypted;
};
var historySessionStorageKeys = {
  key: "historyKey",
  iv: "historyIv"
};
var decryptHistory = async (data) => {
  const iv = getIv();
  const storedKey = await getKeyFromSessionStorage();
  if (!storedKey) {
    throw new Error("Unable to decrypt history");
  }
  return await decryptData(iv, storedKey, data);
};
var encryptData = async (iv, key2, data) => {
  if (typeof window === "undefined") {
    throw new Error("Unable to encrypt history");
  }
  if (typeof window.crypto.subtle === "undefined") {
    console.warn("Encryption is not supported in this environment. SSL is required.");
    return Promise.resolve(data);
  }
  const textEncoder = new TextEncoder();
  const str = JSON.stringify(data);
  const encoded = new Uint8Array(str.length * 3);
  const result2 = textEncoder.encodeInto(str, encoded);
  return window.crypto.subtle.encrypt(
    {
      name: "AES-GCM",
      iv
    },
    key2,
    encoded.subarray(0, result2.written)
  );
};
var decryptData = async (iv, key2, data) => {
  if (typeof window.crypto.subtle === "undefined") {
    console.warn("Decryption is not supported in this environment. SSL is required.");
    return Promise.resolve(data);
  }
  const decrypted = await window.crypto.subtle.decrypt(
    {
      name: "AES-GCM",
      iv
    },
    key2,
    data
  );
  return JSON.parse(new TextDecoder().decode(decrypted));
};
var getIv = () => {
  const ivString = SessionStorage.get(historySessionStorageKeys.iv);
  if (ivString) {
    return new Uint8Array(ivString);
  }
  const iv = window.crypto.getRandomValues(new Uint8Array(12));
  SessionStorage.set(historySessionStorageKeys.iv, Array.from(iv));
  return iv;
};
var createKey = async () => {
  if (typeof window.crypto.subtle === "undefined") {
    console.warn("Encryption is not supported in this environment. SSL is required.");
    return Promise.resolve(null);
  }
  return window.crypto.subtle.generateKey(
    {
      name: "AES-GCM",
      length: 256
    },
    true,
    ["encrypt", "decrypt"]
  );
};
var saveKey = async (key2) => {
  if (typeof window.crypto.subtle === "undefined") {
    console.warn("Encryption is not supported in this environment. SSL is required.");
    return Promise.resolve();
  }
  const keyData = await window.crypto.subtle.exportKey("raw", key2);
  SessionStorage.set(historySessionStorageKeys.key, Array.from(new Uint8Array(keyData)));
};
var getOrCreateKey = async (key2) => {
  if (key2) {
    return key2;
  }
  const newKey = await createKey();
  if (!newKey) {
    return null;
  }
  await saveKey(newKey);
  return newKey;
};
var getKeyFromSessionStorage = async () => {
  const stringKey = SessionStorage.get(historySessionStorageKeys.key);
  if (!stringKey) {
    return null;
  }
  const key2 = await window.crypto.subtle.importKey(
    "raw",
    new Uint8Array(stringKey),
    {
      name: "AES-GCM",
      length: 256
    },
    true,
    ["encrypt", "decrypt"]
  );
  return key2;
};
var stripTopLevelUndefined = (obj) => {
  const result2 = {};
  for (const key2 of Object.keys(obj)) {
    if (obj[key2] !== void 0) {
      result2[key2] = obj[key2];
    }
  }
  return result2;
};
var objectsAreEqual = (obj1, obj2, excludeKeys) => {
  if (obj1 === obj2) {
    return true;
  }
  for (const key2 in obj1) {
    if (excludeKeys.includes(key2)) {
      continue;
    }
    if (obj1[key2] === obj2[key2]) {
      continue;
    }
    if (!compareValues3(obj1[key2], obj2[key2])) {
      return false;
    }
  }
  for (const key2 in obj2) {
    if (excludeKeys.includes(key2)) {
      continue;
    }
    if (!(key2 in obj1)) {
      return false;
    }
  }
  return true;
};
var compareValues3 = (value1, value2) => {
  switch (typeof value1) {
    case "object":
      return objectsAreEqual(value1, value2, []);
    case "function":
      return value1.toString() === value2.toString();
    default:
      return value1 === value2;
  }
};
var conversionMap = {
  ms: 1,
  s: 1e3,
  m: 1e3 * 60,
  h: 1e3 * 60 * 60,
  d: 1e3 * 60 * 60 * 24
};
var timeToMs = (time) => {
  if (typeof time === "number") {
    return time;
  }
  for (const [unit, conversion] of Object.entries(conversionMap)) {
    if (time.endsWith(unit)) {
      return parseFloat(time) * conversion;
    }
  }
  return parseInt(time);
};
var PrefetchedRequests = class {
  cached = [];
  inFlightRequests = [];
  removalTimers = [];
  currentUseId = null;
  add(params, sendFunc, { cacheFor, cacheTags }) {
    const inFlight = this.findInFlight(params);
    if (inFlight) {
      return Promise.resolve();
    }
    const existing = this.findCached(params);
    if (!params.fresh && existing && existing.staleTimestamp > Date.now()) {
      return Promise.resolve();
    }
    const [stale, prefetchExpiresIn] = this.extractStaleValues(cacheFor);
    const promise = new Promise((resolve, reject2) => {
      sendFunc({
        ...params,
        onCancel: () => {
          this.remove(params);
          params.onCancel();
          reject2();
        },
        onError: (error) => {
          this.remove(params);
          params.onError(error);
          reject2();
        },
        onPrefetching(visitParams) {
          params.onPrefetching(visitParams);
        },
        onPrefetched(response, visit) {
          params.onPrefetched(response, visit);
        },
        onPrefetchResponse(response) {
          resolve(response);
        },
        onPrefetchError(error) {
          prefetchedRequests.removeFromInFlight(params);
          reject2(error);
        }
      });
    }).then((response) => {
      this.remove(params);
      const pageResponse = response.getPageResponse();
      page.mergeOncePropsIntoResponse(pageResponse);
      this.cached.push({
        params: { ...params },
        staleTimestamp: Date.now() + stale,
        expiresAt: Date.now() + prefetchExpiresIn,
        response: promise,
        singleUse: prefetchExpiresIn === 0,
        timestamp: Date.now(),
        inFlight: false,
        tags: Array.isArray(cacheTags) ? cacheTags : [cacheTags]
      });
      const oncePropExpiresIn = this.getShortestOncePropTtl(pageResponse);
      this.scheduleForRemoval(
        params,
        oncePropExpiresIn ? Math.min(prefetchExpiresIn, oncePropExpiresIn) : prefetchExpiresIn
      );
      this.removeFromInFlight(params);
      response.handlePrefetch();
      return response;
    });
    this.inFlightRequests.push({
      params: { ...params },
      response: promise,
      staleTimestamp: null,
      inFlight: true
    });
    return promise;
  }
  removeAll() {
    this.cached = [];
    this.removalTimers.forEach((removalTimer) => {
      clearTimeout(removalTimer.timer);
    });
    this.removalTimers = [];
  }
  removeByTags(tags) {
    this.cached = this.cached.filter((prefetched) => {
      return !prefetched.tags.some((tag) => tags.includes(tag));
    });
  }
  remove(params) {
    this.cached = this.cached.filter((prefetched) => {
      return !this.paramsAreEqual(prefetched.params, params);
    });
    this.clearTimer(params);
  }
  removeFromInFlight(params) {
    this.inFlightRequests = this.inFlightRequests.filter((prefetching) => {
      return !this.paramsAreEqual(prefetching.params, params);
    });
  }
  extractStaleValues(cacheFor) {
    const [stale, expires] = this.cacheForToStaleAndExpires(cacheFor);
    return [timeToMs(stale), timeToMs(expires)];
  }
  cacheForToStaleAndExpires(cacheFor) {
    if (!Array.isArray(cacheFor)) {
      return [cacheFor, cacheFor];
    }
    switch (cacheFor.length) {
      case 0:
        return [0, 0];
      case 1:
        return [cacheFor[0], cacheFor[0]];
      default:
        return [cacheFor[0], cacheFor[1]];
    }
  }
  clearTimer(params) {
    const timer = this.removalTimers.find((removalTimer) => {
      return this.paramsAreEqual(removalTimer.params, params);
    });
    if (timer) {
      clearTimeout(timer.timer);
      this.removalTimers = this.removalTimers.filter((removalTimer) => removalTimer !== timer);
    }
  }
  scheduleForRemoval(params, expiresIn) {
    if (typeof window === "undefined") {
      return;
    }
    this.clearTimer(params);
    if (expiresIn > 0) {
      const timer = window.setTimeout(() => this.remove(params), expiresIn);
      this.removalTimers.push({
        params,
        timer
      });
    }
  }
  get(params) {
    return this.findCached(params) || this.findInFlight(params);
  }
  use(prefetched, params) {
    const id = `${params.url.pathname}-${Date.now()}-${Math.random().toString(36).substring(7)}`;
    this.currentUseId = id;
    return prefetched.response.then((response) => {
      if (this.currentUseId !== id) {
        return;
      }
      response.mergeParams({ ...params, onPrefetched: () => {
      } });
      this.removeSingleUseItems(params);
      return response.handle();
    });
  }
  removeSingleUseItems(params) {
    this.cached = this.cached.filter((prefetched) => {
      if (!this.paramsAreEqual(prefetched.params, params)) {
        return true;
      }
      return !prefetched.singleUse;
    });
  }
  findCached(params) {
    return this.cached.find((prefetched) => {
      return this.paramsAreEqual(prefetched.params, params);
    }) || null;
  }
  findInFlight(params) {
    return this.inFlightRequests.find((prefetched) => {
      return this.paramsAreEqual(prefetched.params, params);
    }) || null;
  }
  withoutPurposePrefetchHeader(params) {
    const newParams = cloneDeep(params);
    if (newParams.headers["Purpose"] === "prefetch") {
      delete newParams.headers["Purpose"];
    }
    return newParams;
  }
  paramsAreEqual(params1, params2) {
    return objectsAreEqual(
      this.withoutPurposePrefetchHeader(params1),
      this.withoutPurposePrefetchHeader(params2),
      [
        "showProgress",
        "replace",
        "prefetch",
        "preserveScroll",
        "preserveState",
        "onBefore",
        "onBeforeUpdate",
        "onStart",
        "onProgress",
        "onFinish",
        "onCancel",
        "onSuccess",
        "onError",
        "onFlash",
        "onPrefetched",
        "onCancelToken",
        "onPrefetching",
        "async",
        "viewTransition",
        "optimistic",
        "component",
        "pageProps"
      ]
    );
  }
  updateCachedOncePropsFromCurrentPage() {
    this.cached.forEach((prefetched) => {
      prefetched.response.then((response) => {
        const pageResponse = response.getPageResponse();
        page.mergeOncePropsIntoResponse(pageResponse, { force: true });
        for (const [group, deferredProps] of Object.entries(pageResponse.deferredProps ?? {})) {
          const remaining = deferredProps.filter((prop) => get(pageResponse.props, prop) === void 0);
          if (remaining.length > 0) {
            pageResponse.deferredProps[group] = remaining;
          } else {
            delete pageResponse.deferredProps[group];
          }
        }
        const oncePropExpiresIn = this.getShortestOncePropTtl(pageResponse);
        if (oncePropExpiresIn === null) {
          return;
        }
        const prefetchExpiresIn = prefetched.expiresAt - Date.now();
        const expiresIn = Math.min(prefetchExpiresIn, oncePropExpiresIn);
        if (expiresIn > 0) {
          this.scheduleForRemoval(prefetched.params, expiresIn);
        } else {
          this.remove(prefetched.params);
        }
      });
    });
  }
  getShortestOncePropTtl(page22) {
    const expiryTimestamps = Object.values(page22.onceProps ?? {}).map((onceProp) => onceProp.expiresAt).filter((expiresAt) => !!expiresAt);
    if (expiryTimestamps.length === 0) {
      return null;
    }
    return Math.min(...expiryTimestamps) - Date.now();
  }
};
var prefetchedRequests = new PrefetchedRequests();
var elementInViewport = (el) => {
  if (el.offsetParent === null) {
    return false;
  }
  const rect = el.getBoundingClientRect();
  const verticallyVisible = rect.top < window.innerHeight && rect.bottom >= 0;
  const horizontallyVisible = rect.left < window.innerWidth && rect.right >= 0;
  return verticallyVisible && horizontallyVisible;
};
var getScrollableParent = (element) => {
  const allowsVerticalScroll = (el) => {
    const computedStyle = window.getComputedStyle(el);
    if (computedStyle.overflowY === "scroll") {
      return true;
    }
    if (computedStyle.overflowY !== "auto") {
      return false;
    }
    if (["visible", "clip"].includes(computedStyle.overflowX)) {
      return true;
    }
    return hasDimensionConstraint(computedStyle.maxHeight, el.style.height) || isConstrainedByLayout(el, "height");
  };
  const allowsHorizontalScroll = (el) => {
    const computedStyle = window.getComputedStyle(el);
    if (computedStyle.overflowX === "scroll") {
      return true;
    }
    if (computedStyle.overflowX !== "auto") {
      return false;
    }
    if (["visible", "clip"].includes(computedStyle.overflowY)) {
      return true;
    }
    return hasDimensionConstraint(computedStyle.maxWidth, el.style.width) || isConstrainedByLayout(el, "width");
  };
  const hasDimensionConstraint = (computedMaxDimension, inlineStyleDimension) => {
    if (computedMaxDimension && computedMaxDimension !== "none" && computedMaxDimension !== "0px") {
      return true;
    }
    if (inlineStyleDimension && inlineStyleDimension !== "auto" && inlineStyleDimension !== "0") {
      return true;
    }
    return false;
  };
  const isConstrainedByLayout = (el, dimension) => {
    const parent2 = el.parentElement;
    if (!parent2) {
      return false;
    }
    const parentStyle = window.getComputedStyle(parent2);
    if (["flex", "inline-flex"].includes(parentStyle.display)) {
      const isColumnLayout = ["column", "column-reverse"].includes(parentStyle.flexDirection);
      return dimension === "height" ? isColumnLayout : !isColumnLayout;
    }
    return ["grid", "inline-grid"].includes(parentStyle.display);
  };
  let parent = element?.parentElement;
  while (parent) {
    const allowsScroll = allowsVerticalScroll(parent) || allowsHorizontalScroll(parent);
    if (window.getComputedStyle(parent).display !== "contents" && allowsScroll) {
      return parent;
    }
    parent = parent.parentElement;
  }
  return null;
};
var getElementsInViewportFromCollection = (elements, referenceElement) => {
  if (!referenceElement) {
    return elements.filter((element) => elementInViewport(element));
  }
  const referenceIndex = elements.indexOf(referenceElement);
  const upwardElements = [];
  const downwardElements = [];
  for (let i = referenceIndex; i >= 0; i--) {
    const element = elements[i];
    if (elementInViewport(element)) {
      upwardElements.push(element);
    } else {
      break;
    }
  }
  for (let i = referenceIndex + 1; i < elements.length; i++) {
    const element = elements[i];
    if (elementInViewport(element)) {
      downwardElements.push(element);
    } else {
      break;
    }
  }
  return [...upwardElements.reverse(), ...downwardElements];
};
var requestAnimationFrame = (cb, times2 = 1) => {
  window.requestAnimationFrame(() => {
    if (times2 > 1) {
      requestAnimationFrame(cb, times2 - 1);
    } else {
      cb();
    }
  });
};
var getInitialPageFromDOM = (id) => {
  if (typeof window === "undefined") {
    return null;
  }
  const scriptEl = document.querySelector(`script[data-page="${id}"][type="application/json"]`);
  if (scriptEl?.textContent) {
    return JSON.parse(scriptEl.textContent);
  }
  return null;
};
var isServer = typeof window === "undefined";
var isFirefox = !isServer && /Firefox/i.test(window.navigator.userAgent);
var Scroll = class {
  static save() {
    history.saveScrollPositions(this.getScrollRegions());
  }
  static getScrollRegions() {
    return Array.from(this.regions()).map((region) => ({
      top: region.scrollTop,
      left: region.scrollLeft
    }));
  }
  static regions() {
    return document.querySelectorAll("[scroll-region]");
  }
  static scrollToTop() {
    if (isFirefox && getComputedStyle(document.documentElement).scrollBehavior === "smooth") {
      return requestAnimationFrame(() => window.scrollTo(0, 0), 2);
    }
    window.scrollTo(0, 0);
  }
  static reset() {
    const anchorHash = isServer ? null : window.location.hash;
    if (!anchorHash) {
      this.scrollToTop();
    }
    this.regions().forEach((region) => {
      if (typeof region.scrollTo === "function") {
        region.scrollTo(0, 0);
      } else {
        region.scrollTop = 0;
        region.scrollLeft = 0;
      }
    });
    this.save();
    this.scrollToAnchor();
  }
  static scrollToAnchor() {
    const anchorHash = isServer ? null : window.location.hash;
    if (anchorHash) {
      setTimeout(() => {
        const anchorElement = document.getElementById(anchorHash.slice(1));
        anchorElement ? anchorElement.scrollIntoView() : this.scrollToTop();
      });
    }
  }
  static restore(scrollRegions) {
    if (isServer) {
      return;
    }
    window.requestAnimationFrame(() => {
      this.restoreDocument();
      this.restoreScrollRegions(scrollRegions);
    });
  }
  static restoreScrollRegions(scrollRegions) {
    if (isServer) {
      return;
    }
    this.regions().forEach((region, index) => {
      const scrollPosition = scrollRegions[index];
      if (!scrollPosition) {
        return;
      }
      if (typeof region.scrollTo === "function") {
        region.scrollTo(scrollPosition.left, scrollPosition.top);
      } else {
        region.scrollTop = scrollPosition.top;
        region.scrollLeft = scrollPosition.left;
      }
    });
  }
  static restoreDocument() {
    const scrollPosition = history.getDocumentScrollPosition();
    window.scrollTo(scrollPosition.left, scrollPosition.top);
  }
  static onScroll(event) {
    const target = event.target;
    if (typeof target.hasAttribute === "function" && target.hasAttribute("scroll-region")) {
      this.save();
    }
  }
  static onWindowScroll() {
    history.saveDocumentScrollPosition({
      top: window.scrollY,
      left: window.scrollX
    });
  }
};
var isFile3 = (value) => typeof File !== "undefined" && value instanceof File || value instanceof Blob || typeof FileList !== "undefined" && value instanceof FileList && value.length > 0;
function hasFiles2(data) {
  return isFile3(data) || data instanceof FormData && Array.from(data.values()).some((value) => hasFiles2(value)) || typeof data === "object" && data !== null && Object.values(data).some((value) => hasFiles2(value));
}
var isFormData = (value) => value instanceof FormData;
function objectToFormData(source, form = new FormData(), parentKey = null, queryStringArrayFormat = "brackets") {
  source = source || {};
  for (const key2 in source) {
    if (Object.prototype.hasOwnProperty.call(source, key2)) {
      append(form, composeKey(parentKey, key2, "indices"), source[key2], queryStringArrayFormat);
    }
  }
  return form;
}
function composeKey(parent, key2, format) {
  if (!parent) {
    return key2;
  }
  return format === "brackets" ? `${parent}[]` : `${parent}[${key2}]`;
}
function append(form, key2, value, format) {
  if (Array.isArray(value)) {
    return Array.from(value.keys()).forEach(
      (index) => append(form, composeKey(key2, index.toString(), format), value[index], format)
    );
  } else if (value instanceof Date) {
    return form.append(key2, value.toISOString());
  } else if (value instanceof File) {
    return form.append(key2, value, value.name);
  } else if (value instanceof Blob) {
    return form.append(key2, value);
  } else if (typeof value === "boolean") {
    return form.append(key2, value ? "1" : "0");
  } else if (typeof value === "string") {
    return form.append(key2, value);
  } else if (typeof value === "number") {
    return form.append(key2, `${value}`);
  } else if (value === null || value === void 0) {
    return form.append(key2, "");
  }
  objectToFormData(value, form, key2, format);
}
function hasIndices(url) {
  return /\[\d+\]/.test(decodeURIComponent(url.search));
}
function parse(query) {
  if (!query || query === "?") {
    return {};
  }
  const result2 = {};
  query.replace(/^\?/, "").split("&").filter(Boolean).forEach((segment) => {
    const [rawKey, rawValue] = splitPair(segment);
    set2(result2, decode(rawKey), decode(rawValue));
  });
  return result2;
}
function stringify(data, arrayFormat) {
  const pairs = [];
  build(data, "", pairs, arrayFormat);
  return pairs.length ? "?" + pairs.join("&") : "";
}
function splitPair(pair) {
  const index = pair.indexOf("=");
  return index === -1 ? [pair, ""] : [pair.substring(0, index), pair.substring(index + 1)];
}
function decode(value) {
  return decodeURIComponent(value.replace(/\+/g, " "));
}
function set2(target, key2, value) {
  const keys2 = parseKey(key2);
  if (keys2.some((k) => k === "__proto__")) {
    return;
  }
  let current = target;
  while (keys2.length > 1) {
    const segment = keys2.shift();
    const nextIsArrayPush = keys2[0] === "";
    if (typeof current[segment] !== "object" || current[segment] === null) {
      current[segment] = nextIsArrayPush ? [] : {};
    }
    current = current[segment];
  }
  const final = keys2.shift();
  if (final === "" && Array.isArray(current)) {
    current.push(value);
  } else {
    current[final] = value;
  }
}
function parseKey(key2) {
  const segments = [];
  const base = key2.split("[")[0];
  if (base) {
    segments.push(base);
  }
  let match;
  const pattern = /\[([^\]]*)\]/g;
  while ((match = pattern.exec(key2)) !== null) {
    segments.push(match[1]);
  }
  return segments;
}
function build(value, prefix, pairs, arrayFormat) {
  if (value === void 0) {
    return;
  }
  if (value === null) {
    pairs.push(`${prefix}=`);
    return;
  }
  if (Array.isArray(value)) {
    value.forEach((item, index) => {
      const key2 = arrayFormat === "indices" ? `${prefix}[${index}]` : `${prefix}[]`;
      build(item, key2, pairs, arrayFormat);
    });
    return;
  }
  if (typeof value === "object") {
    Object.keys(value).forEach((key2) => {
      build(value[key2], prefix ? `${prefix}[${key2}]` : key2, pairs, arrayFormat);
    });
    return;
  }
  pairs.push(`${prefix}=${encodeURIComponent(String(value))}`);
}
function hrefToUrl(href) {
  return new URL(href.toString(), typeof window === "undefined" ? void 0 : window.location.toString());
}
var transformUrlAndData = (href, data, method2, forceFormData, queryStringArrayFormat) => {
  let url = typeof href === "string" ? hrefToUrl(href) : href;
  if ((hasFiles2(data) || forceFormData) && !isFormData(data)) {
    if (config.get("form.forceIndicesArrayFormatInFormData")) {
      queryStringArrayFormat = "indices";
    }
    data = objectToFormData(data, new FormData(), null, queryStringArrayFormat);
  }
  if (isFormData(data)) {
    return [url, data];
  }
  const [_href, _data] = mergeDataIntoQueryString(method2, url, data, queryStringArrayFormat);
  return [hrefToUrl(_href), _data];
};
function mergeDataIntoQueryString(method2, href, data, qsArrayFormat = "brackets") {
  const hasDataForQueryString = method2 === "get" && !isFormData(data) && Object.keys(data).length > 0;
  const hasHost = urlHasProtocol(href.toString());
  const hasAbsolutePath = hasHost || href.toString().startsWith("/") || href.toString() === "";
  const hasRelativePath = !hasAbsolutePath && !href.toString().startsWith("#") && !href.toString().startsWith("?");
  const hasRelativePathWithDotPrefix = /^[.]{1,2}([/]|$)/.test(href.toString());
  const hasSearch = href.toString().includes("?") || hasDataForQueryString;
  const hasHash = href.toString().includes("#");
  const url = new URL(href.toString(), typeof window === "undefined" ? "http://localhost" : window.location.toString());
  if (hasDataForQueryString) {
    const arrayFormat = hasIndices(url) ? "indices" : qsArrayFormat;
    url.search = stringify({ ...parse(url.search), ...data }, arrayFormat);
  }
  return [
    [
      hasHost ? `${url.protocol}//${url.host}` : "",
      hasAbsolutePath ? url.pathname : "",
      hasRelativePath ? url.pathname.substring(hasRelativePathWithDotPrefix ? 0 : 1) : "",
      hasSearch ? url.search : "",
      hasHash ? url.hash : ""
    ].join(""),
    hasDataForQueryString ? {} : data
  ];
}
function urlWithoutHash(url) {
  url = new URL(url.href);
  url.hash = "";
  return url;
}
var setHashIfSameUrl = (originUrl, destinationUrl) => {
  if (originUrl.hash && !destinationUrl.hash && urlWithoutHash(originUrl).href === destinationUrl.href) {
    destinationUrl.hash = originUrl.hash;
  }
};
var isSameUrlWithoutHash = (url1, url2) => {
  return urlWithoutHash(url1).href === urlWithoutHash(url2).href;
};
var isSameUrlWithoutQueryOrHash = (url1, url2) => {
  return url1.origin === url2.origin && url1.pathname === url2.pathname;
};
function isUrlMethodPair(href) {
  return href !== null && typeof href === "object" && href !== void 0 && "url" in href && "method" in href;
}
function resolveUrlMethodPairComponent(pair) {
  if (!pair.component) {
    return null;
  }
  if (typeof pair.component !== "string") {
    console.error(
      `The "component" property on the URL method pair received multiple components (${Object.keys(pair.component).join(", ")}), but only a single component string is supported for instant visits. Use the withComponent() method to specify which component to use.`
    );
    return null;
  }
  return pair.component;
}
function urlHasProtocol(url) {
  return /^([a-z][a-z0-9+.-]*:)?\/\/[^/]/i.test(url);
}
function urlToString(url, absolute) {
  const urlObj = typeof url === "string" ? hrefToUrl(url) : url;
  return absolute ? `${urlObj.protocol}//${urlObj.host}${urlObj.pathname}${urlObj.search}${urlObj.hash}` : `${urlObj.pathname}${urlObj.search}${urlObj.hash}`;
}
var CurrentPage = class {
  page;
  swapComponent;
  resolveComponent;
  onFlashCallback;
  componentId = {};
  listeners = [];
  isFirstPageLoad = true;
  cleared = false;
  pendingDeferredProps = null;
  historyQuotaExceeded = false;
  optimisticBaseline = {};
  pendingOptimistics = [];
  optimisticCounter = 0;
  init({
    initialPage,
    swapComponent,
    resolveComponent,
    onFlash
  }) {
    this.page = { ...initialPage, flash: initialPage.flash ?? {}, rescuedProps: initialPage.rescuedProps ?? [] };
    this.swapComponent = swapComponent;
    this.resolveComponent = resolveComponent;
    this.onFlashCallback = onFlash;
    eventHandler.on("historyQuotaExceeded", () => {
      this.historyQuotaExceeded = true;
    });
    return this;
  }
  set(page22, {
    replace: replace2 = false,
    preserveScroll = false,
    preserveState = false,
    viewTransition = false
  } = {}) {
    if (Object.keys(page22.deferredProps || {}).length) {
      this.pendingDeferredProps = {
        deferredProps: page22.deferredProps,
        component: page22.component,
        url: page22.url
      };
      if (page22.initialDeferredProps === void 0) {
        page22.initialDeferredProps = page22.deferredProps;
      }
    }
    this.componentId = {};
    const componentId = this.componentId;
    if (page22.clearHistory) {
      history.clear();
    }
    return this.resolve(page22.component, page22).then((component2) => {
      if (componentId !== this.componentId) {
        return;
      }
      page22.rememberedState ??= {};
      const isServer3 = typeof window === "undefined";
      const location = !isServer3 ? window.location : new URL(page22.url);
      const scrollRegions = !isServer3 && preserveScroll ? Scroll.getScrollRegions() : [];
      replace2 = replace2 || isSameUrlWithoutHash(hrefToUrl(page22.url), location);
      const pageForHistory = { ...page22, flash: {} };
      return new Promise(
        (resolve) => replace2 ? history.replaceState(pageForHistory, resolve) : history.pushState(pageForHistory, resolve)
      ).then(() => {
        const isNewComponent = !this.isTheSame(page22);
        if (!isNewComponent && Object.keys(page22.props.errors || {}).length > 0) {
          viewTransition = false;
        }
        this.page = page22;
        this.cleared = false;
        if (this.hasOnceProps()) {
          prefetchedRequests.updateCachedOncePropsFromCurrentPage();
        }
        if (isNewComponent) {
          this.fireEventsFor("newComponent");
        }
        if (this.isFirstPageLoad) {
          this.fireEventsFor("firstLoad");
        }
        this.isFirstPageLoad = false;
        if (this.historyQuotaExceeded) {
          this.historyQuotaExceeded = false;
          return;
        }
        return this.swap({
          component: component2,
          page: page22,
          preserveState,
          viewTransition
        }).then(() => {
          if (preserveScroll) {
            window.requestAnimationFrame(() => Scroll.restoreScrollRegions(scrollRegions));
          } else {
            Scroll.reset();
          }
          if (this.pendingDeferredProps && this.pendingDeferredProps.component === page22.component && this.pendingDeferredProps.url === page22.url) {
            eventHandler.fireInternalEvent("loadDeferredProps", this.pendingDeferredProps.deferredProps);
          }
          this.pendingDeferredProps = null;
          if (!replace2) {
            fireNavigateEvent(page22);
          }
        });
      });
    });
  }
  setQuietly(page22, {
    preserveState = false
  } = {}) {
    return this.resolve(page22.component, page22).then((component2) => {
      this.page = page22;
      this.cleared = false;
      history.setCurrent(page22);
      return this.swap({ component: component2, page: page22, preserveState, viewTransition: false });
    });
  }
  clear() {
    this.cleared = true;
  }
  isCleared() {
    return this.cleared;
  }
  get() {
    return this.page;
  }
  getWithoutFlashData() {
    return { ...this.page, flash: {} };
  }
  hasOnceProps() {
    return Object.keys(this.page.onceProps ?? {}).length > 0;
  }
  merge(data) {
    this.page = { ...this.page, ...data };
  }
  setPropsQuietly(props) {
    this.page = { ...this.page, props };
    return this.resolve(this.page.component, this.page).then((component2) => {
      return this.swap({ component: component2, page: this.page, preserveState: true, viewTransition: false });
    });
  }
  setFlash(flash) {
    this.page = { ...this.page, flash };
    this.onFlashCallback?.(flash);
  }
  setUrlHash(hash) {
    if (!this.page.url.includes(hash)) {
      this.page.url += hash;
    }
  }
  remember(data) {
    this.page.rememberedState = data;
  }
  swap({
    component: component2,
    page: page22,
    preserveState,
    viewTransition
  }) {
    const doSwap = () => this.swapComponent({ component: component2, page: page22, preserveState });
    if (!viewTransition || !document?.startViewTransition || document.visibilityState === "hidden") {
      return doSwap();
    }
    const viewTransitionCallback = typeof viewTransition === "boolean" ? () => null : viewTransition;
    return new Promise((resolve) => {
      const transitionResult = document.startViewTransition(() => doSwap().then(resolve));
      viewTransitionCallback(transitionResult);
    });
  }
  resolve(component2, page22) {
    return Promise.resolve(this.resolveComponent(component2, page22));
  }
  nextOptimisticId() {
    return ++this.optimisticCounter;
  }
  setBaseline(key2, value) {
    if (!(key2 in this.optimisticBaseline)) {
      this.optimisticBaseline[key2] = value;
    }
  }
  updateBaseline(key2, value) {
    if (key2 in this.optimisticBaseline) {
      this.optimisticBaseline[key2] = value;
    }
  }
  hasBaseline(key2) {
    return key2 in this.optimisticBaseline;
  }
  registerOptimistic(id, callback) {
    this.pendingOptimistics.push({ id, callback });
  }
  unregisterOptimistic(id) {
    this.pendingOptimistics = this.pendingOptimistics.filter((entry) => entry.id !== id);
  }
  replayOptimistics() {
    const baselineKeys = Object.keys(this.optimisticBaseline);
    if (baselineKeys.length === 0) {
      return {};
    }
    const props = cloneDeep(this.page.props);
    for (const key2 of baselineKeys) {
      props[key2] = cloneDeep(this.optimisticBaseline[key2]);
    }
    for (const { callback } of this.pendingOptimistics) {
      const result2 = callback(cloneDeep(props));
      if (result2) {
        Object.assign(props, result2);
      }
    }
    const replayedProps = {};
    for (const key2 of baselineKeys) {
      replayedProps[key2] = props[key2];
    }
    return replayedProps;
  }
  pendingOptimisticCount() {
    return this.pendingOptimistics.length;
  }
  clearOptimisticState() {
    this.optimisticBaseline = {};
    this.pendingOptimistics = [];
  }
  isTheSame(page22) {
    return this.page.component === page22.component;
  }
  on(event, callback) {
    this.listeners.push({ event, callback });
    return () => {
      this.listeners = this.listeners.filter((listener) => listener.event !== event && listener.callback !== callback);
    };
  }
  fireEventsFor(event) {
    this.listeners.filter((listener) => listener.event === event).forEach((listener) => listener.callback());
  }
  mergeOncePropsIntoResponse(response, { force = false } = {}) {
    Object.entries(response.onceProps ?? {}).forEach(([key2, onceProp]) => {
      const existingOnceProp = this.page.onceProps?.[key2];
      if (existingOnceProp === void 0) {
        return;
      }
      if (force || get(response.props, onceProp.prop) === void 0) {
        set(response.props, onceProp.prop, get(this.page.props, existingOnceProp.prop));
        response.onceProps[key2].expiresAt = existingOnceProp.expiresAt;
      }
    });
  }
};
var page = new CurrentPage();
var Queue = class {
  items = [];
  processingPromise = null;
  add(item) {
    this.items.push(item);
    return this.process();
  }
  process() {
    this.processingPromise ??= this.processNext().finally(() => {
      this.processingPromise = null;
    });
    return this.processingPromise;
  }
  processNext() {
    const next = this.items.shift();
    if (next) {
      return Promise.resolve(next()).then(() => this.processNext());
    }
    return Promise.resolve();
  }
};
var isServer2 = typeof window === "undefined";
var queue = new Queue();
var isChromeIOS = !isServer2 && /CriOS/.test(window.navigator.userAgent);
var History = class {
  rememberedState = "rememberedState";
  scrollRegions = "scrollRegions";
  preserveUrl = false;
  current = {};
  // We need initialState for `restore`
  initialState = null;
  remember(data, key2) {
    this.replaceState({
      ...page.getWithoutFlashData(),
      rememberedState: {
        ...page.get()?.rememberedState ?? {},
        [key2]: data
      }
    });
  }
  restore(key2) {
    if (!isServer2) {
      return this.current[this.rememberedState]?.[key2] !== void 0 ? this.current[this.rememberedState]?.[key2] : this.initialState?.[this.rememberedState]?.[key2];
    }
  }
  pushState(page22, cb = null) {
    if (isServer2) {
      return;
    }
    if (this.preserveUrl) {
      cb && cb();
      return;
    }
    this.current = page22;
    queue.add(() => {
      return this.getPageData(page22).then((data) => {
        const doPush = () => this.doPushState({ page: data }, page22.url).then(() => cb?.());
        if (isChromeIOS) {
          return new Promise((resolve) => {
            setTimeout(() => doPush().then(resolve));
          });
        }
        return doPush();
      });
    });
  }
  clonePageProps(page22) {
    try {
      structuredClone(page22.props);
      return page22;
    } catch {
      return {
        ...page22,
        props: cloneDeep(page22.props)
      };
    }
  }
  getPageData(page22) {
    const pageWithClonedProps = this.clonePageProps(page22);
    return new Promise((resolve) => {
      return page22.encryptHistory ? encryptHistory(pageWithClonedProps).then(resolve) : resolve(pageWithClonedProps);
    });
  }
  processQueue() {
    return queue.process();
  }
  decrypt(page22 = null) {
    if (isServer2) {
      return Promise.resolve(page22 ?? page.get());
    }
    const pageData = page22 ?? window.history.state?.page;
    return this.decryptPageData(pageData).then((data) => {
      if (!data) {
        throw new Error("Unable to decrypt history");
      }
      if (this.initialState === null) {
        this.initialState = data ?? void 0;
      } else {
        this.current = data ?? {};
      }
      return data;
    });
  }
  decryptPageData(pageData) {
    return pageData instanceof ArrayBuffer ? decryptHistory(pageData) : Promise.resolve(pageData);
  }
  saveScrollPositions(scrollRegions) {
    queue.add(() => {
      return Promise.resolve().then(() => {
        if (!window.history.state?.page) {
          return;
        }
        if (isEqual(this.getScrollRegions(), scrollRegions)) {
          return;
        }
        return this.doReplaceState({
          page: window.history.state.page,
          scrollRegions
        });
      });
    });
  }
  saveDocumentScrollPosition(scrollRegion) {
    queue.add(() => {
      return Promise.resolve().then(() => {
        if (!window.history.state?.page) {
          return;
        }
        if (isEqual(this.getDocumentScrollPosition(), scrollRegion)) {
          return;
        }
        return this.doReplaceState({
          page: window.history.state.page,
          documentScrollPosition: scrollRegion
        });
      });
    });
  }
  getScrollRegions() {
    return window.history.state?.scrollRegions || [];
  }
  getDocumentScrollPosition() {
    return window.history.state?.documentScrollPosition || { top: 0, left: 0 };
  }
  replaceState(page22, cb = null) {
    if (isEqual(this.current, page22)) {
      cb && cb();
      return;
    }
    const { flash, ...pageWithoutFlash } = page22;
    page.merge(pageWithoutFlash);
    if (isServer2) {
      return;
    }
    if (this.preserveUrl) {
      cb && cb();
      return;
    }
    this.current = page22;
    queue.add(() => {
      return this.getPageData(page22).then((data) => {
        const doReplace = () => this.doReplaceState({ page: data }, page22.url).then(() => cb?.());
        if (isChromeIOS) {
          return new Promise((resolve) => {
            setTimeout(() => doReplace().then(resolve));
          });
        }
        return doReplace();
      });
    });
  }
  isHistoryThrottleError(error) {
    return error instanceof Error && error.name === "SecurityError" && (error.message.includes("history.pushState") || error.message.includes("history.replaceState"));
  }
  isQuotaExceededError(error) {
    return error instanceof Error && error.name === "QuotaExceededError";
  }
  withThrottleProtection(cb) {
    return Promise.resolve().then(() => {
      try {
        return cb();
      } catch (error) {
        if (!this.isHistoryThrottleError(error)) {
          throw error;
        }
        console.error(error.message);
      }
    });
  }
  doReplaceState(data, url) {
    return this.withThrottleProtection(() => {
      window.history.replaceState(
        {
          ...data,
          scrollRegions: data.scrollRegions ?? window.history.state?.scrollRegions,
          documentScrollPosition: data.documentScrollPosition ?? window.history.state?.documentScrollPosition
        },
        "",
        url
      );
    });
  }
  doPushState(data, url) {
    return this.withThrottleProtection(() => {
      try {
        window.history.pushState(data, "", url);
      } catch (error) {
        if (!this.isQuotaExceededError(error)) {
          throw error;
        }
        eventHandler.fireInternalEvent("historyQuotaExceeded", url);
      }
    });
  }
  getState(key2, defaultValue) {
    return this.current?.[key2] ?? defaultValue;
  }
  deleteState(key2) {
    if (this.current[key2] !== void 0) {
      delete this.current[key2];
      this.replaceState(this.current);
    }
  }
  clearInitialState(key2) {
    if (this.initialState && this.initialState[key2] !== void 0) {
      delete this.initialState[key2];
    }
  }
  browserHasHistoryEntry() {
    return !isServer2 && !!window.history.state?.page;
  }
  clear() {
    SessionStorage.remove(historySessionStorageKeys.key);
    SessionStorage.remove(historySessionStorageKeys.iv);
  }
  setCurrent(page22) {
    this.current = page22;
  }
  isValidState(state2) {
    return !!state2.page;
  }
  getAllState() {
    return this.current;
  }
};
if (typeof window !== "undefined" && window.history.scrollRestoration) {
  window.history.scrollRestoration = "manual";
}
var history = new History();
var EventHandler = class {
  internalListeners = [];
  init() {
    if (typeof window !== "undefined") {
      window.addEventListener("popstate", this.handlePopstateEvent.bind(this));
      window.addEventListener("pageshow", this.handlePageshowEvent.bind(this));
      window.addEventListener("scroll", debounce3(Scroll.onWindowScroll.bind(Scroll), 100), true);
    }
    if (typeof document !== "undefined") {
      document.addEventListener("scroll", debounce3(Scroll.onScroll.bind(Scroll), 100), true);
    }
  }
  onGlobalEvent(type, callback) {
    const listener = ((event) => {
      const response = callback(event);
      if (event.cancelable && !event.defaultPrevented && response === false) {
        event.preventDefault();
      }
    });
    return this.registerListener(`inertia:${type}`, listener);
  }
  on(event, callback) {
    this.internalListeners.push({ event, listener: callback });
    return () => {
      this.internalListeners = this.internalListeners.filter((listener) => listener.listener !== callback);
    };
  }
  onMissingHistoryItem() {
    page.clear();
    this.fireInternalEvent("missingHistoryItem");
  }
  fireInternalEvent(event, ...args) {
    this.internalListeners.filter((listener) => listener.event === event).forEach((listener) => listener.listener(...args));
  }
  registerListener(type, listener) {
    document.addEventListener(type, listener);
    return () => document.removeEventListener(type, listener);
  }
  // bfcache restores pages without firing `popstate`, so we use `pageshow` to
  // re-validate encrypted history entries after `clearHistory` removed the keys.
  // https://web.dev/articles/bfcache
  handlePageshowEvent(event) {
    if (event.persisted) {
      history.decrypt().catch(() => this.onMissingHistoryItem());
    }
  }
  handlePopstateEvent(event) {
    const state2 = event.state || null;
    if (state2 === null) {
      const url = hrefToUrl(page.get().url);
      url.hash = window.location.hash;
      history.replaceState({ ...page.getWithoutFlashData(), url: url.href });
      Scroll.reset();
      return;
    }
    if (!history.isValidState(state2)) {
      return this.onMissingHistoryItem();
    }
    history.decrypt(state2.page).then((data) => {
      if (page.get().version !== data.version) {
        this.onMissingHistoryItem();
        return;
      }
      router.cancelAll({ prefetch: false });
      page.setQuietly(data, { preserveState: false }).then(() => {
        Scroll.restore(history.getScrollRegions());
        fireNavigateEvent(page.get());
        const pendingDeferred = {};
        const pageProps = page.get().props;
        for (const [group, props] of Object.entries(data.initialDeferredProps ?? data.deferredProps ?? {})) {
          const missing = props.filter((prop) => get(pageProps, prop) === void 0);
          if (missing.length > 0) {
            pendingDeferred[group] = missing;
          }
        }
        if (Object.keys(pendingDeferred).length > 0) {
          this.fireInternalEvent("loadDeferredProps", pendingDeferred);
        }
      });
    }).catch(() => {
      this.onMissingHistoryItem();
    });
  }
};
var eventHandler = new EventHandler();
var NavigationType = class {
  type;
  constructor() {
    this.type = this.resolveType();
  }
  resolveType() {
    if (typeof window === "undefined") {
      return "navigate";
    }
    const entry = window.performance?.getEntriesByType("navigation")[0];
    return entry?.type ?? "navigate";
  }
  get() {
    return this.type;
  }
  isBackForward() {
    return this.type === "back_forward";
  }
  isReload() {
    return this.type === "reload";
  }
};
var navigationType = new NavigationType();
var InitialVisit = class {
  static handle() {
    this.clearRememberedStateOnReload();
    const scenarios = [this.handleBackForward, this.handleLocation, this.handleDefault];
    scenarios.find((handler) => handler.bind(this)());
  }
  static clearRememberedStateOnReload() {
    if (navigationType.isReload()) {
      history.deleteState(history.rememberedState);
      history.clearInitialState(history.rememberedState);
    }
  }
  static handleBackForward() {
    if (!navigationType.isBackForward() || !history.browserHasHistoryEntry()) {
      return false;
    }
    const scrollRegions = history.getScrollRegions();
    history.decrypt().then((data) => {
      page.set(data, { preserveScroll: true, preserveState: true }).then(() => {
        Scroll.restore(scrollRegions);
        fireNavigateEvent(page.get());
      });
    }).catch(() => {
      eventHandler.onMissingHistoryItem();
    });
    return true;
  }
  /**
   * @link https://inertiajs.com/redirects#external-redirects
   */
  static handleLocation() {
    if (!SessionStorage.exists(SessionStorage.locationVisitKey)) {
      return false;
    }
    const locationVisit = SessionStorage.get(SessionStorage.locationVisitKey) || {};
    SessionStorage.remove(SessionStorage.locationVisitKey);
    if (typeof window !== "undefined") {
      page.setUrlHash(window.location.hash);
    }
    history.decrypt(page.get()).then(() => {
      const rememberedState = history.getState(history.rememberedState, {});
      const scrollRegions = history.getScrollRegions();
      page.remember(rememberedState);
      page.set(page.get(), {
        preserveScroll: locationVisit.preserveScroll,
        preserveState: true
      }).then(() => {
        if (locationVisit.preserveScroll) {
          Scroll.restore(scrollRegions);
        }
        this.fireInitialEvents();
      });
    }).catch(() => {
      eventHandler.onMissingHistoryItem();
    });
    return true;
  }
  static handleDefault() {
    if (typeof window !== "undefined") {
      page.setUrlHash(window.location.hash);
    }
    page.set(page.get(), { preserveScroll: true, preserveState: true }).then(() => {
      if (navigationType.isReload()) {
        Scroll.restore(history.getScrollRegions());
      } else {
        Scroll.scrollToAnchor();
      }
      this.fireInitialEvents();
    });
  }
  static fireInitialEvents() {
    const page22 = page.get();
    fireNavigateEvent(page22);
    if (Object.keys(page22.flash).length > 0) {
      queueMicrotask(() => fireFlashEvent(page22.flash));
    }
  }
};
var Poll = class {
  intervalId = null;
  timeoutId = null;
  throttle = false;
  keepAlive = false;
  cb;
  interval;
  cbCount = 0;
  mode;
  inFlight = false;
  currentCancel = null;
  stopped = true;
  instanceId = 0;
  constructor(interval, cb, options) {
    this.keepAlive = options.keepAlive ?? false;
    this.mode = options.mode ?? "overlap";
    this.cb = cb;
    this.interval = interval;
    if (options.autoStart ?? true) {
      this.start();
    }
  }
  stop() {
    this.stopped = true;
    this.instanceId++;
    this.inFlight = false;
    this.currentCancel = null;
    if (this.intervalId) {
      clearInterval(this.intervalId);
      this.intervalId = null;
    }
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
      this.timeoutId = null;
    }
  }
  start() {
    if (typeof window === "undefined") {
      return;
    }
    this.stop();
    this.stopped = false;
    if (this.mode === "rest") {
      this.scheduleNext();
      return;
    }
    this.intervalId = window.setInterval(() => this.tick(), this.interval);
  }
  isInBackground(hidden2) {
    this.throttle = this.keepAlive ? false : hidden2;
    if (this.throttle) {
      this.cbCount = 0;
    }
  }
  scheduleNext() {
    if (this.stopped) {
      return;
    }
    this.timeoutId = window.setTimeout(() => {
      this.timeoutId = null;
      this.tick();
    }, this.interval);
  }
  tick() {
    if (!this.throttle || this.cbCount % 10 === 0) {
      this.fire();
    } else if (this.mode === "rest") {
      this.scheduleNext();
    }
    if (this.throttle) {
      this.cbCount++;
    }
  }
  fire() {
    if (this.inFlight && this.mode === "cancel") {
      this.currentCancel?.();
    }
    const instance = this.instanceId;
    this.cb({
      onStart: (cancel) => {
        if (instance !== this.instanceId) {
          return;
        }
        this.inFlight = true;
        this.currentCancel = cancel;
      },
      onFinish: () => {
        if (instance !== this.instanceId) {
          return;
        }
        this.inFlight = false;
        this.currentCancel = null;
        if (this.mode === "rest") {
          this.scheduleNext();
        }
      }
    });
  }
};
var Polls = class {
  polls = [];
  constructor() {
    this.setupVisibilityListener();
  }
  get count() {
    return this.polls.length;
  }
  add(interval, cb, options) {
    const poll = new Poll(interval, cb, options);
    this.polls.push(poll);
    return {
      stop: () => poll.stop(),
      start: () => poll.start(),
      destroy: () => {
        poll.stop();
        this.polls = this.polls.filter((p) => p !== poll);
      }
    };
  }
  clear() {
    this.polls.forEach((poll) => poll.stop());
    this.polls = [];
  }
  setupVisibilityListener() {
    if (typeof document === "undefined") {
      return;
    }
    document.addEventListener(
      "visibilitychange",
      () => {
        this.polls.forEach((poll) => poll.isInBackground(document.hidden));
      },
      false
    );
  }
};
var polls = new Polls();
var HttpHandlers = class {
  requestHandlers = [];
  responseHandlers = [];
  errorHandlers = [];
  onRequest(handler) {
    this.requestHandlers.push(handler);
    return () => {
      this.requestHandlers = this.requestHandlers.filter((h2) => h2 !== handler);
    };
  }
  onResponse(handler) {
    this.responseHandlers.push(handler);
    return () => {
      this.responseHandlers = this.responseHandlers.filter((h2) => h2 !== handler);
    };
  }
  onError(handler) {
    this.errorHandlers.push(handler);
    return () => {
      this.errorHandlers = this.errorHandlers.filter((h2) => h2 !== handler);
    };
  }
  async processRequest(config22) {
    let result2 = config22;
    for (const handler of this.requestHandlers) {
      result2 = await handler(result2);
    }
    return result2;
  }
  async processResponse(response) {
    let result2 = response;
    for (const handler of this.responseHandlers) {
      result2 = await handler(result2);
    }
    return result2;
  }
  async processError(error) {
    for (const handler of this.errorHandlers) {
      await handler(error);
    }
  }
};
var httpHandlers = new HttpHandlers();
var HttpError = class extends Error {
  code;
  url;
  constructor(message, code, url) {
    super(url ? `${message} (${url})` : message);
    this.name = "HttpError";
    this.code = code;
    this.url = url;
  }
};
var HttpResponseError2 = class extends HttpError {
  response;
  constructor(message, response, url) {
    super(message, "ERR_HTTP_RESPONSE", url);
    this.name = "HttpResponseError";
    this.response = response;
  }
};
var HttpCancelledError2 = class extends HttpError {
  constructor(message = "Request was cancelled", url) {
    super(message, "ERR_CANCELLED", url);
    this.name = "HttpCancelledError";
  }
};
var HttpNetworkError2 = class extends HttpError {
  cause;
  constructor(message, url, cause) {
    super(message, "ERR_NETWORK", url);
    this.name = "HttpNetworkError";
    this.cause = cause;
  }
};
function getCookie(name) {
  const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)"));
  return match ? decodeURIComponent(match[3]) : null;
}
function parseHeaders2(xhr) {
  const headers = {};
  xhr.getAllResponseHeaders().split("\r\n").forEach((line) => {
    const index = line.indexOf(":");
    if (index > 0) {
      headers[line.slice(0, index).toLowerCase().trim()] = line.slice(index + 1).trim();
    }
  });
  return headers;
}
function setHeaders(xhr, config22) {
  if (!config22.headers) {
    return;
  }
  const isFormData2 = config22.data instanceof FormData;
  Object.entries(config22.headers).forEach(([key2, value]) => {
    if (key2.toLowerCase() !== "content-type" || !isFormData2) {
      xhr.setRequestHeader(key2, String(value));
    }
  });
}
function buildUrlWithParams(url, params) {
  if (!params || Object.keys(params).length === 0) {
    return url;
  }
  const [urlWithParams] = mergeDataIntoQueryString("get", url, params);
  return urlWithParams;
}
var XhrHttpClient = class {
  xsrfCookieName;
  xsrfHeaderName;
  constructor(options = {}) {
    this.xsrfCookieName = options.xsrfCookieName ?? "XSRF-TOKEN";
    this.xsrfHeaderName = options.xsrfHeaderName ?? "X-XSRF-TOKEN";
  }
  async request(config22) {
    const processedConfig = await httpHandlers.processRequest(config22);
    try {
      const response = await this.doRequest(processedConfig);
      return await httpHandlers.processResponse(response);
    } catch (error) {
      if (error instanceof HttpResponseError2 || error instanceof HttpNetworkError2 || error instanceof HttpCancelledError2) {
        await httpHandlers.processError(error);
      }
      throw error;
    }
  }
  doRequest(config22) {
    return new Promise((resolve, reject2) => {
      const xhr = new XMLHttpRequest();
      const url = buildUrlWithParams(config22.url, config22.params);
      xhr.open(config22.method.toUpperCase(), url, true);
      const xsrfToken = getCookie(this.xsrfCookieName);
      if (xsrfToken) {
        xhr.setRequestHeader(this.xsrfHeaderName, xsrfToken);
      }
      let body = null;
      if (config22.data !== null && config22.data !== void 0) {
        if (config22.data instanceof FormData) {
          body = config22.data;
        } else if (typeof config22.data === "object") {
          body = JSON.stringify(config22.data);
          if (!config22.headers?.["Content-Type"] && !config22.headers?.["content-type"]) {
            xhr.setRequestHeader("Content-Type", "application/json");
          }
        } else {
          body = String(config22.data);
        }
      }
      setHeaders(xhr, config22);
      if (config22.onUploadProgress) {
        xhr.upload.onprogress = (event) => {
          const progress3 = event.lengthComputable ? event.loaded / event.total : void 0;
          config22.onUploadProgress({
            progress: progress3,
            percentage: progress3 ? Math.round(progress3 * 100) : 0,
            loaded: event.loaded,
            total: event.lengthComputable ? event.total : void 0
          });
        };
      }
      if (config22.signal) {
        config22.signal.addEventListener("abort", () => xhr.abort());
      }
      xhr.onabort = () => reject2(new HttpCancelledError2("Request was cancelled", config22.url));
      xhr.onerror = () => reject2(new HttpNetworkError2("Network error", config22.url));
      xhr.onload = () => {
        const response = {
          status: xhr.status,
          data: xhr.responseText,
          headers: parseHeaders2(xhr)
        };
        if (xhr.status >= 400) {
          reject2(new HttpResponseError2(`Request failed with status ${xhr.status}`, response, config22.url));
        } else {
          resolve(response);
        }
      };
      xhr.send(body);
    });
  }
};
var xhrHttpClient = new XhrHttpClient();
var httpClient2 = xhrHttpClient;
function isHttpClientOptions(client2) {
  return !("request" in client2);
}
var http = {
  /**
   * Get the current HTTP client
   */
  getClient() {
    return httpClient2;
  },
  /**
   * Set the HTTP client to use for all Inertia requests
   */
  setClient(clientOrOptions) {
    if (!isHttpClientOptions(clientOrOptions)) {
      httpClient2 = clientOrOptions;
      return;
    }
    httpClient2 = new XhrHttpClient(clientOrOptions);
    if (clientOrOptions.xsrfCookieName) {
      client.withXsrfCookieName(clientOrOptions.xsrfCookieName);
    }
    if (clientOrOptions.xsrfHeaderName) {
      client.withXsrfHeaderName(clientOrOptions.xsrfHeaderName);
    }
  },
  /**
   * Register a request handler that runs before each request
   */
  onRequest: httpHandlers.onRequest.bind(httpHandlers),
  /**
   * Register a response handler that runs after each successful response
   */
  onResponse: httpHandlers.onResponse.bind(httpHandlers),
  /**
   * Register an error handler that runs when a request fails
   */
  onError: httpHandlers.onError.bind(httpHandlers),
  /**
   * Process a request config through all registered request handlers.
   * For use by custom HttpClient implementations.
   */
  processRequest: httpHandlers.processRequest.bind(httpHandlers),
  /**
   * Process a response through all registered response handlers.
   * For use by custom HttpClient implementations.
   */
  processResponse: httpHandlers.processResponse.bind(httpHandlers),
  /**
   * Process an error through all registered error handlers.
   * For use by custom HttpClient implementations.
   */
  processError: httpHandlers.processError.bind(httpHandlers)
};
var RequestParams = class _RequestParams {
  callbacks = [];
  params;
  constructor(params) {
    if (!params.prefetch) {
      this.params = params;
    } else {
      const wrappedCallbacks = {
        onBefore: this.wrapCallback(params, "onBefore"),
        onBeforeUpdate: this.wrapCallback(params, "onBeforeUpdate"),
        onStart: this.wrapCallback(params, "onStart"),
        onProgress: this.wrapCallback(params, "onProgress"),
        onFinish: this.wrapCallback(params, "onFinish"),
        onCancel: this.wrapCallback(params, "onCancel"),
        onSuccess: this.wrapCallback(params, "onSuccess"),
        onError: this.wrapCallback(params, "onError"),
        onHttpException: this.wrapCallback(params, "onHttpException"),
        onNetworkError: this.wrapCallback(params, "onNetworkError"),
        onFlash: this.wrapCallback(params, "onFlash"),
        onCancelToken: this.wrapCallback(params, "onCancelToken"),
        onPrefetched: this.wrapCallback(params, "onPrefetched"),
        onPrefetching: this.wrapCallback(params, "onPrefetching")
      };
      this.params = {
        ...params,
        ...wrappedCallbacks,
        onPrefetchResponse: params.onPrefetchResponse || (() => {
        }),
        onPrefetchError: params.onPrefetchError || (() => {
        })
      };
    }
  }
  static create(params) {
    return new _RequestParams(params);
  }
  data() {
    return this.params.method === "get" ? null : this.params.data;
  }
  queryParams() {
    return this.params.method === "get" ? this.params.data : {};
  }
  isPartial() {
    return this.params.only.length > 0 || this.params.except.length > 0 || this.params.reset.length > 0;
  }
  isPrefetch() {
    return this.params.prefetch === true;
  }
  isDeferredPropsRequest() {
    return this.params.deferredProps === true;
  }
  onCancelToken(cb) {
    this.params.onCancelToken({
      cancel: cb
    });
  }
  markAsFinished() {
    this.params.completed = true;
    this.params.cancelled = false;
    this.params.interrupted = false;
  }
  markAsCancelled({ cancelled = true, interrupted = false }) {
    this.params.onCancel();
    this.params.completed = false;
    this.params.cancelled = cancelled;
    this.params.interrupted = interrupted;
  }
  wasCancelledAtAll() {
    return this.params.cancelled || this.params.interrupted;
  }
  onFinish() {
    this.params.onFinish(this.params);
  }
  onStart() {
    this.params.onStart(this.params);
  }
  onPrefetching() {
    this.params.onPrefetching(this.params);
  }
  onPrefetchResponse(response) {
    if (this.params.onPrefetchResponse) {
      this.params.onPrefetchResponse(response);
    }
  }
  onPrefetchError(error) {
    if (this.params.onPrefetchError) {
      this.params.onPrefetchError(error);
    }
  }
  all() {
    return this.params;
  }
  headers() {
    const headers = {
      ...this.params.headers
    };
    if (this.isPartial()) {
      headers["X-Inertia-Partial-Component"] = page.get().component;
    }
    const only = this.params.only.concat(this.params.reset);
    if (only.length > 0) {
      headers["X-Inertia-Partial-Data"] = only.join(",");
    }
    if (this.params.except.length > 0) {
      headers["X-Inertia-Partial-Except"] = this.params.except.join(",");
    }
    if (this.params.reset.length > 0) {
      headers["X-Inertia-Reset"] = this.params.reset.join(",");
    }
    if (this.params.errorBag && this.params.errorBag.length > 0) {
      headers["X-Inertia-Error-Bag"] = this.params.errorBag;
    }
    return headers;
  }
  setPreserveOptions(page22) {
    this.params.preserveScroll = _RequestParams.resolvePreserveOption(this.params.preserveScroll, page22);
    this.params.preserveState = _RequestParams.resolvePreserveOption(this.params.preserveState, page22);
  }
  runCallbacks() {
    this.callbacks.forEach(({ name, args }) => {
      this.params[name](...args);
    });
  }
  merge(toMerge) {
    this.params = {
      ...this.params,
      ...toMerge
    };
  }
  wrapCallback(params, name) {
    return (...args) => {
      this.recordCallback(name, args);
      params[name](...args);
    };
  }
  recordCallback(name, args) {
    this.callbacks.push({ name, args });
  }
  static resolvePreserveOption(value, page22) {
    if (typeof value === "function") {
      return value(page22);
    }
    if (value === "errors") {
      return Object.keys(page22.props.errors || {}).length > 0;
    }
    return value;
  }
};
var dialog_default = {
  createIframeAndPage(html) {
    if (typeof html === "object") {
      html = `All Inertia requests must receive a valid Inertia response, however a plain JSON response was received.<hr>${JSON.stringify(
        html
      )}`;
    }
    const page22 = document.createElement("html");
    page22.innerHTML = html;
    page22.querySelectorAll("a").forEach((a) => a.setAttribute("target", "_top"));
    const iframe = document.createElement("iframe");
    iframe.style.backgroundColor = "white";
    iframe.style.borderRadius = "5px";
    iframe.style.width = "100%";
    iframe.style.height = "100%";
    iframe.setAttribute("sandbox", "allow-scripts");
    return { iframe, page: page22 };
  },
  show(html) {
    const { iframe, page: page22 } = this.createIframeAndPage(html);
    iframe.style.boxSizing = "border-box";
    iframe.style.display = "block";
    const dialog = document.createElement("dialog");
    dialog.id = "inertia-error-dialog";
    Object.assign(dialog.style, {
      width: "calc(100vw - 100px)",
      height: "calc(100vh - 100px)",
      padding: "0",
      margin: "auto",
      border: "none",
      backgroundColor: "transparent"
    });
    const dialogStyleElement = document.createElement("style");
    dialogStyleElement.textContent = `
      dialog#inertia-error-dialog::backdrop {
        background-color: rgba(0, 0, 0, 0.6);
      }

      dialog#inertia-error-dialog:focus {
        outline: none;
      }
    `;
    const nonce = config.get("nonce");
    if (nonce) {
      dialogStyleElement.nonce = nonce;
    }
    document.head.appendChild(dialogStyleElement);
    dialog.addEventListener("click", (event) => {
      if (event.target === dialog) {
        dialog.close();
      }
    });
    dialog.addEventListener("close", () => {
      dialogStyleElement.remove();
      dialog.remove();
    });
    dialog.appendChild(iframe);
    document.body.prepend(dialog);
    dialog.showModal();
    dialog.focus();
    iframe.srcdoc = page22.outerHTML;
  }
};
var isPathOrSubPath = (path, candidate) => {
  return path === candidate || path.startsWith(`${candidate}.`);
};
var partialReloadRequestsProp = (visit, prop) => {
  const { only, except } = visit;
  if (only.length === 0 && except.length === 0) {
    return false;
  }
  if (only.length > 0 && !only.some((candidate) => isPathOrSubPath(prop, candidate))) {
    return false;
  }
  if (except.length > 0 && except.some((candidate) => isPathOrSubPath(prop, candidate))) {
    return false;
  }
  return true;
};
var partialReloadRequestsSomeProps = (visit, props) => {
  return props.some((prop) => partialReloadRequestsProp(visit, prop));
};
var queue2 = new Queue();
var Response = class _Response {
  constructor(requestParams, response, originatingPage) {
    this.requestParams = requestParams;
    this.response = response;
    this.originatingPage = originatingPage;
  }
  wasPrefetched = false;
  processed = false;
  static create(params, response, originatingPage) {
    return new _Response(params, response, originatingPage);
  }
  isProcessed() {
    return this.processed;
  }
  async handlePrefetch() {
    if (isSameUrlWithoutHash(this.requestParams.all().url, window.location)) {
      this.handle();
    }
  }
  async handle() {
    return queue2.add(() => this.process());
  }
  async process() {
    if (this.requestParams.all().prefetch) {
      this.wasPrefetched = true;
      this.requestParams.all().prefetch = false;
      this.requestParams.all().onPrefetched(this.response, this.requestParams.all());
      firePrefetchedEvent(this.response, this.requestParams.all());
      return Promise.resolve();
    }
    this.requestParams.runCallbacks();
    this.processed = true;
    if (!this.isInertiaResponse()) {
      return this.handleNonInertiaResponse();
    }
    if (this.isHttpException()) {
      const response = {
        ...this.response,
        data: this.getDataFromResponse(this.response.data)
      };
      if (this.requestParams.all().onHttpException(response) === false) {
        return;
      }
      if (!fireHttpExceptionEvent(response)) {
        return;
      }
    }
    await history.processQueue();
    history.preserveUrl = this.requestParams.all().preserveUrl;
    await this.setPage();
    const { flash } = page.get();
    if (Object.keys(flash).length > 0 && !this.requestParams.isDeferredPropsRequest()) {
      fireFlashEvent(flash);
      this.requestParams.all().onFlash(flash);
    }
    const errors = page.get().props.errors || {};
    if (Object.keys(errors).length > 0) {
      const scopedErrors = this.getScopedErrors(errors);
      fireErrorEvent(scopedErrors);
      return this.requestParams.all().onError(scopedErrors);
    }
    router.flushByCacheTags(this.requestParams.all().invalidateCacheTags || []);
    if (!this.wasPrefetched) {
      router.flush(page.get().url);
    }
    fireSuccessEvent(page.get());
    await this.requestParams.all().onSuccess(page.get());
    history.preserveUrl = false;
  }
  mergeParams(params) {
    this.requestParams.merge(params);
  }
  getPageResponse() {
    const data = this.getDataFromResponse(this.response.data);
    if (typeof data === "object") {
      return this.response.data = { ...data, flash: data.flash ?? {}, rescuedProps: data.rescuedProps ?? [] };
    }
    return this.response.data = data;
  }
  async handleNonInertiaResponse() {
    if (this.isInertiaRedirect()) {
      router.visit(this.getHeader("x-inertia-redirect"), {
        ...this.requestParams.all(),
        method: "get",
        data: {}
      });
      return;
    }
    if (this.isLocationVisit()) {
      const locationUrl = hrefToUrl(this.getHeader("x-inertia-location"));
      setHashIfSameUrl(this.requestParams.all().url, locationUrl);
      return this.locationVisit(locationUrl);
    }
    const response = {
      ...this.response,
      data: this.getDataFromResponse(this.response.data)
    };
    if (this.requestParams.all().onHttpException(response) === false) {
      return;
    }
    if (fireHttpExceptionEvent(response)) {
      return dialog_default.show(response.data);
    }
  }
  isInertiaResponse() {
    return this.hasHeader("x-inertia");
  }
  isHttpException() {
    return this.response.status >= 400;
  }
  hasStatus(status2) {
    return this.response.status === status2;
  }
  getHeader(header) {
    return this.response.headers[header];
  }
  hasHeader(header) {
    return this.getHeader(header) !== void 0;
  }
  isInertiaRedirect() {
    return this.hasStatus(409) && this.hasHeader("x-inertia-redirect");
  }
  isLocationVisit() {
    return this.hasStatus(409) && this.hasHeader("x-inertia-location");
  }
  /**
   * @link https://inertiajs.com/redirects#external-redirects
   */
  locationVisit(url) {
    try {
      SessionStorage.set(SessionStorage.locationVisitKey, {
        preserveScroll: this.requestParams.all().preserveScroll === true
      });
      if (typeof window === "undefined") {
        return;
      }
      if (isSameUrlWithoutHash(window.location, url)) {
        window.location.reload();
      } else {
        window.location.href = url.href;
      }
    } catch (error) {
      return false;
    }
  }
  async setPage() {
    const pageResponse = this.getPageResponse();
    if (!this.shouldSetPage(pageResponse)) {
      return Promise.resolve();
    }
    this.mergeProps(pageResponse);
    page.mergeOncePropsIntoResponse(pageResponse);
    this.preserveOptimisticProps(pageResponse);
    this.preserveEqualProps(pageResponse);
    await this.setRememberedState(pageResponse);
    this.requestParams.setPreserveOptions(pageResponse);
    pageResponse.url = history.preserveUrl ? page.get().url : this.pageUrl(pageResponse);
    this.requestParams.all().onBeforeUpdate(pageResponse);
    fireBeforeUpdateEvent(pageResponse);
    return page.set(pageResponse, {
      replace: this.requestParams.all().replace,
      preserveScroll: this.requestParams.all().preserveScroll,
      preserveState: this.requestParams.all().preserveState,
      viewTransition: this.requestParams.all().viewTransition
    });
  }
  getDataFromResponse(response) {
    if (typeof response !== "string") {
      return response;
    }
    try {
      return JSON.parse(response);
    } catch (error) {
      return response;
    }
  }
  shouldSetPage(pageResponse) {
    if (!this.requestParams.all().async) {
      return true;
    }
    if (this.originatingPage.component !== pageResponse.component) {
      return true;
    }
    if (this.originatingPage.component !== page.get().component) {
      return false;
    }
    const originatingUrl = hrefToUrl(this.originatingPage.url);
    const currentPageUrl = hrefToUrl(page.get().url);
    return originatingUrl.origin === currentPageUrl.origin && originatingUrl.pathname === currentPageUrl.pathname;
  }
  pageUrl(pageResponse) {
    const responseUrl = hrefToUrl(pageResponse.url);
    if (pageResponse.preserveFragment) {
      responseUrl.hash = this.requestParams.all().url.hash;
    } else {
      setHashIfSameUrl(this.requestParams.all().url, responseUrl);
    }
    return responseUrl.pathname + responseUrl.search + responseUrl.hash;
  }
  preserveOptimisticProps(pageResponse) {
    if (!router.hasPendingOptimistic()) {
      return;
    }
    for (const key2 of Object.keys(pageResponse.props)) {
      if (page.hasBaseline(key2)) {
        page.updateBaseline(key2, pageResponse.props[key2]);
        pageResponse.props[key2] = page.get().props[key2];
      }
    }
  }
  preserveEqualProps(pageResponse) {
    if (pageResponse.component !== page.get().component) {
      return;
    }
    const currentPageProps = page.get().props;
    Object.entries(pageResponse.props).forEach(([key2, value]) => {
      if (isEqual(value, currentPageProps[key2])) {
        pageResponse.props[key2] = currentPageProps[key2];
      }
    });
  }
  mergeProps(pageResponse) {
    if (!this.requestParams.isPartial() || pageResponse.component !== page.get().component) {
      return;
    }
    const propsToAppend = pageResponse.mergeProps || [];
    const propsToPrepend = pageResponse.prependProps || [];
    const propsToDeepMerge = pageResponse.deepMergeProps || [];
    const matchPropsOn = pageResponse.matchPropsOn || [];
    const mergeProp = (prop, shouldAppend) => {
      const currentProp = get(page.get().props, prop);
      const incomingProp = get(pageResponse.props, prop);
      if (Array.isArray(incomingProp)) {
        const newArray = this.mergeOrMatchItems(
          currentProp || [],
          incomingProp,
          prop,
          matchPropsOn,
          shouldAppend
        );
        set(pageResponse.props, prop, newArray);
      } else if (typeof incomingProp === "object" && incomingProp !== null) {
        const newObject = {
          ...currentProp || {},
          ...incomingProp
        };
        set(pageResponse.props, prop, newObject);
      }
    };
    propsToAppend.forEach((prop) => mergeProp(prop, true));
    propsToPrepend.forEach((prop) => mergeProp(prop, false));
    propsToDeepMerge.forEach((prop) => {
      const currentProp = get(page.get().props, prop);
      const incomingProp = get(pageResponse.props, prop);
      const deepMerge = (target, source, matchProp) => {
        if (Array.isArray(source)) {
          return this.mergeOrMatchItems(target, source, matchProp, matchPropsOn);
        }
        if (typeof source === "object" && source !== null) {
          return Object.keys(source).reduce(
            (acc, key2) => {
              acc[key2] = deepMerge(target ? target[key2] : void 0, source[key2], `${matchProp}.${key2}`);
              return acc;
            },
            { ...target }
          );
        }
        return source;
      };
      set(pageResponse.props, prop, deepMerge(currentProp, incomingProp, prop));
    });
    const nestedTopKeys = new Set(
      [...this.requestParams.all().only, ...this.requestParams.all().except].filter((prop) => prop.includes(".")).map((prop) => prop.split(".")[0])
    );
    for (const key2 of nestedTopKeys) {
      const currentValue = page.get().props[key2];
      if (this.isObject(currentValue) && this.isObject(pageResponse.props[key2])) {
        pageResponse.props[key2] = this.deepMergeObjects(currentValue, pageResponse.props[key2]);
      }
    }
    pageResponse.props = { ...page.get().props, ...pageResponse.props };
    if (this.shouldPreserveErrors(pageResponse)) {
      pageResponse.props.errors = page.get().props.errors;
    }
    if (page.get().scrollProps) {
      pageResponse.scrollProps = {
        ...page.get().scrollProps || {},
        ...pageResponse.scrollProps || {}
      };
    }
    if (page.hasOnceProps()) {
      pageResponse.onceProps = {
        ...page.get().onceProps || {},
        ...pageResponse.onceProps || {}
      };
    }
    if (this.requestParams.isDeferredPropsRequest()) {
      pageResponse.flash = { ...page.get().flash };
    }
    const currentOriginalDeferred = page.get().initialDeferredProps;
    if (currentOriginalDeferred && Object.keys(currentOriginalDeferred).length > 0) {
      pageResponse.initialDeferredProps = currentOriginalDeferred;
    }
    pageResponse.rescuedProps = this.mergeRescuedProps(pageResponse);
  }
  mergeRescuedProps(pageResponse) {
    const currentRescued = page.get().rescuedProps ?? [];
    const incomingRescued = pageResponse.rescuedProps ?? [];
    const newRescued = new Set(
      currentRescued.filter((prop) => !partialReloadRequestsProp(this.requestParams.all(), prop))
    );
    incomingRescued.forEach((prop) => newRescued.add(prop));
    return Array.from(newRescued);
  }
  /**
   * By default, the Laravel adapter shares validation errors via Inertia::always(),
   * so responses always include errors, even when empty. Components like
   * InfiniteScroll and WhenVisible, as well as loading deferred props,
   * perform async requests that should practically never reset errors.
   */
  shouldPreserveErrors(pageResponse) {
    if (!this.requestParams.all().preserveErrors) {
      return false;
    }
    const currentErrors = page.get().props.errors;
    if (!currentErrors || Object.keys(currentErrors).length === 0) {
      return false;
    }
    const responseErrors = pageResponse.props.errors;
    if (responseErrors && Object.keys(responseErrors).length > 0) {
      return false;
    }
    return true;
  }
  isObject(item) {
    return item && typeof item === "object" && !Array.isArray(item);
  }
  deepMergeObjects(target, source) {
    const result2 = { ...target };
    for (const key2 of Object.keys(source)) {
      const targetValue = target[key2];
      const sourceValue = source[key2];
      if (this.isObject(targetValue) && this.isObject(sourceValue)) {
        result2[key2] = this.deepMergeObjects(targetValue, sourceValue);
      } else {
        result2[key2] = sourceValue;
      }
    }
    return result2;
  }
  mergeOrMatchItems(existingItems, newItems, matchProp, matchPropsOn, shouldAppend = true) {
    const items = Array.isArray(existingItems) ? existingItems : [];
    const matchingKey = matchPropsOn.find((key2) => {
      const keyPath = key2.split(".").slice(0, -1).join(".");
      return keyPath === matchProp;
    });
    if (!matchingKey) {
      return shouldAppend ? [...items, ...newItems] : [...newItems, ...items];
    }
    const uniqueProperty = matchingKey.split(".").pop() || "";
    const newItemsMap = /* @__PURE__ */ new Map();
    newItems.forEach((item) => {
      if (this.hasUniqueProperty(item, uniqueProperty)) {
        newItemsMap.set(item[uniqueProperty], item);
      }
    });
    return shouldAppend ? this.appendWithMatching(items, newItems, newItemsMap, uniqueProperty) : this.prependWithMatching(items, newItems, newItemsMap, uniqueProperty);
  }
  appendWithMatching(existingItems, newItems, newItemsMap, uniqueProperty) {
    const updatedExisting = existingItems.map((item) => {
      if (this.hasUniqueProperty(item, uniqueProperty) && newItemsMap.has(item[uniqueProperty])) {
        return newItemsMap.get(item[uniqueProperty]);
      }
      return item;
    });
    const newItemsToAdd = newItems.filter((item) => {
      if (!this.hasUniqueProperty(item, uniqueProperty)) {
        return true;
      }
      return !existingItems.some(
        (existing) => this.hasUniqueProperty(existing, uniqueProperty) && existing[uniqueProperty] === item[uniqueProperty]
      );
    });
    return [...updatedExisting, ...newItemsToAdd];
  }
  prependWithMatching(existingItems, newItems, newItemsMap, uniqueProperty) {
    const untouchedExisting = existingItems.filter((item) => {
      if (this.hasUniqueProperty(item, uniqueProperty)) {
        return !newItemsMap.has(item[uniqueProperty]);
      }
      return true;
    });
    return [...newItems, ...untouchedExisting];
  }
  hasUniqueProperty(item, property2) {
    return item && typeof item === "object" && property2 in item;
  }
  async setRememberedState(pageResponse) {
    const rememberedState = await history.getState(history.rememberedState, {});
    if (this.requestParams.all().preserveState && rememberedState && pageResponse.component === page.get().component) {
      pageResponse.rememberedState = rememberedState;
    }
  }
  getScopedErrors(errors) {
    if (!this.requestParams.all().errorBag) {
      return errors;
    }
    return errors[this.requestParams.all().errorBag || ""] || {};
  }
};
var Request = class _Request {
  constructor(params, page22, { optimistic = false } = {}) {
    this.page = page22;
    this.requestParams = RequestParams.create(params);
    this.cancelToken = new AbortController();
    this.optimistic = optimistic;
  }
  response;
  cancelToken;
  requestParams;
  requestHasFinished = false;
  optimistic;
  static create(params, page22, options) {
    return new _Request(params, page22, options);
  }
  isPrefetch() {
    return this.requestParams.isPrefetch();
  }
  isOptimistic() {
    return this.optimistic;
  }
  isPendingOptimistic() {
    return this.isOptimistic() && (!this.response || !this.response.isProcessed());
  }
  async send() {
    this.requestParams.onCancelToken(() => this.cancel({ cancelled: true }));
    fireStartEvent(this.requestParams.all());
    this.requestParams.onStart();
    if (this.requestParams.all().prefetch) {
      this.requestParams.onPrefetching();
      firePrefetchingEvent(this.requestParams.all());
    }
    const originallyPrefetch = this.requestParams.all().prefetch;
    return http.getClient().request({
      method: this.requestParams.all().method,
      url: urlWithoutHash(this.requestParams.all().url).href,
      data: this.requestParams.data(),
      signal: this.cancelToken.signal,
      headers: this.getHeaders(),
      onUploadProgress: this.onProgress.bind(this)
    }).then((response) => {
      this.response = Response.create(this.requestParams, response, this.page);
      return this.response.handle();
    }).catch((error) => {
      if (error instanceof HttpResponseError2) {
        this.response = Response.create(this.requestParams, error.response, this.page);
        return this.response.handle();
      }
      return Promise.reject(error);
    }).catch((error) => {
      if (error instanceof HttpCancelledError2) {
        return;
      }
      if (this.requestParams.all().onNetworkError(error) === false) {
        return;
      }
      if (fireNetworkErrorEvent(error)) {
        if (originallyPrefetch) {
          this.requestParams.onPrefetchError(error);
        }
        return Promise.reject(error);
      }
    }).finally(() => {
      this.finish();
      if (originallyPrefetch && this.response) {
        this.requestParams.onPrefetchResponse(this.response);
      }
    });
  }
  finish() {
    if (this.requestParams.wasCancelledAtAll()) {
      return;
    }
    this.requestParams.markAsFinished();
    this.fireFinishEvents();
  }
  fireFinishEvents() {
    if (this.requestHasFinished) {
      return;
    }
    this.requestHasFinished = true;
    fireFinishEvent(this.requestParams.all());
    this.requestParams.onFinish();
  }
  cancel({ cancelled = false, interrupted = false }) {
    if (this.requestHasFinished) {
      return;
    }
    this.cancelToken.abort();
    this.requestParams.markAsCancelled({ cancelled, interrupted });
    this.fireFinishEvents();
  }
  onProgress(progress3) {
    if (this.requestParams.data() instanceof FormData) {
      fireProgressEvent(progress3);
      this.requestParams.all().onProgress(progress3);
    }
  }
  getHeaders() {
    const headers = {
      ...this.requestParams.headers(),
      Accept: "text/html, application/xhtml+xml",
      "X-Requested-With": "XMLHttpRequest",
      "X-Inertia": true
    };
    const page22 = page.get();
    if (page22.version) {
      headers["X-Inertia-Version"] = page22.version;
    }
    const onceProps = Object.entries(page22.onceProps || {}).filter(([, onceProp]) => {
      if (get(page22.props, onceProp.prop) === void 0) {
        return false;
      }
      return !onceProp.expiresAt || onceProp.expiresAt > Date.now();
    }).map(([key2]) => key2);
    if (onceProps.length > 0) {
      headers["X-Inertia-Except-Once-Props"] = onceProps.join(",");
    }
    return headers;
  }
};
var RequestStream = class {
  requests = [];
  maxConcurrent;
  interruptible;
  constructor({ maxConcurrent, interruptible }) {
    this.maxConcurrent = maxConcurrent;
    this.interruptible = interruptible;
  }
  send(request2) {
    this.requests.push(request2);
    request2.send().finally(() => {
      this.requests = this.requests.filter((r) => r !== request2);
    });
  }
  interruptInFlight() {
    this.cancel({ interrupted: true }, false);
  }
  cancelInFlight({ prefetch = true, optimistic = true } = {}) {
    this.requests.filter((request2) => prefetch || !request2.isPrefetch()).filter((request2) => optimistic || !request2.isOptimistic()).forEach((request2) => request2.cancel({ cancelled: true }));
  }
  cancel({ cancelled = false, interrupted = false } = {}, force = false) {
    if (!force && !this.shouldCancel()) {
      return;
    }
    const request2 = this.requests.shift();
    request2?.cancel({ cancelled, interrupted });
  }
  shouldCancel() {
    return this.interruptible && this.requests.length >= this.maxConcurrent;
  }
  hasPendingOptimistic() {
    return this.requests.some((request2) => request2.isPendingOptimistic());
  }
};
var noop3 = () => {
};
var Router = class {
  syncRequestStream = new RequestStream({
    maxConcurrent: 1,
    interruptible: true
  });
  asyncRequestStream = new RequestStream({
    maxConcurrent: Infinity,
    interruptible: false
  });
  clientVisitQueue = new Queue();
  pendingOptimisticCallback = void 0;
  init({
    initialPage,
    resolveComponent,
    swapComponent,
    onFlash
  }) {
    page.init({
      initialPage,
      resolveComponent,
      swapComponent,
      onFlash
    });
    InitialVisit.handle();
    eventHandler.init();
    eventHandler.on("missingHistoryItem", () => {
      if (typeof window !== "undefined") {
        this.visit(window.location.href, { preserveState: true, preserveScroll: true, replace: true });
      }
    });
    eventHandler.on("loadDeferredProps", (deferredProps) => {
      this.loadDeferredProps(deferredProps);
    });
    eventHandler.on("historyQuotaExceeded", (url) => {
      window.location.href = url;
    });
  }
  optimistic(callback) {
    this.pendingOptimisticCallback = callback;
    return this;
  }
  get(url, data = {}, options = {}) {
    return this.visit(url, { ...options, method: "get", data });
  }
  post(url, data = {}, options = {}) {
    return this.visit(url, { preserveState: true, ...options, method: "post", data });
  }
  put(url, data = {}, options = {}) {
    return this.visit(url, { preserveState: true, ...options, method: "put", data });
  }
  patch(url, data = {}, options = {}) {
    return this.visit(url, { preserveState: true, ...options, method: "patch", data });
  }
  delete(url, options = {}) {
    return this.visit(url, { preserveState: true, ...options, method: "delete" });
  }
  reload(options = {}) {
    return this.doReload(options);
  }
  doReload(options = {}) {
    if (typeof window === "undefined") {
      return;
    }
    return this.visit(window.location.href, {
      ...options,
      preserveScroll: true,
      preserveState: true,
      async: true,
      headers: {
        ...options.headers || {},
        "Cache-Control": "no-cache"
      }
    });
  }
  remember(data, key2 = "default") {
    history.remember(data, key2);
  }
  restore(key2 = "default") {
    return history.restore(key2);
  }
  on(type, callback) {
    if (typeof window === "undefined") {
      return () => {
      };
    }
    return eventHandler.onGlobalEvent(type, callback);
  }
  once(type, callback) {
    if (typeof window === "undefined") {
      return () => {
      };
    }
    const remove22 = this.on(type, (event) => {
      remove22();
      return callback(event);
    });
    return remove22;
  }
  hasPendingOptimistic() {
    return this.asyncRequestStream.hasPendingOptimistic();
  }
  get activePolls() {
    return polls.count;
  }
  cancelAll({ async = true, prefetch = true, sync = true } = {}) {
    if (async) {
      this.asyncRequestStream.cancelInFlight({ prefetch });
    }
    if (sync) {
      this.syncRequestStream.cancelInFlight();
    }
  }
  poll(interval, requestOptions = {}, options = {}) {
    return polls.add(
      interval,
      ({ onStart, onFinish }) => {
        const resolved = typeof requestOptions === "function" ? requestOptions() : requestOptions;
        this.reload({
          preserveErrors: true,
          ...resolved,
          onCancelToken: (token) => {
            onStart(token.cancel);
            resolved.onCancelToken?.(token);
          },
          onFinish: (visit) => {
            onFinish();
            resolved.onFinish?.(visit);
          }
        });
      },
      {
        autoStart: options.autoStart ?? true,
        keepAlive: options.keepAlive ?? false,
        mode: options.mode
      }
    );
  }
  visit(href, options = {}) {
    options.optimistic = options.optimistic ?? this.pendingOptimisticCallback;
    this.pendingOptimisticCallback = void 0;
    if (options.optimistic) {
      options.async = options.async ?? true;
    }
    const visit = this.getPendingVisit(href, {
      ...options,
      showProgress: options.showProgress ?? (!options.async || !!options.optimistic)
    });
    const events = this.getVisitEvents(options);
    if (events.onBefore(visit) === false || !fireBeforeEvent(visit)) {
      return;
    }
    const currentPageUrl = hrefToUrl(page.get().url);
    const isPartialReload = visit.only.length > 0 || visit.except.length > 0 || visit.reset.length > 0;
    const isSamePage = isPartialReload ? isSameUrlWithoutQueryOrHash(visit.url, currentPageUrl) : isSameUrlWithoutHash(visit.url, currentPageUrl);
    if (!isSamePage) {
      this.asyncRequestStream.cancelInFlight({ prefetch: false, optimistic: false });
    }
    if (!visit.async) {
      this.syncRequestStream.interruptInFlight();
    }
    if (options.optimistic) {
      this.applyOptimisticUpdate(options.optimistic, events);
    }
    if (!page.isCleared() && !visit.preserveUrl) {
      Scroll.save();
    }
    const requestParams = {
      ...visit,
      ...events
    };
    const sendRequest = () => {
      const prefetched = prefetchedRequests.get(requestParams);
      if (prefetched) {
        progress.reveal(prefetched.inFlight);
        prefetchedRequests.use(prefetched, requestParams);
      } else {
        progress.reveal(true);
        const requestStream = visit.async ? this.asyncRequestStream : this.syncRequestStream;
        requestStream.send(Request.create(requestParams, page.get(), { optimistic: !!options.optimistic }));
      }
    };
    if (Array.isArray(visit.component)) {
      console.error(
        `The "component" prop received an array of components (${visit.component.join(", ")}), but only a single component string is supported for instant visits. Pass an explicit component name instead.`
      );
      visit.component = null;
    }
    if (visit.component) {
      history.processQueue().then(() => {
        this.performInstantSwap(visit).then(() => {
          requestParams.preserveState = true;
          requestParams.replace = true;
          requestParams.viewTransition = false;
          sendRequest();
        });
      });
    } else {
      sendRequest();
    }
  }
  getCached(href, options = {}) {
    return prefetchedRequests.findCached(this.getPrefetchParams(href, options));
  }
  flush(href, options = {}) {
    prefetchedRequests.remove(this.getPrefetchParams(href, options));
  }
  flushAll() {
    prefetchedRequests.removeAll();
  }
  flushByCacheTags(tags) {
    prefetchedRequests.removeByTags(Array.isArray(tags) ? tags : [tags]);
  }
  getPrefetching(href, options = {}) {
    return prefetchedRequests.findInFlight(this.getPrefetchParams(href, options));
  }
  prefetch(href, options = {}, prefetchOptions = {}) {
    const method2 = options.method ?? (isUrlMethodPair(href) ? href.method : "get");
    if (method2 !== "get") {
      throw new Error("Prefetch requests must use the GET method");
    }
    const visit = this.getPendingVisit(href, {
      ...options,
      async: true,
      showProgress: false,
      prefetch: true,
      viewTransition: false
    });
    const visitUrl = visit.url.origin + visit.url.pathname + visit.url.search;
    const currentUrl = window.location.origin + window.location.pathname + window.location.search;
    if (visitUrl === currentUrl) {
      return;
    }
    const events = this.getVisitEvents(options);
    if (events.onBefore(visit) === false || !fireBeforeEvent(visit)) {
      return;
    }
    progress.hide();
    this.asyncRequestStream.interruptInFlight();
    const requestParams = {
      ...visit,
      ...events
    };
    const ensureCurrentPageIsSet = () => {
      return new Promise((resolve) => {
        const checkIfPageIsDefined = () => {
          if (page.get()) {
            resolve();
          } else {
            setTimeout(checkIfPageIsDefined, 50);
          }
        };
        checkIfPageIsDefined();
      });
    };
    ensureCurrentPageIsSet().then(() => {
      prefetchedRequests.add(
        requestParams,
        (params) => {
          this.asyncRequestStream.send(Request.create(params, page.get()));
        },
        {
          cacheFor: config.get("prefetch.cacheFor"),
          cacheTags: [],
          ...prefetchOptions
        }
      );
    });
  }
  clearHistory() {
    history.clear();
  }
  decryptHistory() {
    return history.decrypt();
  }
  resolveComponent(component2, page22) {
    return page.resolve(component2, page22);
  }
  replace(params) {
    this.clientVisit(params, { replace: true });
  }
  replaceProp(name, value, options) {
    this.replace({
      preserveScroll: true,
      preserveState: true,
      props(currentProps) {
        const newValue = typeof value === "function" ? value(get(currentProps, name), currentProps) : value;
        return set(cloneDeep(currentProps), name, newValue);
      },
      ...options || {}
    });
  }
  appendToProp(name, value, options) {
    this.replaceProp(
      name,
      (currentValue, currentProps) => {
        const newValue = typeof value === "function" ? value(currentValue, currentProps) : value;
        if (!Array.isArray(currentValue)) {
          currentValue = currentValue !== void 0 ? [currentValue] : [];
        }
        return [...currentValue, newValue];
      },
      options
    );
  }
  prependToProp(name, value, options) {
    this.replaceProp(
      name,
      (currentValue, currentProps) => {
        const newValue = typeof value === "function" ? value(currentValue, currentProps) : value;
        if (!Array.isArray(currentValue)) {
          currentValue = currentValue !== void 0 ? [currentValue] : [];
        }
        return [newValue, ...currentValue];
      },
      options
    );
  }
  push(params) {
    this.clientVisit(params);
  }
  flash(keyOrData, value) {
    const current = page.get().flash;
    let flash;
    if (typeof keyOrData === "function") {
      flash = keyOrData(current);
    } else if (typeof keyOrData === "string") {
      flash = { ...current, [keyOrData]: value };
    } else if (keyOrData && Object.keys(keyOrData).length) {
      flash = { ...current, ...keyOrData };
    } else {
      return;
    }
    page.setFlash(flash);
    if (Object.keys(flash).length) {
      fireFlashEvent(flash);
    }
  }
  clientVisit(params, { replace: replace2 = false } = {}) {
    this.clientVisitQueue.add(() => this.performClientVisit(params, { replace: replace2 }));
  }
  performClientVisit(params, { replace: replace2 = false } = {}) {
    const current = page.get();
    const onceProps = typeof params.props === "function" ? Object.fromEntries(
      Object.values(current.onceProps ?? {}).map((onceProp) => [
        onceProp.prop,
        get(current.props, onceProp.prop)
      ])
    ) : {};
    const props = typeof params.props === "function" ? params.props(current.props, onceProps) : params.props ?? current.props;
    const flash = typeof params.flash === "function" ? params.flash(current.flash) : params.flash;
    const { viewTransition, onError, onFinish, onFlash, onSuccess, ...pageParams } = params;
    const page22 = {
      ...current,
      ...pageParams,
      flash: flash ?? {},
      props
    };
    const preserveScroll = RequestParams.resolvePreserveOption(params.preserveScroll ?? false, page22);
    const preserveState = RequestParams.resolvePreserveOption(params.preserveState ?? false, page22);
    return page.set(page22, {
      replace: replace2,
      preserveScroll,
      preserveState,
      viewTransition
    }).then(() => {
      const currentFlash = page.get().flash;
      if (Object.keys(currentFlash).length > 0) {
        fireFlashEvent(currentFlash);
        onFlash?.(currentFlash);
      }
      const errors = page.get().props.errors || {};
      if (Object.keys(errors).length === 0) {
        onSuccess?.(page.get());
        return;
      }
      const scopedErrors = params.errorBag ? errors[params.errorBag || ""] || {} : errors;
      onError?.(scopedErrors);
    }).finally(() => onFinish?.(params));
  }
  performInstantSwap(visit) {
    const current = page.get();
    const sharedProps = Object.fromEntries(
      (current.sharedProps ?? []).filter((key2) => key2 in current.props).map((key2) => [key2, current.props[key2]])
    );
    const resolvedPageProps = typeof visit.pageProps === "function" ? visit.pageProps(cloneDeep(current.props), cloneDeep(sharedProps)) : visit.pageProps;
    const intermediateProps = resolvedPageProps !== null ? { ...resolvedPageProps } : { ...sharedProps };
    const intermediatePage = {
      component: visit.component,
      url: visit.url.pathname + visit.url.search + visit.url.hash,
      version: current.version,
      props: {
        ...intermediateProps,
        errors: {}
      },
      flash: {},
      rescuedProps: [],
      clearHistory: false,
      encryptHistory: current.encryptHistory,
      sharedProps: current.sharedProps,
      rememberedState: {}
    };
    return page.set(intermediatePage, {
      replace: visit.replace,
      preserveScroll: RequestParams.resolvePreserveOption(visit.preserveScroll, intermediatePage),
      preserveState: false,
      viewTransition: visit.viewTransition
    });
  }
  getPrefetchParams(href, options) {
    return {
      ...this.getPendingVisit(href, {
        ...options,
        async: true,
        showProgress: false,
        prefetch: true,
        viewTransition: false
      }),
      ...this.getVisitEvents(options)
    };
  }
  getPendingVisit(href, options) {
    if (isUrlMethodPair(href)) {
      const urlMethodPair = href;
      href = urlMethodPair.url;
      options.method = options.method ?? urlMethodPair.method;
    }
    const defaultVisitOptionsCallback = config.get("visitOptions");
    const configuredOptions = defaultVisitOptionsCallback ? defaultVisitOptionsCallback(href.toString(), cloneDeep(options)) || {} : {};
    const mergedOptions = {
      method: "get",
      data: {},
      replace: false,
      preserveScroll: false,
      preserveState: false,
      only: [],
      except: [],
      headers: {},
      errorBag: "",
      forceFormData: false,
      queryStringArrayFormat: "brackets",
      async: false,
      showProgress: true,
      fresh: false,
      reset: [],
      preserveUrl: false,
      preserveErrors: false,
      prefetch: false,
      invalidateCacheTags: [],
      viewTransition: false,
      component: null,
      pageProps: null,
      ...stripTopLevelUndefined(options),
      ...stripTopLevelUndefined(configuredOptions)
    };
    const [url, _data] = transformUrlAndData(
      href,
      mergedOptions.data,
      mergedOptions.method,
      mergedOptions.forceFormData,
      mergedOptions.queryStringArrayFormat
    );
    const visit = {
      cancelled: false,
      completed: false,
      interrupted: false,
      ...mergedOptions,
      url,
      data: _data
    };
    if (visit.prefetch) {
      visit.headers["Purpose"] = "prefetch";
    }
    return visit;
  }
  getVisitEvents(options) {
    return {
      onCancelToken: options.onCancelToken || noop3,
      onBefore: options.onBefore || noop3,
      onBeforeUpdate: options.onBeforeUpdate || noop3,
      onStart: options.onStart || noop3,
      onProgress: options.onProgress || noop3,
      onFinish: options.onFinish || noop3,
      onCancel: options.onCancel || noop3,
      onSuccess: options.onSuccess || noop3,
      onError: options.onError || noop3,
      onHttpException: options.onHttpException || noop3,
      onNetworkError: options.onNetworkError || noop3,
      onFlash: options.onFlash || noop3,
      onPrefetched: options.onPrefetched || noop3,
      onPrefetching: options.onPrefetching || noop3
    };
  }
  applyOptimisticUpdate(optimistic, events) {
    const currentProps = page.get().props;
    const optimisticProps = optimistic(cloneDeep(currentProps));
    if (!optimisticProps) {
      return;
    }
    const changedKeys = [];
    for (const key2 of Object.keys(optimisticProps)) {
      if (!isEqual(currentProps[key2], optimisticProps[key2])) {
        changedKeys.push(key2);
      }
    }
    if (changedKeys.length === 0) {
      return;
    }
    const id = page.nextOptimisticId();
    const component2 = page.get().component;
    for (const key2 of changedKeys) {
      page.setBaseline(key2, cloneDeep(currentProps[key2]));
    }
    page.registerOptimistic(id, optimistic);
    page.setPropsQuietly({ ...currentProps, ...optimisticProps });
    let shouldRestore = true;
    const originalOnSuccess = events.onSuccess;
    events.onSuccess = (page22) => {
      shouldRestore = false;
      return originalOnSuccess(page22);
    };
    const originalOnFinish = events.onFinish;
    events.onFinish = (visit) => {
      page.unregisterOptimistic(id);
      if (shouldRestore && page.get().component === component2) {
        const replayedProps = page.replayOptimistics();
        if (Object.keys(replayedProps).length > 0) {
          page.setPropsQuietly({ ...page.get().props, ...replayedProps });
        }
      }
      if (page.pendingOptimisticCount() === 0) {
        page.clearOptimisticState();
      }
      return originalOnFinish(visit);
    };
  }
  loadDeferredProps(deferred) {
    if (deferred) {
      Object.values(deferred).forEach((props) => {
        this.doReload({ only: props, deferredProps: true, preserveErrors: true });
      });
    }
  }
};
var UseFormUtils = class {
  /**
   * Creates a callback that returns a UrlMethodPair.
   *
   * createWayfinderCallback(urlMethodPair)
   * createWayfinderCallback(method, url)
   * createWayfinderCallback(() => urlMethodPair)
   * createWayfinderCallback(() => method, () => url)
   */
  static createWayfinderCallback(...args) {
    return () => {
      if (args.length === 1) {
        return isUrlMethodPair(args[0]) ? args[0] : args[0]();
      }
      return {
        method: typeof args[0] === "function" ? args[0]() : args[0],
        url: typeof args[1] === "function" ? args[1]() : args[1]
      };
    };
  }
  /**
   * Parses all useForm() arguments into { rememberKey, data, precognitionEndpoint }.
   *
   * useForm()
   * useForm(data)
   * useForm(rememberKey, data)
   * useForm(method, url, data)
   * useForm(urlMethodPair, data)
   *
   */
  static parseUseFormArguments(...args) {
    if (args.length === 0) {
      return {
        rememberKey: null,
        data: {},
        precognitionEndpoint: null
      };
    }
    if (args.length === 1) {
      return {
        rememberKey: null,
        data: args[0],
        precognitionEndpoint: null
      };
    }
    if (args.length === 2) {
      if (typeof args[0] === "string") {
        return {
          rememberKey: args[0],
          data: args[1],
          precognitionEndpoint: null
        };
      }
      return {
        rememberKey: null,
        data: args[1],
        precognitionEndpoint: this.createWayfinderCallback(args[0])
      };
    }
    return {
      rememberKey: null,
      data: args[2],
      precognitionEndpoint: this.createWayfinderCallback(args[0], args[1])
    };
  }
  /**
   * Parses all submission arguments into { method, url, options }.
   * It uses the Precognition endpoint if no explicit method/url are provided.
   *
   * form.submit(method, url)
   * form.submit(method, url, options)
   * form.submit(urlMethodPair)
   * form.submit(urlMethodPair, options)
   * form.submit()
   * form.submit(options)
   */
  static parseSubmitArguments(args, precognitionEndpoint) {
    if (args.length === 3 || args.length === 2 && typeof args[0] === "string") {
      return { method: args[0], url: args[1], options: args[2] ?? {} };
    }
    if (isUrlMethodPair(args[0])) {
      return { ...args[0], options: args[1] ?? {} };
    }
    return { ...precognitionEndpoint(), options: args[0] ?? {} };
  }
  /**
   * Merges headers into the Precognition validate() arguments.
   */
  static mergeHeadersForValidation(field, config22, headers) {
    const merge3 = (config3) => {
      config3.headers = {
        ...headers ?? {},
        ...config3.headers ?? {}
      };
      return config3;
    };
    if (field && typeof field === "object" && !("target" in field)) {
      field = merge3(field);
    } else if (config22 && typeof config22 === "object") {
      config22 = merge3(config22);
    } else if (typeof field === "string") {
      config22 = merge3(config22 ?? {});
    } else {
      field = merge3(field ?? {});
    }
    return [field, config22];
  }
};
function undotKey(key2) {
  if (!key2.includes(".")) {
    return key2;
  }
  const transformSegment = (segment) => {
    if (segment.startsWith("[") && segment.endsWith("]")) {
      return segment;
    }
    return segment.split(".").reduce((result2, part, index) => index === 0 ? part : `${result2}[${part}]`);
  };
  return key2.replace(/\\\./g, "__ESCAPED_DOT__").split(/(\[[^\]]*\])/).filter(Boolean).map(transformSegment).join("").replace(/__ESCAPED_DOT__/g, ".");
}
function parseKey2(key2) {
  const path = [];
  const pattern = /([^\[\]]+)|\[(\d*)\]/g;
  let match;
  while ((match = pattern.exec(key2)) !== null) {
    if (match[1] !== void 0) {
      path.push(match[1]);
    } else if (match[2] !== void 0) {
      path.push(match[2] === "" ? "" : Number(match[2]));
    }
  }
  return path;
}
function setNestedObject(obj, path, value) {
  let current = obj;
  for (let i = 0; i < path.length - 1; i++) {
    if (!(path[i] in current)) {
      current[path[i]] = {};
    }
    current = current[path[i]];
  }
  current[path[path.length - 1]] = value;
}
function objectHasSequentialNumericKeys(value) {
  const keys2 = Object.keys(value);
  const numericKeys = keys2.filter((k) => /^\d+$/.test(k)).map(Number).sort((a, b) => a - b);
  return keys2.length === numericKeys.length && numericKeys.length > 0 && numericKeys[0] === 0 && numericKeys.every((n, i) => n === i);
}
function convertSequentialObjectsToArrays(value) {
  if (Array.isArray(value)) {
    return value.map(convertSequentialObjectsToArrays);
  }
  if (typeof value !== "object" || value === null || isFile3(value)) {
    return value;
  }
  if (objectHasSequentialNumericKeys(value)) {
    const result22 = [];
    for (let i = 0; i < Object.keys(value).length; i++) {
      result22[i] = convertSequentialObjectsToArrays(value[i]);
    }
    return result22;
  }
  const result2 = {};
  for (const key2 in value) {
    result2[key2] = convertSequentialObjectsToArrays(value[key2]);
  }
  return result2;
}
function formDataToObject(source) {
  const form = {};
  for (const [key2, value] of source.entries()) {
    if (value instanceof File && value.size === 0 && value.name === "") {
      continue;
    }
    const path = parseKey2(undotKey(key2));
    if (path[path.length - 1] === "") {
      const arrayPath = path.slice(0, -1);
      const existing = get(form, arrayPath);
      if (Array.isArray(existing)) {
        existing.push(value);
      } else if (existing && typeof existing === "object" && !isFile3(existing)) {
        const numericKeys = Object.keys(existing).filter((k) => /^\d+$/.test(k)).map(Number).sort((a, b) => a - b);
        set(form, arrayPath, numericKeys.length > 0 ? [...numericKeys.map((k) => existing[k]), value] : [value]);
      } else {
        set(form, arrayPath, [value]);
      }
      continue;
    }
    setNestedObject(form, path.map(String), value);
  }
  return convertSequentialObjectsToArrays(form);
}
var Renderer = {
  buildDOMElement(tag) {
    const template2 = document.createElement("template");
    template2.innerHTML = tag;
    const node = template2.content.firstChild;
    if (!tag.startsWith("<script ")) {
      return node;
    }
    const script = document.createElement("script");
    script.innerHTML = node.innerHTML;
    node.getAttributeNames().forEach((name) => {
      script.setAttribute(name, node.getAttribute(name) || "");
    });
    return script;
  },
  isInertiaManagedElement(element) {
    return element.nodeType === Node.ELEMENT_NODE && element.getAttribute("data-inertia") !== null;
  },
  findMatchingElementIndex(element, elements) {
    const key2 = element.getAttribute("data-inertia");
    if (key2 !== null) {
      return elements.findIndex((element2) => element2.getAttribute("data-inertia") === key2);
    }
    return -1;
  },
  update: debounce3(function(elements) {
    const sourceElements = elements.map((element) => this.buildDOMElement(element));
    const targetElements = Array.from(document.head.childNodes).filter(
      (element) => this.isInertiaManagedElement(element)
    );
    if (sourceElements.some((element) => element instanceof HTMLTitleElement)) {
      document.head.querySelectorAll("title:not([data-inertia])").forEach((title) => title.remove());
    }
    targetElements.forEach((targetElement) => {
      const index = this.findMatchingElementIndex(targetElement, sourceElements);
      if (index === -1) {
        targetElement.remove();
        return;
      }
      const sourceElement = sourceElements.splice(index, 1)[0];
      if (sourceElement && !targetElement.isEqualNode(sourceElement)) {
        targetElement.replaceWith(sourceElement);
      }
    });
    sourceElements.forEach((element) => {
      document.head.appendChild(element);
    });
  }, 1)
};
function createHeadManager(isServer3, titleCallback, onUpdate) {
  const states = {};
  let lastProviderId = 0;
  function connect() {
    const id = lastProviderId += 1;
    states[id] = [];
    return id.toString();
  }
  function disconnect(id) {
    if (id === null || Object.keys(states).indexOf(id) === -1) {
      return;
    }
    delete states[id];
    commit();
  }
  function reconnect(id) {
    if (Object.keys(states).indexOf(id) === -1) {
      states[id] = [];
    }
  }
  function update2(id, elements = []) {
    if (id !== null && Object.keys(states).indexOf(id) > -1) {
      states[id] = elements;
    }
    commit();
  }
  function collect() {
    const title = titleCallback("");
    const defaults2 = {
      ...title ? { title: `<title data-inertia="">${title}</title>` } : {}
    };
    const elements = Object.values(states).reduce((carry, elements2) => carry.concat(elements2), []).reduce((carry, element) => {
      if (element.indexOf("<") === -1) {
        return carry;
      }
      if (element.indexOf("<title ") === 0) {
        const title2 = element.match(/(<title [^>]+>)(.*?)(<\/title>)/s);
        carry.title = title2 ? `${title2[1]}${titleCallback(title2[2])}${title2[3]}` : element;
        return carry;
      }
      const match = element.match(/ data-inertia="[^"]+"/);
      if (match) {
        carry[match[0]] = element;
      } else {
        carry[Object.keys(carry).length] = element;
      }
      return carry;
    }, defaults2);
    return Object.values(elements);
  }
  function commit() {
    isServer3 ? onUpdate(collect()) : Renderer.update(collect());
  }
  commit();
  return {
    forceUpdate: commit,
    createProvider: function() {
      const id = connect();
      return {
        reconnect: () => reconnect(id),
        update: (elements) => update2(id, elements),
        disconnect: () => disconnect(id)
      };
    }
  };
}
var MERGE_INTENT_HEADER = "X-Inertia-Infinite-Scroll-Merge-Intent";
var useInfiniteScrollData = (options) => {
  const getScrollPropFromCurrentPage = () => {
    const scrollProp = page.get().scrollProps?.[options.getPropName()];
    if (scrollProp) {
      return scrollProp;
    }
    throw new Error(`The page object does not contain a scroll prop named "${options.getPropName()}".`);
  };
  const state2 = {
    component: null,
    loading: false,
    previousPage: null,
    nextPage: null,
    lastLoadedPage: null,
    requestCount: 0
  };
  const resetState = () => {
    const scrollProp = getScrollPropFromCurrentPage();
    state2.component = page.get().component;
    state2.loading = false;
    state2.previousPage = scrollProp.previousPage;
    state2.nextPage = scrollProp.nextPage;
    state2.lastLoadedPage = scrollProp.currentPage;
    state2.requestCount = 0;
  };
  const getRememberKey = () => `inertia:infinite-scroll-data:${options.getPropName()}`;
  if (typeof window !== "undefined") {
    resetState();
    const rememberedState = router.restore(getRememberKey());
    if (rememberedState && typeof rememberedState === "object" && rememberedState.lastLoadedPage === getScrollPropFromCurrentPage().currentPage) {
      state2.previousPage = rememberedState.previousPage;
      state2.nextPage = rememberedState.nextPage;
      state2.lastLoadedPage = rememberedState.lastLoadedPage;
      state2.requestCount = rememberedState.requestCount || 0;
    }
  }
  const removeEventListener = router.on("success", (event) => {
    if (state2.component === event.detail.page.component && getScrollPropFromCurrentPage().reset) {
      resetState();
      options.onReset?.();
    }
  });
  const getScrollPropKeyForSide = (side) => {
    return side === "next" ? "nextPage" : "previousPage";
  };
  const findPageToLoad = (side) => {
    const pagePropName = getScrollPropKeyForSide(side);
    return state2[pagePropName];
  };
  const syncStateOnSuccess = (side) => {
    const scrollProp = getScrollPropFromCurrentPage();
    const paginationProp = getScrollPropKeyForSide(side);
    state2.lastLoadedPage = scrollProp.currentPage;
    state2[paginationProp] = scrollProp[paginationProp];
    state2.requestCount += 1;
    router.remember(
      {
        previousPage: state2.previousPage,
        nextPage: state2.nextPage,
        lastLoadedPage: state2.lastLoadedPage,
        requestCount: state2.requestCount
      },
      getRememberKey()
    );
  };
  const getPageName = () => getScrollPropFromCurrentPage().pageName;
  const getRequestCount = () => state2.requestCount;
  const fetchPage = (side, reloadOptions = {}) => {
    const page22 = findPageToLoad(side);
    if (state2.loading || page22 === null) {
      return;
    }
    state2.loading = true;
    router.reload({
      preserveErrors: true,
      ...reloadOptions,
      data: { ...reloadOptions.data || {}, [getPageName()]: page22 },
      only: [...reloadOptions.only || [], options.getPropName()],
      preserveUrl: true,
      // we handle URL updates manually via useInfiniteScrollQueryString()
      headers: {
        [MERGE_INTENT_HEADER]: side === "previous" ? "prepend" : "append",
        ...reloadOptions.headers
      },
      onBefore: (visit) => {
        side === "next" ? options.onBeforeNextRequest() : options.onBeforePreviousRequest();
        reloadOptions.onBefore?.(visit);
      },
      onBeforeUpdate: (page3) => {
        options.onBeforeUpdate();
        reloadOptions.onBeforeUpdate?.(page3);
      },
      onSuccess: (page3) => {
        syncStateOnSuccess(side);
        reloadOptions.onSuccess?.(page3);
      },
      onFinish: (visit) => {
        state2.loading = false;
        const completed = visit.completed;
        const page3 = completed ? state2.lastLoadedPage : null;
        side === "next" ? options.onCompleteNextRequest(page3, { page: page3, completed }) : options.onCompletePreviousRequest(page3, { page: page3, completed });
        reloadOptions.onFinish?.(visit);
      }
    });
  };
  const getLastLoadedPage = () => state2.lastLoadedPage;
  const hasPrevious = () => !!state2.previousPage;
  const hasNext = () => !!state2.nextPage;
  const fetchPrevious = (reloadOptions) => fetchPage("previous", reloadOptions);
  const fetchNext = (reloadOptions) => fetchPage("next", reloadOptions);
  return {
    getLastLoadedPage,
    getPageName,
    getRequestCount,
    hasPrevious,
    hasNext,
    fetchNext,
    fetchPrevious,
    removeEventListener
  };
};
var useIntersectionObservers = () => {
  const intersectionObservers = [];
  const newIntersectionObserver = (callback, options = {}) => {
    const observer = new IntersectionObserver((entries) => {
      for (const entry of entries) {
        if (entry.isIntersecting) {
          callback(entry);
        }
      }
    }, options);
    intersectionObservers.push(observer);
    return observer;
  };
  const flushAll = () => {
    intersectionObservers.forEach((observer) => observer.disconnect());
    intersectionObservers.length = 0;
  };
  return {
    new: newIntersectionObserver,
    flushAll
  };
};
var INFINITE_SCROLL_PAGE_KEY = "infiniteScrollPage";
var INFINITE_SCROLL_IGNORE_KEY = "infiniteScrollIgnore";
var getPageFromElement = (element) => element.dataset[INFINITE_SCROLL_PAGE_KEY];
var useInfiniteScrollElementManager = (options) => {
  const intersectionObservers = useIntersectionObservers();
  let itemsObserver;
  let startElementObserver;
  let endElementObserver;
  let itemsMutationObserver;
  let triggersEnabled = false;
  const setupObservers = () => {
    itemsMutationObserver = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        mutation.addedNodes.forEach((node) => {
          if (node.nodeType !== Node.ELEMENT_NODE) {
            return;
          }
          addedElements.add(node);
        });
      });
      rememberElementsDebounced();
    });
    itemsMutationObserver.observe(options.getItemsElement(), { childList: true });
    itemsObserver = intersectionObservers.new(
      (entry) => options.onItemIntersected(entry.target)
    );
    const observerOptions = {
      root: options.getScrollableParent(),
      rootMargin: `${Math.max(1, options.getTriggerMargin())}px`
    };
    startElementObserver = intersectionObservers.new(options.onPreviousTriggered, observerOptions);
    endElementObserver = intersectionObservers.new(options.onNextTriggered, observerOptions);
  };
  const enableTriggers = () => {
    if (triggersEnabled) {
      disableTriggers();
    }
    const startElement = options.getStartElement();
    const endElement = options.getEndElement();
    if (startElement && options.shouldFetchPrevious()) {
      startElementObserver.observe(startElement);
    }
    if (endElement && options.shouldFetchNext()) {
      endElementObserver.observe(endElement);
    }
    triggersEnabled = true;
  };
  const disableTriggers = () => {
    if (!triggersEnabled) {
      return;
    }
    startElementObserver.disconnect();
    endElementObserver.disconnect();
    triggersEnabled = false;
  };
  const refreshTriggers = () => {
    if (triggersEnabled) {
      enableTriggers();
    }
  };
  const flushAll = () => {
    disableTriggers();
    intersectionObservers.flushAll();
    itemsMutationObserver?.disconnect();
  };
  const addedElements = /* @__PURE__ */ new Set();
  const elementIsUntagged = (element) => !(INFINITE_SCROLL_PAGE_KEY in element.dataset) && !(INFINITE_SCROLL_IGNORE_KEY in element.dataset);
  const processManuallyAddedElements = () => {
    Array.from(addedElements).forEach((element) => {
      if (elementIsUntagged(element)) {
        element.dataset[INFINITE_SCROLL_IGNORE_KEY] = "true";
      }
      itemsObserver.observe(element);
    });
    addedElements.clear();
  };
  const findUntaggedElements = (containerElement) => {
    return Array.from(
      containerElement.querySelectorAll(
        `:scope > *:not([data-infinite-scroll-page]):not([data-infinite-scroll-ignore])`
      )
    );
  };
  let hasRestoredElements = false;
  const processServerLoadedElements = (loadedPage) => {
    if (!hasRestoredElements) {
      hasRestoredElements = true;
      if (restoreElements()) {
        return;
      }
    }
    findUntaggedElements(options.getItemsElement()).forEach((element) => {
      if (elementIsUntagged(element)) {
        element.dataset[INFINITE_SCROLL_PAGE_KEY] = loadedPage?.toString() || "1";
      }
      itemsObserver.observe(element);
    });
    rememberElements();
  };
  const getElementsRememberKey = () => `inertia:infinite-scroll-elements:${options.getPropName()}`;
  const rememberElements = () => {
    const pageElementRange = {};
    const childNodes = options.getItemsElement().childNodes;
    for (let index = 0; index < childNodes.length; index++) {
      const node = childNodes[index];
      if (node.nodeType !== Node.ELEMENT_NODE) {
        continue;
      }
      const page22 = getPageFromElement(node);
      if (typeof page22 === "undefined") {
        continue;
      }
      if (!(page22 in pageElementRange)) {
        pageElementRange[page22] = { from: index, to: index };
      } else {
        pageElementRange[page22].to = index;
      }
    }
    router.remember(pageElementRange, getElementsRememberKey());
  };
  const rememberElementsDebounced = debounce3(rememberElements, 250);
  const restoreElements = () => {
    const pageElementRange = router.restore(getElementsRememberKey());
    if (!pageElementRange || typeof pageElementRange !== "object") {
      return false;
    }
    const childNodes = options.getItemsElement().childNodes;
    for (let index = 0; index < childNodes.length; index++) {
      const node = childNodes[index];
      if (node.nodeType !== Node.ELEMENT_NODE) {
        continue;
      }
      const element = node;
      let elementPage;
      for (const [page22, range3] of Object.entries(pageElementRange)) {
        if (index >= range3.from && index <= range3.to) {
          elementPage = page22;
          break;
        }
      }
      if (elementPage) {
        element.dataset[INFINITE_SCROLL_PAGE_KEY] = elementPage;
      } else if (!elementIsUntagged(element)) {
        continue;
      } else {
        element.dataset[INFINITE_SCROLL_IGNORE_KEY] = "true";
      }
      itemsObserver.observe(element);
    }
    return true;
  };
  return {
    setupObservers,
    enableTriggers,
    disableTriggers,
    refreshTriggers,
    flushAll,
    processManuallyAddedElements,
    processServerLoadedElements
  };
};
var queue3 = new Queue();
var initialUrl;
var payloadUrl;
var initialUrlWasAbsolute = null;
var useInfiniteScrollQueryString = (options) => {
  let enabled = true;
  const queuePageUpdate = (page22) => {
    queue3.add(() => {
      return new Promise((resolve) => {
        if (!enabled) {
          initialUrl = payloadUrl = null;
          return resolve();
        }
        if (!initialUrl || !payloadUrl) {
          const currentPageUrl = page.get().url;
          initialUrl = hrefToUrl(currentPageUrl);
          payloadUrl = hrefToUrl(currentPageUrl);
          initialUrlWasAbsolute = urlHasProtocol(currentPageUrl);
        }
        const pageName = options.getPageName();
        const searchParams = payloadUrl.searchParams;
        if (page22 === "1") {
          searchParams.delete(pageName);
        } else {
          searchParams.set(pageName, page22);
        }
        setTimeout(() => resolve());
      });
    }).finally(() => {
      if (enabled && initialUrl && payloadUrl && initialUrl.href !== payloadUrl.href && initialUrlWasAbsolute !== null) {
        router.replace({
          url: urlToString(payloadUrl, initialUrlWasAbsolute),
          preserveScroll: true,
          preserveState: true
        });
      }
      initialUrl = payloadUrl = initialUrlWasAbsolute = null;
    });
  };
  const onItemIntersected = debounce3((itemElement) => {
    const itemsElement = options.getItemsElement();
    if (!enabled || options.shouldPreserveUrl() || !itemElement || !itemsElement) {
      return;
    }
    const pageMap = /* @__PURE__ */ new Map();
    const elements = [...itemsElement.children];
    getElementsInViewportFromCollection(elements, itemElement).forEach((element) => {
      const page22 = getPageFromElement(element) ?? "1";
      if (pageMap.has(page22)) {
        pageMap.set(page22, pageMap.get(page22) + 1);
      } else {
        pageMap.set(page22, 1);
      }
    });
    const sortedPages = Array.from(pageMap.entries()).sort((a, b) => b[1] - a[1]);
    const mostVisiblePage = sortedPages[0]?.[0];
    if (mostVisiblePage !== void 0) {
      queuePageUpdate(mostVisiblePage);
    }
  }, 250);
  return {
    onItemIntersected,
    cancel: () => enabled = false
  };
};
var useInfiniteScrollPreservation = (options) => {
  const createCallbacks = () => {
    let currentScrollTop;
    let referenceElement = null;
    let referenceElementTop = 0;
    const captureScrollPosition = () => {
      const scrollableContainer = options.getScrollableParent();
      const itemsElement = options.getItemsElement();
      currentScrollTop = scrollableContainer?.scrollTop || window.scrollY;
      const visibleElements = getElementsInViewportFromCollection([...itemsElement.children]);
      if (visibleElements.length > 0) {
        referenceElement = visibleElements[0];
        const containerRect = scrollableContainer?.getBoundingClientRect() || { top: 0 };
        const containerTop = scrollableContainer ? containerRect.top : 0;
        const rect = referenceElement.getBoundingClientRect();
        referenceElementTop = rect.top - containerTop;
      }
    };
    const restoreScrollPosition = () => {
      if (!referenceElement) {
        return;
      }
      let attempts = 0;
      let restored = false;
      const restore = () => {
        attempts++;
        if (restored || attempts > 10) {
          return false;
        }
        const scrollableContainer = options.getScrollableParent();
        const containerRect = scrollableContainer?.getBoundingClientRect() || { top: 0 };
        const containerTop = scrollableContainer ? containerRect.top : 0;
        const newRect = referenceElement.getBoundingClientRect();
        const newElementTop = newRect.top - containerTop;
        const adjustment = newElementTop - referenceElementTop;
        if (adjustment === 0) {
          window.requestAnimationFrame(restore);
          return;
        }
        if (scrollableContainer) {
          scrollableContainer.scrollTo({ top: currentScrollTop + adjustment });
        } else {
          window.scrollTo(0, window.scrollY + adjustment);
        }
        restored = true;
      };
      window.requestAnimationFrame(restore);
    };
    return {
      captureScrollPosition,
      restoreScrollPosition
    };
  };
  return {
    createCallbacks
  };
};
function useInfiniteScroll(options) {
  const queryStringManager = useInfiniteScrollQueryString({ ...options, getPageName: () => dataManager.getPageName() });
  const scrollPreservation = useInfiniteScrollPreservation(options);
  const elementManager = useInfiniteScrollElementManager({
    ...options,
    // As items enter viewport, update URL to reflect the most visible page
    onItemIntersected: queryStringManager.onItemIntersected,
    onPreviousTriggered: () => dataManager.fetchPrevious(),
    onNextTriggered: () => dataManager.fetchNext()
  });
  const dataManager = useInfiniteScrollData({
    ...options,
    // Before updating page data, tag any manually added DOM elements
    // so they don't get confused with server-loaded content
    onBeforeUpdate: elementManager.processManuallyAddedElements,
    // After successful request, tag new server content
    onCompletePreviousRequest: (_, details) => {
      options.onCompletePreviousRequest(details);
      if (details.completed) {
        requestAnimationFrame(() => elementManager.processServerLoadedElements(details.page), 2);
      }
    },
    onCompleteNextRequest: (_, details) => {
      options.onCompleteNextRequest(details);
      if (details.completed) {
        requestAnimationFrame(() => elementManager.processServerLoadedElements(details.page), 2);
      }
    },
    onReset: options.onDataReset
  });
  const addScrollPreservationCallbacks = (reloadOptions) => {
    const { captureScrollPosition, restoreScrollPosition } = scrollPreservation.createCallbacks();
    const originalOnBeforeUpdate = reloadOptions.onBeforeUpdate || (() => {
    });
    const originalOnSuccess = reloadOptions.onSuccess || (() => {
    });
    reloadOptions.onBeforeUpdate = (page22) => {
      originalOnBeforeUpdate(page22);
      captureScrollPosition();
    };
    reloadOptions.onSuccess = (page22) => {
      originalOnSuccess(page22);
      restoreScrollPosition();
    };
    return reloadOptions;
  };
  const originalFetchNext = dataManager.fetchNext;
  dataManager.fetchNext = (reloadOptions = {}) => {
    reloadOptions = { ...options.getReloadOptions?.(), ...reloadOptions };
    if (options.inReverseMode()) {
      reloadOptions = addScrollPreservationCallbacks(reloadOptions);
    }
    originalFetchNext(reloadOptions);
  };
  const originalFetchPrevious = dataManager.fetchPrevious;
  dataManager.fetchPrevious = (reloadOptions = {}) => {
    reloadOptions = { ...options.getReloadOptions?.(), ...reloadOptions };
    if (!options.inReverseMode()) {
      reloadOptions = addScrollPreservationCallbacks(reloadOptions);
    }
    originalFetchPrevious(reloadOptions);
  };
  const removeEventListener = router.on("success", () => requestAnimationFrame(elementManager.refreshTriggers, 2));
  return {
    dataManager,
    elementManager,
    flush: () => {
      removeEventListener();
      dataManager.removeEventListener();
      elementManager.flushAll();
      queryStringManager.cancel();
    }
  };
}
function createLayoutPropsStore() {
  let shared = {};
  let named = {};
  let snapshot = { shared, named };
  const listeners = /* @__PURE__ */ new Set();
  let pendingNotify = false;
  const updateSnapshot = () => {
    snapshot = { shared, named };
  };
  const notify = () => {
    if (pendingNotify) {
      return;
    }
    pendingNotify = true;
    queueMicrotask(() => {
      pendingNotify = false;
      listeners.forEach((fn) => fn());
    });
  };
  return {
    set(props) {
      const merged = { ...shared, ...props };
      if (isEqual(shared, merged)) {
        return;
      }
      shared = merged;
      updateSnapshot();
      notify();
    },
    setFor(name, props) {
      const current = named[name] || {};
      const merged = { ...current, ...props };
      if (isEqual(current, merged)) {
        return;
      }
      named = { ...named, [name]: merged };
      updateSnapshot();
      notify();
    },
    reset() {
      shared = {};
      named = {};
      updateSnapshot();
      notify();
    },
    subscribe(callback) {
      listeners.add(callback);
      return () => listeners.delete(callback);
    },
    get: () => snapshot
  };
}
function isPlainObject3(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function hasComponentKey(value) {
  return isPlainObject3(value) && "component" in value;
}
function hasComponentEntry(value, isComponent2) {
  return "component" in value && isComponent2(value.component);
}
function isNamedLayouts(value, isComponent2) {
  if (!isPlainObject3(value) || isComponent2(value) || hasComponentEntry(value, isComponent2)) {
    return false;
  }
  return Object.values(value).every(
    (v) => isComponent2(v) || Array.isArray(v) && isComponent2(v[0]) || hasComponentKey(v) && isComponent2(v.component)
  );
}
function isPropsObject(value, isComponent2) {
  return isPlainObject3(value) && !isComponent2(value) && !hasComponentEntry(value, isComponent2) && !isNamedLayouts(value, isComponent2);
}
function isPropsObjectOrCallback(value, isComponent2) {
  if (isPropsObject(value, isComponent2)) {
    return true;
  }
  if (!isPlainObject3(value) || isComponent2(value) || hasComponentEntry(value, isComponent2)) {
    return false;
  }
  const values2 = Object.values(value);
  return values2.length > 0 && values2.every((v) => typeof v === "function");
}
function isTuple(value, isComponent2) {
  return Array.isArray(value) && value.length === 2 && isComponent2(value[0]) && isPlainObject3(value[1]) && !isComponent2(value[1]);
}
function extract(item, isComponent2) {
  if (Array.isArray(item) && isComponent2(item[0])) {
    return { component: item[0], props: item[1] ?? {} };
  }
  if (hasComponentKey(item) && isComponent2(item.component)) {
    return { component: item.component, props: item.props ?? {} };
  }
  if (isComponent2(item)) {
    return { component: item, props: {} };
  }
  throw new Error(`Invalid layout definition: received ${typeof item}`);
}
function normalizeLayouts(layout2, isComponent2, isRenderFunction2) {
  if (!layout2 || isRenderFunction2 && isRenderFunction2(layout2)) {
    return [];
  }
  if (isNamedLayouts(layout2, isComponent2)) {
    return Object.entries(layout2).map(([name, value]) => ({ ...extract(value, isComponent2), name }));
  }
  if (isTuple(layout2, isComponent2)) {
    return [{ component: layout2[0], props: layout2[1] ?? {} }];
  }
  if (Array.isArray(layout2)) {
    return layout2.map((item) => extract(item, isComponent2));
  }
  if (hasComponentKey(layout2) && isComponent2(layout2.component)) {
    return [{ component: layout2.component, props: layout2.props ?? {} }];
  }
  if (isComponent2(layout2)) {
    return [{ component: layout2, props: {} }];
  }
  return [];
}
function isContentEditableOrPrevented(event) {
  return event.target instanceof HTMLElement && event.target.isContentEditable || event.defaultPrevented;
}
function shouldIntercept(event) {
  const isLink = event.currentTarget.tagName.toLowerCase() === "a";
  return !(isContentEditableOrPrevented(event) || isLink && event.altKey || isLink && event.ctrlKey || isLink && event.metaKey || isLink && event.shiftKey || isLink && "button" in event && event.button !== 0);
}
function shouldNavigate(event) {
  const isButton = event.currentTarget.tagName.toLowerCase() === "button";
  return !isContentEditableOrPrevented(event) && (event.key === "Enter" || isButton && event.key === " ");
}
var baseComponentSelector = "nprogress";
var usePopover;
var progress2;
var settings = {
  minimum: 0.08,
  easing: "linear",
  speed: 200,
  trickle: true,
  trickleSpeed: 200,
  showSpinner: true,
  barSelector: '[role="bar"]',
  spinnerSelector: '[role="spinner"]',
  parent: "body",
  color: "#29d",
  includeCSS: true,
  popover: null,
  template: [
    '<div class="bar" role="bar">',
    '<div class="peg"></div>',
    "</div>",
    '<div class="spinner" role="spinner">',
    '<div class="spinner-icon"></div>',
    "</div>"
  ].join("")
};
var status = null;
var hidden = false;
var configure = (options) => {
  Object.assign(settings, options);
  usePopover = settings.popover ?? "popover" in HTMLElement.prototype;
  if (settings.includeCSS) {
    injectCSS(settings.color);
  }
  progress2 = document.createElement("div");
  progress2.id = baseComponentSelector;
  progress2.innerHTML = settings.template;
  if (usePopover) {
    progress2.popover = "manual";
  }
};
var set7 = (n) => {
  const started = isStarted();
  n = clamp3(n, settings.minimum, 1);
  status = n === 1 ? null : n;
  const progress3 = render(!started);
  const bar = progress3.querySelector(settings.barSelector);
  const speed = settings.speed;
  const ease = settings.easing;
  progress3.offsetWidth;
  queue4((next) => {
    const barStyles = {
      transition: `all ${speed}ms ${ease}`,
      transform: `translate3d(${toBarPercentage(n)}%,0,0)`
    };
    for (const key2 in barStyles) {
      bar.style[key2] = barStyles[key2];
    }
    if (n !== 1) {
      return setTimeout(next, speed);
    }
    progress3.style.transition = "none";
    progress3.style.opacity = "1";
    progress3.offsetWidth;
    setTimeout(() => {
      progress3.style.transition = `all ${speed}ms linear`;
      progress3.style.opacity = "0";
      setTimeout(() => {
        remove3();
        progress3.style.transition = "";
        progress3.style.opacity = "";
        next();
      }, speed);
    }, speed);
  });
};
var isStarted = () => typeof status === "number";
var start = () => {
  if (!status) {
    set7(0);
  }
  const work = function() {
    setTimeout(function() {
      if (!status) {
        return;
      }
      increaseByRandom();
      work();
    }, settings.trickleSpeed);
  };
  if (settings.trickle) {
    work();
  }
};
var done = (force) => {
  if (!force && !status) {
    return;
  }
  increaseByRandom(0.3 + 0.5 * Math.random());
  set7(1);
};
var increaseByRandom = (amount) => {
  const n = status;
  if (n === null) {
    return start();
  }
  if (n > 1) {
    return;
  }
  amount = typeof amount === "number" ? amount : (() => {
    const ranges = {
      0.1: [0, 0.2],
      0.04: [0.2, 0.5],
      0.02: [0.5, 0.8],
      5e-3: [0.8, 0.99]
    };
    for (const r in ranges) {
      if (n >= ranges[r][0] && n < ranges[r][1]) {
        return parseFloat(r);
      }
    }
    return 0;
  })();
  return set7(clamp3(n + amount, 0, 0.994));
};
var render = (fromStart) => {
  if (isRendered()) {
    return document.getElementById(baseComponentSelector);
  }
  document.documentElement.classList.add(`${baseComponentSelector}-busy`);
  const bar = progress2.querySelector(settings.barSelector);
  const perc = fromStart ? "-100" : toBarPercentage(status || 0);
  bar.style.transition = "all 0 linear";
  bar.style.transform = `translate3d(${perc}%,0,0)`;
  if (!settings.showSpinner) {
    progress2.querySelector(settings.spinnerSelector)?.remove();
  }
  if (usePopover) {
    document.body.appendChild(progress2);
    if (!hidden) {
      progress2.showPopover();
    }
  } else {
    const parent = getParent();
    if (parent !== document.body) {
      parent.classList.add(`${baseComponentSelector}-custom-parent`);
    }
    parent.appendChild(progress2);
    if (hidden) {
      progress2.style.display = "none";
    }
  }
  return progress2;
};
var getParent = () => {
  return document.querySelector(settings.parent);
};
var remove3 = () => {
  document.documentElement.classList.remove(`${baseComponentSelector}-busy`);
  if (usePopover && progress2?.isConnected) {
    try {
      progress2.hidePopover();
    } catch {
    }
  }
  if (!usePopover) {
    getParent().classList.remove(`${baseComponentSelector}-custom-parent`);
  }
  progress2?.remove();
};
var isRendered = () => {
  return document.getElementById(baseComponentSelector) !== null;
};
function clamp3(n, min2, max2) {
  if (n < min2) {
    return min2;
  }
  if (n > max2) {
    return max2;
  }
  return n;
}
var toBarPercentage = (n) => (-1 + n) * 100;
var queue4 = /* @__PURE__ */ (() => {
  const pending = [];
  const next = () => {
    const fn = pending.shift();
    if (fn) {
      fn(next);
    }
  };
  return (fn) => {
    pending.push(fn);
    if (pending.length === 1) {
      next();
    }
  };
})();
var injectCSS = (color) => {
  const element = document.createElement("style");
  const nonce = config.get("nonce");
  if (nonce) {
    element.nonce = nonce;
  }
  element.textContent = `
    #${baseComponentSelector} {
      pointer-events: none;
      background: none;
      border: none;
      margin: 0;
      padding: 0;
      overflow: visible;
      inset: unset;
      width: 100%;
      height: 0;
      position: fixed;
      top: 0;
      left: 0;
    }

    #${baseComponentSelector}::backdrop {
      display: none;
    }

    #${baseComponentSelector} .bar {
      background: ${color};

      position: fixed;
      z-index: 1031;
      top: 0;
      left: 0;

      width: 100%;
      height: 2px;
    }

    #${baseComponentSelector} .peg {
      display: block;
      position: absolute;
      right: 0px;
      width: 100px;
      height: 100%;
      box-shadow: 0 0 10px ${color}, 0 0 5px ${color};
      opacity: 1.0;

      transform: rotate(3deg) translate(0px, -4px);
    }

    #${baseComponentSelector} .spinner {
      display: block;
      position: fixed;
      z-index: 1031;
      top: 15px;
      right: 15px;
    }

    #${baseComponentSelector} .spinner-icon {
      width: 18px;
      height: 18px;
      box-sizing: border-box;

      border: solid 2px transparent;
      border-top-color: ${color};
      border-left-color: ${color};
      border-radius: 50%;

      animation: ${baseComponentSelector}-spinner 400ms linear infinite;
    }

    .${baseComponentSelector}-custom-parent {
      overflow: hidden;
      position: relative;
    }

    .${baseComponentSelector}-custom-parent #${baseComponentSelector} .spinner,
    .${baseComponentSelector}-custom-parent #${baseComponentSelector} .bar {
      position: absolute;
    }

    @keyframes ${baseComponentSelector}-spinner {
      0%   { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  `;
  document.head.appendChild(element);
};
var show = () => {
  hidden = false;
  if (!progress2?.isConnected) {
    return;
  }
  if (usePopover) {
    try {
      progress2.showPopover();
    } catch {
    }
  } else {
    progress2.style.display = "";
  }
};
var hide = () => {
  hidden = true;
  if (!progress2?.isConnected) {
    return;
  }
  if (usePopover) {
    try {
      progress2.hidePopover();
    } catch {
    }
  } else {
    progress2.style.display = "none";
  }
};
var progress_component_default = {
  configure,
  isStarted,
  done,
  set: set7,
  remove: remove3,
  start,
  status,
  show,
  hide
};
var Progress = class {
  hideCount = 0;
  start() {
    progress_component_default.start();
  }
  reveal(force = false) {
    this.hideCount = Math.max(0, this.hideCount - 1);
    if (force || this.hideCount === 0) {
      progress_component_default.show();
    }
  }
  hide() {
    this.hideCount++;
    progress_component_default.hide();
  }
  set(status2) {
    progress_component_default.set(Math.max(0, Math.min(1, status2)));
  }
  finish() {
    progress_component_default.done();
  }
  reset() {
    progress_component_default.set(0);
  }
  remove() {
    progress_component_default.done();
    progress_component_default.remove();
  }
  isStarted() {
    return progress_component_default.isStarted();
  }
  getStatus() {
    return progress_component_default.status;
  }
};
var progress = new Progress();
function addEventListeners(delay3) {
  document.addEventListener("inertia:start", (e) => handleStartEvent(e, delay3));
  document.addEventListener("inertia:progress", handleProgressEvent);
}
function handleStartEvent(event, delay3) {
  if (!event.detail.visit.showProgress) {
    progress.hide();
  }
  const timeout3 = setTimeout(() => progress.start(), delay3);
  document.addEventListener("inertia:finish", (e) => finish(e, timeout3), { once: true });
}
function handleProgressEvent(event) {
  if (progress.isStarted() && event.detail.progress?.percentage) {
    progress.set(Math.max(progress.getStatus(), event.detail.progress.percentage / 100 * 0.9));
  }
}
function finish(event, timeout3) {
  clearTimeout(timeout3);
  if (!progress.isStarted()) {
    return;
  }
  if (event.detail.visit.completed) {
    progress.finish();
  } else if (event.detail.visit.interrupted) {
    progress.reset();
  } else if (event.detail.visit.cancelled) {
    progress.remove();
  }
}
function setupProgress({
  delay: delay3 = 250,
  color = "#29d",
  includeCSS = true,
  showSpinner = false,
  popover = null
} = {}) {
  addEventListeners(delay3);
  progress_component_default.configure({
    showSpinner,
    includeCSS,
    color,
    popover
  });
}
var FormComponentResetSymbol = /* @__PURE__ */ Symbol("FormComponentReset");
function isFormElement(element) {
  return element instanceof HTMLInputElement || element instanceof HTMLSelectElement || element instanceof HTMLTextAreaElement;
}
function resetInputElement(input, defaultValues) {
  const oldValue = input.value;
  const oldChecked = input.checked;
  switch (input.type.toLowerCase()) {
    case "checkbox":
      input.checked = defaultValues.includes(input.value);
      break;
    case "radio":
      input.checked = defaultValues[0] === input.value;
      break;
    case "file":
      input.value = "";
      break;
    case "button":
    case "submit":
    case "reset":
    case "image":
      break;
    default:
      input.value = defaultValues[0] !== null && defaultValues[0] !== void 0 ? String(defaultValues[0]) : "";
  }
  return input.value !== oldValue || input.checked !== oldChecked;
}
function resetSelectElement(select, defaultValues) {
  const oldValue = select.value;
  const oldSelectedOptions = Array.from(select.selectedOptions).map((opt) => opt.value);
  if (select.multiple) {
    const defaultStrings = defaultValues.map((value) => String(value));
    Array.from(select.options).forEach((option) => {
      option.selected = defaultStrings.includes(option.value);
    });
  } else {
    select.value = defaultValues[0] !== void 0 ? String(defaultValues[0]) : "";
  }
  const newSelectedOptions = Array.from(select.selectedOptions).map((opt) => opt.value);
  const hasChanged = select.multiple ? JSON.stringify(oldSelectedOptions.sort()) !== JSON.stringify(newSelectedOptions.sort()) : select.value !== oldValue;
  return hasChanged;
}
function resetFormElement(element, defaultValues) {
  if (element.disabled) {
    if (element instanceof HTMLInputElement) {
      const oldValue = element.value;
      const oldChecked = element.checked;
      switch (element.type.toLowerCase()) {
        case "checkbox":
        case "radio":
          element.checked = element.defaultChecked;
          return element.checked !== oldChecked;
        case "file":
          element.value = "";
          return oldValue !== "";
        case "button":
        case "submit":
        case "reset":
        case "image":
          return false;
        default:
          element.value = element.defaultValue;
          return element.value !== oldValue;
      }
    } else if (element instanceof HTMLSelectElement) {
      const oldSelectedOptions = Array.from(element.selectedOptions).map((opt) => opt.value);
      Array.from(element.options).forEach((option) => {
        option.selected = option.defaultSelected;
      });
      const newSelectedOptions = Array.from(element.selectedOptions).map((opt) => opt.value);
      return JSON.stringify(oldSelectedOptions.sort()) !== JSON.stringify(newSelectedOptions.sort());
    } else if (element instanceof HTMLTextAreaElement) {
      const oldValue = element.value;
      element.value = element.defaultValue;
      return element.value !== oldValue;
    }
    return false;
  }
  if (element instanceof HTMLInputElement) {
    return resetInputElement(element, defaultValues);
  } else if (element instanceof HTMLSelectElement) {
    return resetSelectElement(element, defaultValues);
  } else if (element instanceof HTMLTextAreaElement) {
    const oldValue = element.value;
    element.value = defaultValues[0] !== void 0 ? String(defaultValues[0]) : "";
    return element.value !== oldValue;
  }
  return false;
}
function resetFieldElements(elements, defaultValues) {
  let hasChanged = false;
  if (elements instanceof RadioNodeList || elements instanceof HTMLCollection) {
    Array.from(elements).forEach((node, index) => {
      if (node instanceof Element && isFormElement(node)) {
        if (node instanceof HTMLInputElement && ["checkbox", "radio"].includes(node.type.toLowerCase())) {
          if (resetFormElement(node, defaultValues)) {
            hasChanged = true;
          }
        } else {
          const indexedDefaultValues = defaultValues[index] !== void 0 ? [defaultValues[index]] : [defaultValues[0] ?? null].filter(Boolean);
          if (resetFormElement(node, indexedDefaultValues)) {
            hasChanged = true;
          }
        }
      }
    });
  } else if (isFormElement(elements)) {
    hasChanged = resetFormElement(elements, defaultValues);
  }
  return hasChanged;
}
function resetFormFields(formElement, defaults2, fieldNames) {
  if (!formElement) {
    return;
  }
  const resetEntireForm = !fieldNames || fieldNames.length === 0;
  if (resetEntireForm) {
    const formData = new FormData(formElement);
    const formElementNames = Array.from(formElement.elements).map((el) => isFormElement(el) ? el.name : "").filter(Boolean);
    fieldNames = [.../* @__PURE__ */ new Set([...defaults2.keys(), ...formData.keys(), ...formElementNames])];
  }
  let hasChanged = false;
  fieldNames.forEach((fieldName) => {
    const elements = formElement.elements.namedItem(fieldName);
    if (elements) {
      if (resetFieldElements(elements, defaults2.getAll(fieldName))) {
        hasChanged = true;
      }
    }
  });
  if (hasChanged && resetEntireForm) {
    formElement.dispatchEvent(
      new CustomEvent("reset", { bubbles: true, cancelable: true, detail: { [FormComponentResetSymbol]: true } })
    );
  }
}
function buildSSRBody(id, page22, html) {
  const json = JSON.stringify(page22).replace(/\//g, "\\/");
  return `<script data-page="${id}" type="application/json">${json}<\/script><div data-server-rendered="true" id="${id}">${html}</div>`;
}
var router = new Router();

// node_modules/@inertiajs/vue3/dist/index.js
var store = createLayoutPropsStore();
var state = ref(store.get());
store.subscribe(() => {
  state.value = store.get();
});
function setLayoutProps(nameOrProps, props) {
  if (typeof nameOrProps === "string") {
    store.setFor(nameOrProps, props);
  } else {
    store.set(nameOrProps);
  }
}
function resetLayoutProps() {
  store.reset();
  state.value = store.get();
}
var remember = {
  created() {
    if (!this.$options.remember) {
      return;
    }
    if (Array.isArray(this.$options.remember)) {
      this.$options.remember = { data: this.$options.remember };
    }
    if (typeof this.$options.remember === "string") {
      this.$options.remember = { data: [this.$options.remember] };
    }
    if (typeof this.$options.remember.data === "string") {
      this.$options.remember = { data: [this.$options.remember.data] };
    }
    const rememberKey = this.$options.remember.key instanceof Function ? this.$options.remember.key.call(this) : this.$options.remember.key;
    const restored = router.restore(rememberKey);
    const rememberable = this.$options.remember.data.filter((key2) => {
      return !(this[key2] !== null && typeof this[key2] === "object" && this[key2].__rememberable === false);
    });
    const hasCallbacks = (key2) => {
      return this[key2] !== null && typeof this[key2] === "object" && typeof this[key2].__remember === "function" && typeof this[key2].__restore === "function";
    };
    rememberable.forEach((key2) => {
      if (this[key2] !== void 0 && restored !== void 0 && restored[key2] !== void 0) {
        hasCallbacks(key2) ? this[key2].__restore(restored[key2]) : this[key2] = restored[key2];
      }
      this.$watch(
        key2,
        () => {
          router.remember(
            rememberable.reduce(
              (data, key3) => ({
                ...data,
                [key3]: cloneDeep(hasCallbacks(key3) ? this[key3].__remember() : this[key3])
              }),
              {}
            ),
            rememberKey
          );
        },
        { immediate: true, deep: true }
      );
    });
  }
};
var remember_default = remember;
function useFormState(options) {
  const { data: dataOption, rememberKey } = options;
  let { precognitionEndpoint } = options;
  const isDataFunction = typeof dataOption === "function";
  const resolveData = () => isDataFunction ? dataOption() : dataOption;
  const restored = rememberKey ? router.restore(rememberKey) : null;
  const initialData = restored?.data ?? cloneDeep(resolveData());
  let defaults2 = cloneDeep(initialData);
  let transform2 = (data) => data;
  let validatorRef = null;
  let withAllErrors = null;
  const withAllErrorsEnabled = () => withAllErrors ?? config2.get("form.withAllErrors");
  let recentlySuccessfulTimeoutId;
  let defaultsCalledInOnSuccess = false;
  let rememberExcludeKeys = [];
  const form = reactive({
    ...cloneDeep(defaults2),
    isDirty: false,
    errors: {},
    hasErrors: false,
    processing: false,
    progress: null,
    wasSuccessful: false,
    recentlySuccessful: false,
    withPrecognition(...args) {
      precognitionEndpoint = UseFormUtils.createWayfinderCallback(...args);
      const formWithPrecognition = this;
      const validator = createValidator(
        (client2) => {
          const { method: method2, url } = precognitionEndpoint();
          const transformedData = cloneDeep(transform2(this.data()));
          return client2[method2](url, transformedData);
        },
        cloneDeep(defaults2)
      );
      validatorRef = validator;
      validator.on("validatingChanged", () => {
        formWithPrecognition.validating = validator.validating();
      }).on("validatedChanged", () => {
        formWithPrecognition.__valid = validator.valid();
      }).on("touchedChanged", () => {
        formWithPrecognition.__touched = validator.touched();
      }).on("errorsChanged", () => {
        const validationErrors = withAllErrorsEnabled() ? validator.errors() : toSimpleValidationErrors(validator.errors());
        this.errors = {};
        this.setError(validationErrors);
        formWithPrecognition.__valid = validator.valid();
      });
      const tap = (value, callback) => {
        callback(value);
        return value;
      };
      Object.assign(formWithPrecognition, {
        __touched: [],
        __valid: [],
        validating: false,
        validator: () => validator,
        withAllErrors: () => tap(formWithPrecognition, () => withAllErrors = true),
        valid: (field) => formWithPrecognition.__valid.includes(field),
        invalid: (field) => field in this.errors,
        setValidationTimeout: (duration) => tap(formWithPrecognition, () => validator.setTimeout(duration)),
        validateFiles: () => tap(formWithPrecognition, () => validator.validateFiles()),
        withoutFileValidation: () => tap(formWithPrecognition, () => validator.withoutFileValidation()),
        touch: (field, ...fields) => {
          if (Array.isArray(field)) {
            validator.touch(field);
          } else if (typeof field === "string") {
            validator.touch([field, ...fields]);
          } else {
            validator.touch(field);
          }
          return formWithPrecognition;
        },
        touched: (field) => typeof field === "string" ? formWithPrecognition.__touched.includes(field) : formWithPrecognition.__touched.length > 0,
        validate: (field, config3) => {
          if (typeof field === "object" && !("target" in field)) {
            config3 = field;
            field = void 0;
          }
          if (field === void 0) {
            validator.validate(config3);
          } else {
            const fieldName = resolveName(field);
            const transformedData = transform2(this.data());
            validator.validate(fieldName, get(transformedData, fieldName), config3);
          }
          return formWithPrecognition;
        },
        setErrors: (errors) => tap(formWithPrecognition, () => this.setError(errors)),
        forgetError: (field) => tap(
          formWithPrecognition,
          () => this.clearErrors(resolveName(field))
        )
      });
      return formWithPrecognition;
    },
    data() {
      return Object.keys(defaults2).reduce((carry, key2) => {
        return set(carry, key2, get(this, key2));
      }, {});
    },
    transform(callback) {
      transform2 = callback;
      return this;
    },
    defaults(fieldOrFields, maybeValue) {
      if (isDataFunction) {
        throw new Error("You cannot call `defaults()` when using a function to define your form data.");
      }
      defaultsCalledInOnSuccess = true;
      if (typeof fieldOrFields === "undefined") {
        defaults2 = cloneDeep(this.data());
        this.isDirty = false;
      } else {
        defaults2 = typeof fieldOrFields === "string" ? set(cloneDeep(defaults2), fieldOrFields, maybeValue) : Object.assign({}, cloneDeep(defaults2), fieldOrFields);
      }
      validatorRef?.defaults(defaults2);
      return this;
    },
    reset(...fields) {
      const resolvedData = isDataFunction ? cloneDeep(resolveData()) : defaults2;
      const clonedData = cloneDeep(resolvedData);
      if (fields.length === 0) {
        if (isDataFunction) {
          defaults2 = clonedData;
        }
        Object.assign(this, clonedData);
      } else {
        ;
        fields.filter((key2) => has(clonedData, key2)).forEach((key2) => {
          if (isDataFunction) {
            set(defaults2, key2, get(clonedData, key2));
          }
          set(this, key2, get(clonedData, key2));
        });
      }
      validatorRef?.reset(...fields);
      return this;
    },
    setError(fieldOrFields, maybeValue) {
      const errors = typeof fieldOrFields === "string" ? { [fieldOrFields]: maybeValue } : fieldOrFields;
      Object.assign(this.errors, errors);
      this.hasErrors = Object.keys(this.errors).length > 0;
      validatorRef?.setErrors(errors);
      return this;
    },
    clearErrors(...fields) {
      this.errors = Object.keys(this.errors).reduce(
        (carry, field) => ({
          ...carry,
          ...fields.length > 0 && !fields.includes(field) ? { [field]: this.errors[field] } : {}
        }),
        {}
      );
      this.hasErrors = Object.keys(this.errors).length > 0;
      if (validatorRef) {
        if (fields.length === 0) {
          validatorRef.setErrors({});
        } else {
          fields.forEach(validatorRef.forgetError);
        }
      }
      return this;
    },
    resetAndClearErrors(...fields) {
      this.reset(...fields);
      this.clearErrors(...fields);
      return this;
    },
    __rememberable: rememberKey === null,
    __remember() {
      const formData = this.data();
      if (rememberExcludeKeys.length > 0) {
        const filtered = { ...formData };
        rememberExcludeKeys.forEach((k) => delete filtered[k]);
        return { data: filtered, errors: this.errors };
      }
      return { data: formData, errors: this.errors };
    },
    __restore(restored2) {
      Object.assign(this, restored2.data);
      this.setError(restored2.errors);
    }
  });
  const typedForm = form;
  if (restored?.errors) {
    typedForm.setError(restored.errors);
  }
  watch(
    typedForm,
    () => {
      typedForm.isDirty = !isEqual(typedForm.data(), defaults2);
    },
    { immediate: true, deep: true }
  );
  watch(
    typedForm,
    (newValue) => {
      if (!rememberKey) {
        return;
      }
      const storedData = router.restore(rememberKey);
      const newData = cloneDeep(newValue.__remember());
      if (!isEqual(storedData, newData)) {
        router.remember(newData, rememberKey);
      }
    },
    { immediate: true, deep: true }
  );
  if (precognitionEndpoint) {
    typedForm.withPrecognition(precognitionEndpoint);
  }
  return {
    form: typedForm,
    setDefaults: (newDefaults) => {
      defaults2 = newDefaults;
    },
    getTransform: () => transform2,
    getPrecognitionEndpoint: () => precognitionEndpoint ?? null,
    markAsSuccessful: () => {
      typedForm.clearErrors();
      typedForm.wasSuccessful = true;
      typedForm.recentlySuccessful = true;
      recentlySuccessfulTimeoutId = setTimeout(
        () => typedForm.recentlySuccessful = false,
        config2.get("form.recentlySuccessfulDuration")
      );
    },
    wasDefaultsCalledInOnSuccess: () => defaultsCalledInOnSuccess,
    resetDefaultsCalledInOnSuccess: () => {
      defaultsCalledInOnSuccess = false;
    },
    setRememberExcludeKeys: (keys2) => {
      rememberExcludeKeys = keys2;
    },
    resetBeforeSubmit: () => {
      typedForm.wasSuccessful = false;
      typedForm.recentlySuccessful = false;
      clearTimeout(recentlySuccessfulTimeoutId);
    },
    finishProcessing: () => {
      typedForm.processing = false;
      typedForm.progress = null;
    },
    withAllErrors: {
      enabled: withAllErrorsEnabled,
      enable: () => {
        withAllErrors = true;
      }
    }
  };
}
var reservedFormKeys = null;
var bootstrapping = false;
function validateFormDataKeys(data) {
  if (bootstrapping) {
    return;
  }
  if (reservedFormKeys === null) {
    bootstrapping = true;
    reservedFormKeys = new Set(Object.keys(useForm({})));
    bootstrapping = false;
  }
  const conflicts = Object.keys(data).filter((key2) => reservedFormKeys.has(key2));
  if (conflicts.length > 0) {
    console.error(
      `[Inertia] useForm() data contains field(s) that conflict with form properties: ${conflicts.map((k) => `"${k}"`).join(", ")}. These fields will be overwritten by form methods/properties. Please rename these fields.`
    );
  }
}
function useForm(...args) {
  const { rememberKey, data, precognitionEndpoint } = UseFormUtils.parseUseFormArguments(...args);
  const initialDefaults = typeof data === "function" ? cloneDeep(data()) : cloneDeep(data);
  validateFormDataKeys(initialDefaults);
  let cancelToken = null;
  let pendingOptimisticCallback = null;
  const {
    form: baseForm,
    setDefaults,
    getTransform,
    getPrecognitionEndpoint,
    markAsSuccessful,
    wasDefaultsCalledInOnSuccess,
    resetDefaultsCalledInOnSuccess,
    setRememberExcludeKeys,
    resetBeforeSubmit,
    finishProcessing
  } = useFormState({
    data,
    rememberKey,
    precognitionEndpoint
  });
  const form = baseForm;
  const createSubmitMethod = (method2) => (url, options = {}) => {
    form.submit(method2, url, options);
  };
  Object.assign(form, {
    submit(...args2) {
      const { method: method2, url, options } = UseFormUtils.parseSubmitArguments(args2, getPrecognitionEndpoint());
      resetDefaultsCalledInOnSuccess();
      const _options = {
        ...options,
        onCancelToken: (token) => {
          cancelToken = token;
          return options.onCancelToken?.(token);
        },
        onBefore: (visit) => {
          resetBeforeSubmit();
          return options.onBefore?.(visit);
        },
        onStart: (visit) => {
          form.processing = true;
          return options.onStart?.(visit);
        },
        onProgress: (event) => {
          form.progress = event ?? null;
          return options.onProgress?.(event);
        },
        onSuccess: async (page22) => {
          markAsSuccessful();
          const onSuccess = options.onSuccess ? await options.onSuccess(page22) : null;
          if (!wasDefaultsCalledInOnSuccess()) {
            setDefaults(cloneDeep(form.data()));
            form.isDirty = false;
          }
          return onSuccess;
        },
        onError: (errors) => {
          form.clearErrors().setError(errors);
          return options.onError?.(errors);
        },
        onCancel: () => {
          return options.onCancel?.();
        },
        onFinish: (visit) => {
          finishProcessing();
          cancelToken = null;
          return options.onFinish?.(visit);
        }
      };
      _options.optimistic = _options.optimistic ?? pendingOptimisticCallback ?? void 0;
      pendingOptimisticCallback = null;
      const transformedData = getTransform()(form.data());
      if (method2 === "delete") {
        router.delete(url, { ..._options, data: transformedData });
      } else {
        router[method2](url, transformedData, _options);
      }
    },
    get: createSubmitMethod("get"),
    post: createSubmitMethod("post"),
    put: createSubmitMethod("put"),
    patch: createSubmitMethod("patch"),
    delete: createSubmitMethod("delete"),
    cancel() {
      if (cancelToken) {
        cancelToken.cancel();
      }
    },
    dontRemember(...keys2) {
      setRememberExcludeKeys(keys2);
      return form;
    },
    optimistic(callback) {
      pendingOptimisticCallback = callback;
      return form;
    }
  });
  return getPrecognitionEndpoint() ? form : form;
}
function isComponent(value) {
  if (!value) {
    return false;
  }
  if (typeof value === "function") {
    return true;
  }
  if (typeof value === "object") {
    const obj = value;
    return typeof obj.render === "function" || typeof obj.setup === "function" || typeof obj.template === "string" || "__file" in obj || "__name" in obj;
  }
  return false;
}
function isRenderFunction(value) {
  if (typeof value !== "function") {
    return false;
  }
  const fn = value;
  return fn.length === 2 && typeof fn.prototype === "undefined";
}
var component = ref(void 0);
var page2 = ref();
var pageAccessor = null;
var layout = shallowRef(null);
var key = ref(void 0);
var headManager;
var App = defineComponent({
  name: "Inertia",
  props: {
    initialPage: {
      type: Object,
      required: true
    },
    initialComponent: {
      type: Object,
      required: false
    },
    resolveComponent: {
      type: Function,
      required: false
    },
    titleCallback: {
      type: Function,
      required: false,
      default: (title) => title
    },
    onHeadUpdate: {
      type: Function,
      required: false,
      default: () => () => {
      }
    },
    defaultLayout: {
      type: Function,
      required: false
    }
  },
  setup({
    initialPage,
    initialComponent,
    resolveComponent,
    titleCallback,
    onHeadUpdate,
    defaultLayout
  }) {
    component.value = initialComponent ? markRaw(initialComponent) : void 0;
    page2.value = { ...initialPage, flash: initialPage.flash ?? {} };
    key.value = void 0;
    const isServer3 = typeof window === "undefined";
    headManager = createHeadManager(isServer3, titleCallback || ((title) => title), onHeadUpdate || (() => {
    }));
    if (!isServer3) {
      router.init({
        initialPage,
        resolveComponent,
        swapComponent: async (options) => {
          if (!options.preserveState) {
            resetLayoutProps();
          }
          component.value = markRaw(options.component);
          page2.value = options.page;
          key.value = options.preserveState ? key.value : Date.now();
        },
        onFlash: (flash) => {
          page2.value = { ...page2.value, flash };
        }
      });
      router.on("navigate", () => headManager.forceUpdate());
    }
    return () => {
      if (component.value) {
        component.value.inheritAttrs = !!component.value.inheritAttrs;
        const child = h(component.value, {
          ...page2.value.props,
          key: key.value
        });
        if (layout.value) {
          component.value.layout = layout.value;
          layout.value = null;
        }
        if (component.value.layout && isRenderFunction(component.value.layout)) {
          return component.value.layout(h, child);
        }
        let effectiveLayout;
        let callbackProps = null;
        const layoutValue = component.value.layout;
        if (typeof layoutValue === "function" && layoutValue.length <= 1 && typeof layoutValue.prototype === "undefined") {
          const result2 = layoutValue(page2.value.props);
          if (isPropsObjectOrCallback(result2, isComponent)) {
            effectiveLayout = defaultLayout?.(page2.value.component, page2.value);
            callbackProps = result2;
          } else {
            effectiveLayout = result2;
          }
        } else if (isPropsObject(layoutValue, isComponent)) {
          effectiveLayout = defaultLayout?.(page2.value.component, page2.value);
          callbackProps = layoutValue;
        } else {
          effectiveLayout = layoutValue ?? defaultLayout?.(page2.value.component, page2.value);
        }
        if (effectiveLayout) {
          let layouts = normalizeLayouts(
            effectiveLayout,
            isComponent,
            component.value.layout && !callbackProps ? isRenderFunction : void 0
          );
          if (callbackProps) {
            layouts = layouts.map((l) => ({ ...l, props: { ...l.props, ...callbackProps } }));
          }
          if (layouts.length > 0) {
            const dynamicProps = isServer3 ? { shared: {}, named: {} } : state.value;
            return layouts.reduceRight((childNode, layout2) => {
              const layoutComponent = layout2.component;
              layoutComponent.inheritAttrs = !!layoutComponent.inheritAttrs;
              return h(
                layoutComponent,
                {
                  ...page2.value.props,
                  ...layout2.props,
                  ...dynamicProps.shared,
                  ...layout2.name ? dynamicProps.named[layout2.name] || {} : {}
                },
                () => childNode
              );
            }, child);
          }
        }
        return child;
      }
    };
  }
});
var app_default = App;
var plugin = {
  install(app) {
    router.form = useForm;
    Object.defineProperty(app.config.globalProperties, "$inertia", { get: () => router });
    Object.defineProperty(app.config.globalProperties, "$page", { get: () => page2.value });
    Object.defineProperty(app.config.globalProperties, "$headManager", { get: () => headManager });
    app.mixin(remember_default);
  }
};
function usePage() {
  if (!pageAccessor) {
    pageAccessor = reactive({
      props: computed(() => page2.value?.props),
      url: computed(() => page2.value?.url),
      component: computed(() => page2.value?.component),
      version: computed(() => page2.value?.version),
      clearHistory: computed(() => page2.value?.clearHistory),
      deferredProps: computed(() => page2.value?.deferredProps),
      rescuedProps: computed(() => page2.value?.rescuedProps),
      mergeProps: computed(() => page2.value?.mergeProps),
      prependProps: computed(() => page2.value?.prependProps),
      deepMergeProps: computed(() => page2.value?.deepMergeProps),
      matchPropsOn: computed(() => page2.value?.matchPropsOn),
      rememberedState: computed(() => page2.value?.rememberedState),
      encryptHistory: computed(() => page2.value?.encryptHistory),
      scrollProps: computed(() => page2.value?.scrollProps),
      flash: computed(() => page2.value?.flash)
    });
  }
  return pageAccessor;
}
async function createInertiaApp({
  id = "app",
  resolve,
  setup,
  title,
  progress: progress22 = {},
  page: page22,
  render: render2,
  defaults: defaults2 = {},
  nonce,
  http: http3,
  layout: layout2,
  withApp
} = {}) {
  config2.replace(defaults2);
  if (nonce) {
    config2.set("nonce", nonce);
  }
  if (http3) {
    http.setClient(http3);
  }
  const isServer3 = typeof window === "undefined";
  const resolveComponent = (name, page3) => Promise.resolve(resolve(name, page3)).then((module) => module.default || module);
  if (isServer3 && !page22 && !render2) {
    return async (page3, renderToString) => {
      let head22 = [];
      const initialComponent = await resolveComponent(page3.component, page3);
      const props = {
        initialPage: page3,
        initialComponent,
        resolveComponent,
        titleCallback: title,
        onHeadUpdate: (elements) => head22 = elements,
        defaultLayout: layout2
      };
      let vueApp2;
      if (setup) {
        vueApp2 = setup({
          el: null,
          App: app_default,
          props,
          plugin
        });
      } else {
        vueApp2 = createSSRApp({ render: () => h(app_default, props) });
        vueApp2.use(plugin);
        if (withApp) {
          withApp(vueApp2, { ssr: true, page: page3 });
        }
      }
      const html = await renderToString(vueApp2);
      const body = buildSSRBody(id, page3, html);
      return { head: head22, body };
    };
  }
  const initialPage = page22 || getInitialPageFromDOM(id);
  let head3 = [];
  const vueApp = await Promise.all([
    resolveComponent(initialPage.component, initialPage),
    router.decryptHistory().catch(() => {
    })
  ]).then(([initialComponent]) => {
    const props = {
      initialPage,
      initialComponent,
      resolveComponent,
      titleCallback: title,
      onHeadUpdate: isServer3 ? (elements) => head3 = elements : void 0,
      defaultLayout: layout2
    };
    if (isServer3) {
      return setup({
        el: null,
        App: app_default,
        props,
        plugin
      });
    }
    const el = document.getElementById(id);
    if (setup) {
      return setup({
        el,
        App: app_default,
        props,
        plugin
      });
    }
    if (el.hasAttribute("data-server-rendered")) {
      const app = createSSRApp({ render: () => h(app_default, props) });
      app.use(plugin);
      if (withApp) {
        withApp(app, { ssr: false, page: initialPage });
      }
      app.mount(el);
    } else {
      const app = createApp({ render: () => h(app_default, props) });
      app.use(plugin);
      if (withApp) {
        withApp(app, { ssr: false, page: initialPage });
      }
      app.mount(el);
    }
  });
  if (!isServer3 && progress22) {
    setupProgress(progress22);
  }
  if (isServer3 && render2 && vueApp) {
    const html = await render2(vueApp);
    const body = buildSSRBody(id, initialPage, html);
    return { head: head3, body };
  }
}
var deferred_default = defineComponent({
  name: "Deferred",
  props: {
    data: {
      type: [String, Array],
      required: true
    }
  },
  slots: Object,
  setup(props, { slots }) {
    const reloading = ref(false);
    const activeReloads = /* @__PURE__ */ new Set();
    const page22 = usePage();
    const keys2 = computed(() => Array.isArray(props.data) ? props.data : [props.data]);
    const rescuedKeys = computed(() => new Set(page22.rescuedProps));
    let removeStartListener = null;
    let removeFinishListener = null;
    onMounted(() => {
      removeStartListener = router.on("start", (e) => {
        const visit = e.detail.visit;
        if (visit.preserveState === true && isSameUrlWithoutQueryOrHash(visit.url, window.location) && partialReloadRequestsSomeProps(visit, keys2.value)) {
          activeReloads.add(visit);
          reloading.value = true;
        }
      });
      removeFinishListener = router.on("finish", (e) => {
        const visit = e.detail.visit;
        if (activeReloads.has(visit)) {
          activeReloads.delete(visit);
          reloading.value = activeReloads.size > 0;
        }
      });
    });
    onUnmounted(() => {
      removeStartListener?.();
      removeFinishListener?.();
      activeReloads.clear();
    });
    return () => {
      if (!slots.fallback) {
        throw new Error("`<Deferred>` requires a `<template #fallback>` slot");
      }
      const propsAreDefined = keys2.value.every((key2) => get(page22.props, key2) !== void 0);
      const hasRescuedProps = keys2.value.some((key2) => rescuedKeys.value.has(key2));
      const slotProps = { reloading: reloading.value };
      if (propsAreDefined && !hasRescuedProps) {
        return h(Fragment, { key: "default" }, slots.default?.(slotProps) ?? []);
      }
      if (hasRescuedProps && slots.rescue) {
        return h(Fragment, { key: "rescue" }, slots.rescue(slotProps));
      }
      return h(Fragment, { key: "fallback" }, slots.fallback({}));
    };
  }
});
var noop4 = () => void 0;
var FormContextKey = /* @__PURE__ */ Symbol("InertiaFormContext");
var Form = defineComponent({
  name: "Form",
  slots: Object,
  props: {
    action: {
      type: [String, Object],
      default: ""
    },
    method: {
      type: String,
      default: "get"
    },
    headers: {
      type: Object,
      default: () => ({})
    },
    queryStringArrayFormat: {
      type: String,
      default: "brackets"
    },
    errorBag: {
      type: [String, null],
      default: null
    },
    showProgress: {
      type: Boolean,
      default: true
    },
    transform: {
      type: Function,
      default: (data) => data
    },
    options: {
      type: Object,
      default: () => ({})
    },
    resetOnError: {
      type: [Boolean, Array],
      default: false
    },
    resetOnSuccess: {
      type: [Boolean, Array],
      default: false
    },
    setDefaultsOnSuccess: {
      type: Boolean,
      default: false
    },
    onCancelToken: {
      type: Function,
      default: noop4
    },
    onBefore: {
      type: Function,
      default: noop4
    },
    onStart: {
      type: Function,
      default: noop4
    },
    onProgress: {
      type: Function,
      default: noop4
    },
    onFinish: {
      type: Function,
      default: noop4
    },
    onCancel: {
      type: Function,
      default: noop4
    },
    onSuccess: {
      type: Function,
      default: noop4
    },
    onError: {
      type: Function,
      default: noop4
    },
    onSubmitComplete: {
      type: Function,
      default: noop4
    },
    disableWhileProcessing: {
      type: Boolean,
      default: false
    },
    invalidateCacheTags: {
      type: [String, Array],
      default: () => []
    },
    validateFiles: {
      type: Boolean,
      default: false
    },
    validationTimeout: {
      type: Number,
      default: 1500
    },
    optimistic: {
      type: Function,
      default: void 0
    },
    withAllErrors: {
      type: Boolean,
      default: null
    },
    component: {
      type: String,
      default: null
    },
    instant: {
      type: Boolean,
      default: false
    }
  },
  setup(props, { slots, attrs, expose }) {
    const getTransformedData = () => {
      const [_url, data] = getUrlAndData();
      return props.transform(data);
    };
    const form = useForm({}).withPrecognition(
      () => method2.value,
      () => getUrlAndData()[0]
    ).transform(getTransformedData).setValidationTimeout(props.validationTimeout);
    if (props.validateFiles) {
      form.validateFiles();
    }
    if (props.withAllErrors ?? config.get("form.withAllErrors")) {
      form.withAllErrors();
    }
    const formElement = ref();
    const method2 = computed(
      () => isUrlMethodPair(props.action) ? props.action.method : props.method.toLowerCase()
    );
    const resolvedComponent = computed(() => {
      if (props.component) {
        return props.component;
      }
      if (props.instant && isUrlMethodPair(props.action)) {
        return resolveUrlMethodPairComponent(props.action);
      }
      return null;
    });
    const isDirty = ref(false);
    const defaultData = ref(new FormData());
    const onFormUpdate = (event) => {
      if (event.type === "reset" && event.detail?.[FormComponentResetSymbol]) {
        event.preventDefault();
      }
      isDirty.value = event.type === "reset" ? false : !isEqual(getData(), formDataToObject(defaultData.value));
    };
    const formEvents = ["input", "change", "reset"];
    onMounted(() => {
      defaultData.value = getFormData();
      form.defaults(getData());
      formEvents.forEach((e) => formElement.value.addEventListener(e, onFormUpdate));
    });
    watch(
      () => props.validateFiles,
      (value) => value ? form.validateFiles() : form.withoutFileValidation()
    );
    watch(
      () => props.validationTimeout,
      (value) => form.setValidationTimeout(value)
    );
    onBeforeUnmount(() => formEvents.forEach((e) => formElement.value?.removeEventListener(e, onFormUpdate)));
    const getFormData = (submitter) => new FormData(formElement.value, submitter);
    const getData = (submitter) => formDataToObject(getFormData(submitter));
    const getUrlAndData = (submitter) => {
      return mergeDataIntoQueryString(
        method2.value,
        isUrlMethodPair(props.action) ? props.action.url : props.action,
        getData(submitter),
        props.queryStringArrayFormat
      );
    };
    const submit = (submitter) => {
      const [url, data] = getUrlAndData(submitter);
      const formTarget = submitter?.getAttribute("formtarget");
      if (formTarget === "_blank" && method2.value === "get") {
        window.open(url, "_blank");
        return;
      }
      const maybeReset = (resetOption) => {
        if (!resetOption) {
          return;
        }
        if (resetOption === true) {
          reset();
        } else if (resetOption.length > 0) {
          reset(...resetOption);
        }
      };
      const submitOptions = {
        headers: props.headers,
        queryStringArrayFormat: props.queryStringArrayFormat,
        errorBag: props.errorBag,
        showProgress: props.showProgress,
        invalidateCacheTags: props.invalidateCacheTags,
        component: resolvedComponent.value,
        optimistic: props.optimistic ? (pageProps) => props.optimistic(pageProps, data) : void 0,
        onCancelToken: props.onCancelToken,
        onBefore: props.onBefore,
        onStart: props.onStart,
        onProgress: props.onProgress,
        onFinish: props.onFinish,
        onCancel: props.onCancel,
        onSuccess: async (...args) => {
          const result2 = await props.onSuccess?.(...args);
          props.onSubmitComplete?.(exposed);
          maybeReset(props.resetOnSuccess);
          if (props.setDefaultsOnSuccess === true) {
            defaults2();
          }
          return result2;
        },
        onError: (...args) => {
          props.onError?.(...args);
          maybeReset(props.resetOnError);
        },
        ...props.options
      };
      form.transform(() => props.transform(data)).submit(method2.value, url, submitOptions);
      form.transform(getTransformedData);
    };
    const reset = (...fields) => {
      resetFormFields(formElement.value, defaultData.value, fields);
      form.reset(...fields);
    };
    const clearErrors = (...fields) => {
      form.clearErrors(...fields);
    };
    const resetAndClearErrors = (...fields) => {
      clearErrors(...fields);
      reset(...fields);
    };
    const defaults2 = () => {
      defaultData.value = getFormData();
      isDirty.value = false;
    };
    const exposed = {
      get errors() {
        return form.errors;
      },
      get hasErrors() {
        return form.hasErrors;
      },
      get processing() {
        return form.processing;
      },
      get progress() {
        return form.progress;
      },
      get wasSuccessful() {
        return form.wasSuccessful;
      },
      get recentlySuccessful() {
        return form.recentlySuccessful;
      },
      get validating() {
        return form.validating;
      },
      clearErrors,
      resetAndClearErrors,
      setError: (fieldOrFields, maybeValue) => form.setError(typeof fieldOrFields === "string" ? { [fieldOrFields]: maybeValue } : fieldOrFields),
      get isDirty() {
        return isDirty.value;
      },
      reset,
      submit,
      defaults: defaults2,
      getData,
      getFormData,
      // Precognition
      touch: form.touch,
      valid: form.valid,
      invalid: form.invalid,
      touched: form.touched,
      validate: (field, config3) => form.validate(...UseFormUtils.mergeHeadersForValidation(field, config3, props.headers)),
      validator: () => form.validator()
    };
    expose(exposed);
    provide(FormContextKey, exposed);
    return () => {
      return h(
        "form",
        {
          ...attrs,
          ref: formElement,
          action: isUrlMethodPair(props.action) ? props.action.url : props.action,
          method: method2.value,
          onSubmit: (event) => {
            event.preventDefault();
            submit(event.submitter);
          },
          inert: props.disableWhileProcessing && form.processing
        },
        slots.default ? slots.default(exposed) : []
      );
    };
  }
});
function useFormContext() {
  return inject(FormContextKey);
}
function createForm() {
  return Form;
}
var form_default = Form;
function isUnaryTag(node) {
  return typeof node.type === "string" && [
    "area",
    "base",
    "br",
    "col",
    "embed",
    "hr",
    "img",
    "input",
    "keygen",
    "link",
    "meta",
    "param",
    "source",
    "track",
    "wbr"
  ].indexOf(node.type) > -1;
}
function renderTagStart(node) {
  node.props = node.props || {};
  node.props["data-inertia"] = node.props["head-key"] !== void 0 ? node.props["head-key"] : "";
  const attrs = Object.keys(node.props).reduce((carry, name) => {
    const value = String(node.props[name]);
    if (["key", "head-key"].includes(name)) {
      return carry;
    } else if (value === "") {
      return carry + ` ${name}`;
    } else {
      return carry + ` ${name}="${escape2(value)}"`;
    }
  }, "");
  return `<${String(node.type)}${attrs}>`;
}
function renderTagChildren(node) {
  const { children } = node;
  if (typeof children === "string") {
    return children;
  }
  if (Array.isArray(children)) {
    return children.reduce((html, child) => {
      return html + renderTag(child);
    }, "");
  }
  return "";
}
function isFunctionNode(node) {
  return typeof node.type === "function";
}
function isComponentNode(node) {
  return typeof node.type === "object";
}
function isCommentNode(node) {
  return /(comment|cmt)/i.test(node.type.toString());
}
function isFragmentNode(node) {
  return /(fragment|fgt|symbol\(\))/i.test(node.type.toString());
}
function isTextNode(node) {
  return /(text|txt)/i.test(node.type.toString());
}
function renderTag(node) {
  if (isTextNode(node)) {
    return String(node.children);
  } else if (isFragmentNode(node)) {
    return "";
  } else if (isCommentNode(node)) {
    return "";
  }
  let html = renderTagStart(node);
  if (node.children) {
    html += renderTagChildren(node);
  }
  if (!isUnaryTag(node)) {
    html += `</${String(node.type)}>`;
  }
  return html;
}
function addTitleElement(elements, title) {
  if (title && !elements.find((tag) => tag.startsWith("<title"))) {
    elements.push(`<title data-inertia="">${escape2(title)}</title>`);
  }
  return elements;
}
function renderNodes(nodes, title) {
  const elements = nodes.flatMap((node) => resolveNode(node)).map((node) => renderTag(node)).filter((node) => node);
  return addTitleElement(elements, title);
}
function resolveNode(node) {
  if (isFunctionNode(node)) {
    return resolveNode(node.type());
  } else if (isComponentNode(node)) {
    console.warn(`Using components in the <Head> component is not supported.`);
    return [];
  } else if (isTextNode(node) && node.children) {
    return node;
  } else if (isFragmentNode(node) && node.children) {
    return node.children.flatMap((child) => resolveNode(child));
  } else if (isCommentNode(node)) {
    return [];
  } else {
    return node;
  }
}
var Head = defineComponent({
  props: {
    title: {
      type: String,
      required: false
    }
  },
  setup(props, { slots }) {
    const provider = headManager.createProvider();
    onBeforeUnmount(() => {
      provider.disconnect();
    });
    return () => {
      provider.update(renderNodes(slots.default ? slots.default() : [], props.title));
    };
  }
});
var head_default = Head;
var resolveHTMLElement = (value, fallback) => {
  if (!value) {
    return fallback;
  }
  if (typeof value === "string") {
    return document.querySelector(value);
  }
  if (typeof value === "function") {
    return value() || null;
  }
  return fallback;
};
var InfiniteScroll = defineComponent({
  name: "InfiniteScroll",
  slots: Object,
  props: {
    data: {
      type: String,
      required: true
    },
    buffer: {
      type: Number,
      default: 0
    },
    onlyNext: {
      type: Boolean,
      default: false
    },
    onlyPrevious: {
      type: Boolean,
      default: false
    },
    as: {
      type: String,
      default: "div"
    },
    manual: {
      type: Boolean,
      default: false
    },
    manualAfter: {
      type: Number,
      default: 0
    },
    preserveUrl: {
      type: Boolean,
      default: false
    },
    reverse: {
      type: Boolean,
      default: false
    },
    autoScroll: {
      type: Boolean,
      default: void 0
    },
    itemsElement: {
      type: [String, Function, Object],
      default: null
    },
    startElement: {
      type: [String, Function, Object],
      default: null
    },
    endElement: {
      type: [String, Function, Object],
      default: null
    },
    params: {
      type: Object,
      default: () => ({})
    }
  },
  inheritAttrs: false,
  setup(props, { slots, attrs, expose }) {
    const itemsElementRef = ref(null);
    const startElementRef = ref(null);
    const endElementRef = ref(null);
    const itemsElement = computed(
      () => resolveHTMLElement(props.itemsElement, itemsElementRef.value)
    );
    const scrollableParent = computed(() => getScrollableParent(itemsElement.value));
    const startElement = computed(
      () => resolveHTMLElement(props.startElement, startElementRef.value)
    );
    const endElement = computed(() => resolveHTMLElement(props.endElement, endElementRef.value));
    const loadingPrevious = ref(false);
    const loadingNext = ref(false);
    const requestCount = ref(0);
    const hasPreviousPage = ref(false);
    const hasNextPage = ref(false);
    const syncStateFromDataManager = () => {
      requestCount.value = dataManager.getRequestCount();
      hasPreviousPage.value = dataManager.hasPrevious();
      hasNextPage.value = dataManager.hasNext();
    };
    const {
      dataManager,
      elementManager,
      flush: flushInfiniteScroll
    } = useInfiniteScroll({
      // Data
      getPropName: () => props.data,
      inReverseMode: () => props.reverse,
      shouldFetchNext: () => !props.onlyPrevious,
      shouldFetchPrevious: () => !props.onlyNext,
      shouldPreserveUrl: () => props.preserveUrl,
      getReloadOptions: () => props.params,
      // Elements
      getTriggerMargin: () => props.buffer,
      getStartElement: () => startElement.value,
      getEndElement: () => endElement.value,
      getItemsElement: () => itemsElement.value,
      getScrollableParent: () => scrollableParent.value,
      // Request callbacks
      onBeforePreviousRequest: () => loadingPrevious.value = true,
      onBeforeNextRequest: () => loadingNext.value = true,
      onCompletePreviousRequest: ({ completed }) => {
        loadingPrevious.value = false;
        if (completed) {
          syncStateFromDataManager();
        }
      },
      onCompleteNextRequest: ({ completed }) => {
        loadingNext.value = false;
        if (completed) {
          syncStateFromDataManager();
        }
      },
      onDataReset: syncStateFromDataManager
    });
    syncStateFromDataManager();
    if (typeof window === "undefined") {
      const scrollProp = usePage().scrollProps?.[props.data];
      if (scrollProp) {
        hasPreviousPage.value = !!scrollProp.previousPage;
        hasNextPage.value = !!scrollProp.nextPage;
      }
    }
    const autoLoad = computed(() => !manualMode.value);
    const manualMode = computed(
      () => props.manual || props.manualAfter > 0 && requestCount.value >= props.manualAfter
    );
    const scrollToBottom = () => {
      if (scrollableParent.value) {
        scrollableParent.value.scrollTo({
          top: scrollableParent.value.scrollHeight,
          behavior: "instant"
        });
      } else {
        window.scrollTo({
          top: document.body.scrollHeight,
          behavior: "instant"
        });
      }
    };
    onMounted(() => {
      elementManager.setupObservers();
      elementManager.processServerLoadedElements(dataManager.getLastLoadedPage());
      const shouldAutoScroll = props.autoScroll !== void 0 ? props.autoScroll : props.reverse;
      if (shouldAutoScroll) {
        scrollToBottom();
      }
      if (autoLoad.value) {
        elementManager.enableTriggers();
      }
    });
    onUnmounted(flushInfiniteScroll);
    watch(
      () => [autoLoad.value, props.onlyNext, props.onlyPrevious],
      ([enabled]) => {
        enabled ? elementManager.enableTriggers() : elementManager.disableTriggers();
      }
    );
    expose({
      fetchNext: dataManager.fetchNext,
      fetchPrevious: dataManager.fetchPrevious,
      hasPrevious: dataManager.hasPrevious,
      hasNext: dataManager.hasNext
    });
    return () => {
      const renderElements = [];
      const sharedExposed = {
        loadingPrevious: loadingPrevious.value,
        loadingNext: loadingNext.value,
        hasPrevious: hasPreviousPage.value,
        hasNext: hasNextPage.value
      };
      if (!props.startElement) {
        const headerAutoMode = autoLoad.value && !props.onlyNext;
        const exposedPrevious = {
          loading: loadingPrevious.value,
          fetch: dataManager.fetchPrevious,
          autoMode: headerAutoMode,
          manualMode: !headerAutoMode,
          hasMore: hasPreviousPage.value,
          ...sharedExposed
        };
        renderElements.push(
          h(
            "div",
            { ref: startElementRef },
            slots.previous ? slots.previous(exposedPrevious) : loadingPrevious.value ? slots.loading?.(exposedPrevious) : void 0
          )
        );
      }
      renderElements.push(
        h(
          props.as,
          { ...attrs, ref: itemsElementRef },
          slots.default?.({
            loading: loadingPrevious.value || loadingNext.value,
            loadingPrevious: loadingPrevious.value,
            loadingNext: loadingNext.value
          })
        )
      );
      if (!props.endElement) {
        const footerAutoMode = autoLoad.value && !props.onlyPrevious;
        const exposedNext = {
          loading: loadingNext.value,
          fetch: dataManager.fetchNext,
          autoMode: footerAutoMode,
          manualMode: !footerAutoMode,
          hasMore: hasNextPage.value,
          ...sharedExposed
        };
        renderElements.push(
          h(
            "div",
            { ref: endElementRef },
            slots.next ? slots.next(exposedNext) : loadingNext.value ? slots.loading?.(exposedNext) : void 0
          )
        );
      }
      return h(Fragment, {}, props.reverse ? [...renderElements].reverse() : renderElements);
    };
  }
});
var infiniteScroll_default = InfiniteScroll;
var noop22 = () => {
};
var Link = defineComponent({
  name: "Link",
  props: {
    as: {
      type: [String, Object],
      default: "a"
    },
    data: {
      type: Object,
      default: () => ({})
    },
    href: {
      type: [String, Object],
      default: ""
    },
    method: {
      type: String,
      default: "get"
    },
    replace: {
      type: Boolean,
      default: false
    },
    preserveScroll: {
      type: [Boolean, String, Function],
      default: false
    },
    preserveState: {
      type: [Boolean, String, Function],
      default: null
    },
    preserveUrl: {
      type: Boolean,
      default: false
    },
    only: {
      type: Array,
      default: () => []
    },
    except: {
      type: Array,
      default: () => []
    },
    headers: {
      type: Object,
      default: () => ({})
    },
    queryStringArrayFormat: {
      type: String,
      default: "brackets"
    },
    async: {
      type: Boolean,
      default: false
    },
    prefetch: {
      type: [Boolean, String, Array],
      default: false
    },
    cacheFor: {
      type: [Number, String, Array],
      default: 0
    },
    onStart: {
      type: Function,
      default: noop22
    },
    onProgress: {
      type: Function,
      default: noop22
    },
    onFinish: {
      type: Function,
      default: noop22
    },
    onBefore: {
      type: Function,
      default: noop22
    },
    onCancel: {
      type: Function,
      default: noop22
    },
    onSuccess: {
      type: Function,
      default: noop22
    },
    onError: {
      type: Function,
      default: noop22
    },
    onCancelToken: {
      type: Function,
      default: noop22
    },
    onPrefetching: {
      type: Function,
      default: noop22
    },
    onPrefetched: {
      type: Function,
      default: noop22
    },
    cacheTags: {
      type: [String, Array],
      default: () => []
    },
    viewTransition: {
      type: [Boolean, Object],
      default: false
    },
    component: {
      type: String,
      default: null
    },
    instant: {
      type: Boolean,
      default: false
    },
    pageProps: {
      type: [Object, Function],
      default: null
    }
  },
  setup(props, { slots, attrs }) {
    const inFlightCount = ref(0);
    const hoverTimeout = ref();
    const prefetchModes = computed(() => {
      if (props.prefetch === true) {
        return ["hover"];
      }
      if (props.prefetch === false) {
        return [];
      }
      if (Array.isArray(props.prefetch)) {
        return props.prefetch;
      }
      return [props.prefetch];
    });
    const cacheForValue = computed(() => {
      if (props.cacheFor !== 0) {
        return props.cacheFor;
      }
      if (prefetchModes.value.length === 1 && prefetchModes.value[0] === "click") {
        return 0;
      }
      return config2.get("prefetch.cacheFor");
    });
    onMounted(() => {
      if (prefetchModes.value.includes("mount")) {
        prefetch();
      }
    });
    onUnmounted(() => {
      clearTimeout(hoverTimeout.value);
    });
    const method2 = computed(
      () => isUrlMethodPair(props.href) ? props.href.method : (props.method ?? "get").toLowerCase()
    );
    const as = computed(() => {
      if (typeof props.as !== "string" || props.as.toLowerCase() !== "a") {
        return props.as;
      }
      return method2.value !== "get" ? "button" : props.as.toLowerCase();
    });
    const mergeDataArray = computed(
      () => mergeDataIntoQueryString(
        method2.value,
        isUrlMethodPair(props.href) ? props.href.url : props.href,
        props.data || {},
        props.queryStringArrayFormat
      )
    );
    const href = computed(() => mergeDataArray.value[0]);
    const data = computed(() => mergeDataArray.value[1]);
    const resolvedComponent = computed(() => {
      if (props.component) {
        return props.component;
      }
      if (props.instant && isUrlMethodPair(props.href)) {
        return resolveUrlMethodPairComponent(props.href);
      }
      return null;
    });
    const elProps = computed(() => {
      if (as.value === "button") {
        return { type: "button" };
      }
      if (as.value === "a" || typeof as.value !== "string") {
        return { href: href.value };
      }
      return {};
    });
    const baseParams = computed(() => ({
      data: data.value,
      method: method2.value,
      replace: props.replace,
      preserveScroll: props.preserveScroll,
      preserveState: props.preserveState ?? method2.value !== "get",
      preserveUrl: props.preserveUrl,
      only: props.only,
      except: props.except,
      headers: props.headers,
      async: props.async,
      component: resolvedComponent.value,
      pageProps: props.pageProps
    }));
    const visitParams = computed(() => ({
      ...baseParams.value,
      viewTransition: props.viewTransition,
      onCancelToken: props.onCancelToken,
      onBefore: props.onBefore,
      onStart: (visit) => {
        inFlightCount.value++;
        props.onStart?.(visit);
      },
      onProgress: props.onProgress,
      onFinish: (visit) => {
        inFlightCount.value--;
        props.onFinish?.(visit);
      },
      onCancel: props.onCancel,
      onSuccess: props.onSuccess,
      onError: props.onError
    }));
    const prefetch = () => {
      router.prefetch(
        href.value,
        {
          ...baseParams.value,
          onPrefetching: props.onPrefetching,
          onPrefetched: props.onPrefetched
        },
        {
          cacheFor: cacheForValue.value,
          cacheTags: props.cacheTags
        }
      );
    };
    const regularEvents = {
      onClick: (event) => {
        if (shouldIntercept(event)) {
          event.preventDefault();
          router.visit(href.value, visitParams.value);
        }
      }
    };
    const prefetchHoverEvents = {
      onMouseenter: () => {
        hoverTimeout.value = setTimeout(() => {
          prefetch();
        }, config2.get("prefetch.hoverDelay"));
      },
      onMouseleave: () => {
        clearTimeout(hoverTimeout.value);
      },
      onClick: regularEvents.onClick
    };
    const prefetchClickEvents = {
      onMousedown: (event) => {
        if (shouldIntercept(event)) {
          event.preventDefault();
          prefetch();
        }
      },
      onKeydown: (event) => {
        if (shouldNavigate(event)) {
          event.preventDefault();
          prefetch();
        }
      },
      onMouseup: (event) => {
        if (shouldIntercept(event)) {
          event.preventDefault();
          router.visit(href.value, visitParams.value);
        }
      },
      onKeyup: (event) => {
        if (shouldNavigate(event)) {
          event.preventDefault();
          router.visit(href.value, visitParams.value);
        }
      },
      onClick: (event) => {
        if (shouldIntercept(event)) {
          event.preventDefault();
        }
      }
    };
    return () => {
      return h(
        as.value,
        {
          ...attrs,
          ...elProps.value,
          "data-loading": inFlightCount.value > 0 ? "" : void 0,
          ...(() => {
            if (prefetchModes.value.includes("hover")) {
              return prefetchHoverEvents;
            }
            if (prefetchModes.value.includes("click")) {
              return prefetchClickEvents;
            }
            return regularEvents;
          })()
        },
        slots
      );
    };
  }
});
var link_default = Link;
function useHttp(...args) {
  const { rememberKey, data, precognitionEndpoint } = UseFormUtils.parseUseFormArguments(...args);
  let abortController = null;
  let pendingOptimisticCallback = null;
  const {
    form: baseForm,
    setDefaults,
    getTransform,
    getPrecognitionEndpoint,
    markAsSuccessful,
    wasDefaultsCalledInOnSuccess,
    resetDefaultsCalledInOnSuccess,
    setRememberExcludeKeys,
    resetBeforeSubmit,
    finishProcessing,
    withAllErrors
  } = useFormState({
    data,
    rememberKey,
    precognitionEndpoint
  });
  const form = baseForm;
  form.response = null;
  const submit = async (method2, url, options) => {
    const onBefore = options.onBefore?.();
    if (onBefore === false) {
      return Promise.reject(new Error("Request cancelled by onBefore"));
    }
    resetDefaultsCalledInOnSuccess();
    resetBeforeSubmit();
    abortController = new AbortController();
    const cancelToken = {
      cancel: () => abortController?.abort()
    };
    options.onCancelToken?.(cancelToken);
    options.optimistic = options.optimistic ?? pendingOptimisticCallback ?? void 0;
    pendingOptimisticCallback = null;
    let snapshot;
    if (options.optimistic) {
      snapshot = cloneDeep(form.data());
      const optimisticData = options.optimistic(cloneDeep(snapshot));
      if (optimisticData) {
        Object.keys(optimisticData).forEach((key2) => {
          ;
          form[key2] = optimisticData[key2];
        });
      }
    }
    form.processing = true;
    options.onStart?.();
    const transform2 = getTransform();
    const transformedData = transform2(form.data());
    const useFormData = hasFiles2(transformedData);
    let requestUrl = url;
    let requestData;
    let contentType;
    if (method2 === "get") {
      const [urlWithParams] = mergeDataIntoQueryString(
        method2,
        url,
        transformedData
      );
      requestUrl = urlWithParams;
    } else {
      if (useFormData) {
        requestData = objectToFormData(transformedData);
      } else {
        requestData = JSON.stringify(transformedData);
        contentType = "application/json";
      }
    }
    try {
      const response = await http.getClient().request({
        method: method2,
        url: requestUrl,
        data: requestData,
        headers: {
          Accept: "application/json",
          ...contentType ? { "Content-Type": contentType } : {},
          ...options.headers
        },
        signal: abortController.signal,
        onUploadProgress: (event) => {
          form.progress = event;
          options.onProgress?.(event);
        }
      });
      const responseData = response.data ? JSON.parse(response.data) : null;
      if (response.status >= 200 && response.status < 300) {
        markAsSuccessful();
        form.response = responseData;
        options.onSuccess?.(responseData, response);
        if (!wasDefaultsCalledInOnSuccess()) {
          setDefaults(cloneDeep(form.data()));
        }
        form.isDirty = false;
        return responseData;
      }
      throw new HttpResponseError2(`Request failed with status ${response.status}`, response, url);
    } catch (error) {
      if (snapshot) {
        Object.keys(snapshot).forEach((key2) => {
          ;
          form[key2] = snapshot[key2];
        });
      }
      if (error instanceof HttpResponseError2) {
        if (error.response.status === 422) {
          const responseData = JSON.parse(error.response.data);
          const validationErrors = responseData.errors || {};
          const processedErrors = withAllErrors.enabled() ? validationErrors : toSimpleValidationErrors(validationErrors);
          form.clearErrors().setError(processedErrors);
          options.onError?.(processedErrors);
        } else {
          options.onHttpException?.(error.response);
        }
        throw error;
      }
      if (error instanceof HttpCancelledError2 || error instanceof Error && error.name === "AbortError") {
        options.onCancel?.();
        throw new HttpCancelledError2("Request was cancelled", url);
      }
      options.onNetworkError?.(error instanceof Error ? error : new Error("Unknown error"));
      throw error;
    } finally {
      finishProcessing();
      abortController = null;
      options.onFinish?.();
    }
  };
  const createSubmitMethod = (method2) => async (url, options = {}) => {
    return submit(method2, url, options);
  };
  Object.assign(form, {
    submit(...args2) {
      const parsed = UseFormUtils.parseSubmitArguments(args2, getPrecognitionEndpoint());
      return submit(parsed.method, parsed.url, parsed.options);
    },
    get: createSubmitMethod("get"),
    post: createSubmitMethod("post"),
    put: createSubmitMethod("put"),
    patch: createSubmitMethod("patch"),
    delete: createSubmitMethod("delete"),
    cancel() {
      if (abortController) {
        abortController.abort();
      }
    },
    dontRemember(...keys2) {
      setRememberExcludeKeys(keys2);
      return form;
    },
    optimistic(callback) {
      pendingOptimisticCallback = callback;
      return form;
    },
    withAllErrors() {
      withAllErrors.enable();
      return form;
    }
  });
  const originalWithPrecognition = form.withPrecognition;
  form.withPrecognition = (...args2) => {
    originalWithPrecognition.call(form, ...args2);
    return form;
  };
  return getPrecognitionEndpoint() ? form : form;
}
function usePoll(interval, requestOptions = {}, options = {
  keepAlive: false,
  autoStart: true
}) {
  const { stop, start: start2, destroy } = router.poll(interval, requestOptions, {
    ...options,
    autoStart: false
  });
  onMounted(() => {
    if (options.autoStart ?? true) {
      start2();
    }
  });
  onUnmounted(() => {
    destroy();
  });
  return {
    stop,
    start: start2
  };
}
function usePrefetch(options = {}) {
  const isPrefetching = ref(false);
  const lastUpdatedAt = ref(null);
  const isPrefetched = ref(false);
  const cached = typeof window === "undefined" ? null : router.getCached(window.location.pathname, options);
  const inFlight = typeof window === "undefined" ? null : router.getPrefetching(window.location.pathname, options);
  lastUpdatedAt.value = cached?.staleTimestamp || null;
  isPrefetching.value = inFlight !== null;
  isPrefetched.value = cached !== null;
  let onPrefetchedListener;
  let onPrefetchingListener;
  onMounted(() => {
    onPrefetchingListener = router.on("prefetching", (e) => {
      if (e.detail.visit.url.pathname === window.location.pathname) {
        isPrefetching.value = true;
      }
    });
    onPrefetchedListener = router.on("prefetched", (e) => {
      if (e.detail.visit.url.pathname === window.location.pathname) {
        isPrefetching.value = false;
        isPrefetched.value = true;
      }
    });
  });
  onUnmounted(() => {
    onPrefetchedListener();
    onPrefetchingListener();
  });
  return {
    lastUpdatedAt,
    isPrefetching,
    isPrefetched,
    flush: () => router.flush(window.location.pathname, options)
  };
}
function useRemember(data, key2) {
  if (typeof data === "object" && data !== null && data.__rememberable === false) {
    return data;
  }
  const restored = router.restore(key2);
  const type = isReactive(data) ? reactive : ref;
  const hasCallbacks = typeof data.__remember === "function" && typeof data.__restore === "function";
  const remembered = type(
    restored === void 0 ? data : hasCallbacks ? data.__restore(cloneDeep(restored)) : cloneDeep(restored)
  );
  watch(
    remembered,
    (newValue) => {
      router.remember(cloneDeep(hasCallbacks ? data.__remember() : newValue), key2);
    },
    { immediate: true, deep: true }
  );
  return remembered;
}
var whenVisible_default = defineComponent({
  name: "WhenVisible",
  slots: Object,
  props: {
    data: {
      type: [String, Array]
    },
    params: {
      type: Object
    },
    buffer: {
      type: Number,
      default: 0
    },
    as: {
      type: String,
      default: "div"
    },
    always: {
      type: Boolean,
      default: false
    }
  },
  setup(props, { slots }) {
    const loaded = ref(false);
    const fetching = ref(false);
    const observer = ref(null);
    const elementRef = ref(null);
    const page22 = usePage();
    const keys2 = computed(() => {
      return props.data ? Array.isArray(props.data) ? props.data : [props.data] : [];
    });
    function getReloadParams() {
      const reloadParams = { preserveErrors: true, ...props.params };
      if (props.data) {
        reloadParams.only = Array.isArray(props.data) ? props.data : [props.data];
      }
      return reloadParams;
    }
    function registerObserver() {
      if (typeof window === "undefined") {
        return;
      }
      observer.value?.disconnect();
      observer.value = new IntersectionObserver(
        (entries) => {
          if (!entries[0].isIntersecting) {
            return;
          }
          if (fetching.value) {
            return;
          }
          if (!props.always && loaded.value) {
            return;
          }
          fetching.value = true;
          const reloadParams = getReloadParams();
          router.reload({
            ...reloadParams,
            onStart: (e) => {
              fetching.value = true;
              reloadParams.onStart?.(e);
            },
            onFinish: (e) => {
              loaded.value = true;
              fetching.value = false;
              reloadParams.onFinish?.(e);
              if (!props.always) {
                observer.value?.disconnect();
              }
            }
          });
        },
        {
          rootMargin: `${props.buffer}px`
        }
      );
      if (elementRef.value) {
        observer.value.observe(elementRef.value);
      }
    }
    watch(
      () => keys2.value.map((key2) => get(page22.props, key2)),
      () => {
        const exists = keys2.value.length > 0 && keys2.value.every((key2) => get(page22.props, key2) !== void 0);
        loaded.value = exists;
        if (exists && !props.always) {
          return;
        }
        if (!observer.value || !exists) {
          nextTick(registerObserver);
        }
      },
      { immediate: true }
    );
    onUnmounted(() => {
      observer.value?.disconnect();
    });
    return () => {
      const els = [];
      if (props.always || !loaded.value) {
        els.push(h(props.as, { ref: elementRef }));
      }
      if (!loaded.value) {
        els.push(slots.fallback ? slots.fallback({}) : null);
      } else if (slots.default) {
        els.push(slots.default({ fetching: fetching.value }));
      }
      return els;
    };
  }
});
var config2 = config.extend({});
export {
  app_default as App,
  deferred_default as Deferred,
  form_default as Form,
  head_default as Head,
  infiniteScroll_default as InfiniteScroll,
  link_default as Link,
  whenVisible_default as WhenVisible,
  config2 as config,
  createForm,
  createInertiaApp,
  http,
  progress,
  resetLayoutProps,
  router,
  setLayoutProps,
  useForm,
  useFormContext,
  useHttp,
  usePage,
  usePoll,
  usePrefetch,
  useRemember
};
//# sourceMappingURL=@inertiajs_vue3.js.map
