import { Bt as onUnmounted, Gn as reactive, It as onMounted, Ln as isReactive, Mt as onBeforeUnmount, N as Fragment, St as inject, Vn as markRaw, W as computed, Wt as provide, Xn as shallowRef, _n as watch, kt as nextTick, mt as h, o as createApp, qn as ref, rt as defineComponent, s as createSSRApp } from "./vue.runtime.esm-bundler-Cb0HG1GX.js";
//#region node_modules/es-toolkit/dist/compat/predicate/isSymbol.mjs
/**
* Check whether a value is a symbol.
*
* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `symbol`.
*
* @param value The value to check.
* @returns Returns `true` if `value` is a symbol, else `false`.
* @example
* isSymbol(Symbol.iterator);
* // => true
*
* isSymbol('abc');
* // => false
*/
function isSymbol(value) {
	return typeof value === "symbol" || value instanceof Symbol;
}
//#endregion
//#region 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 || (function() {
	return this;
})();
//#endregion
//#region node_modules/es-toolkit/dist/function/debounce.mjs
/**
* Creates a debounced function that delays invoking the provided function until after `debounceMs` milliseconds
* have elapsed since the last time the debounced function was invoked. The debounced function also has a `cancel`
* method to cancel any pending execution.
*
* @template F - The type of function.
* @param func - The function to debounce.
* @param debounceMs - The number of milliseconds to delay.
* @param options - The options object
* @param options.signal - An optional AbortSignal to cancel the debounced function.
* @returns A new debounced function with a `cancel` method.
*
* @example
* const debouncedFunction = debounce(() => {
*   console.log('Function executed');
* }, 1000);
*
* // Will log 'Function executed' after 1 second if not called again in that time
* debouncedFunction();
*
* // Will not log anything as the previous call is canceled
* debouncedFunction.cancel();
*
* // With AbortSignal
* const controller = new AbortController();
* const signal = controller.signal;
* const debouncedWithSignal = debounce(() => {
*  console.log('Function executed');
* }, 1000, { signal });
*
* debouncedWithSignal();
*
* // Will cancel the debounced function call
* controller.abort();
*/
function debounce$2(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 invoke = () => {
		if (pendingArgs !== null) {
			func.apply(pendingThis, pendingArgs);
			pendingThis = void 0;
			pendingArgs = null;
		}
	};
	const onTimerEnd = () => {
		if (trailing) invoke();
		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 = () => {
		invoke();
	};
	const debounced = function(...args) {
		if (signal?.aborted) return;
		pendingThis = this;
		pendingArgs = args;
		const isFirstCall = timeoutId == null;
		schedule();
		if (leading && isFirstCall) invoke();
	};
	debounced.schedule = schedule;
	debounced.cancel = cancel;
	debounced.flush = flush;
	signal?.addEventListener("abort", cancel, { once: true });
	return debounced;
}
//#endregion
//#region node_modules/es-toolkit/dist/function/noop.mjs
/**
* A no-operation function that does nothing.
* This can be used as a placeholder or default function.
*
* @example
* noop(); // Does nothing
*
* @returns This function does not return anything.
*/
function noop$2() {}
//#endregion
//#region node_modules/es-toolkit/dist/predicate/isPrimitive.mjs
/**
* Checks whether a value is a JavaScript primitive.
* JavaScript primitives include null, undefined, strings, numbers, booleans, symbols, and bigints.
*
* @param value The value to check.
* @returns Returns true if `value` is a primitive, false otherwise.
*
* @example
* isPrimitive(null); // true
* isPrimitive(undefined); // true
* isPrimitive('123'); // true
* isPrimitive(false); // true
* isPrimitive(true); // true
* isPrimitive(Symbol('a')); // true
* isPrimitive(123n); // true
* isPrimitive({}); // false
* isPrimitive(new Date()); // false
* isPrimitive(new Map()); // false
* isPrimitive(new Set()); // false
* isPrimitive([1, 2, 3]); // false
*/
function isPrimitive(value) {
	return value == null || typeof value !== "object" && typeof value !== "function";
}
//#endregion
//#region node_modules/es-toolkit/dist/predicate/isTypedArray.mjs
/**
* Checks if a value is a TypedArray.
* @param x The value to check.
* @returns Returns true if `x` is a TypedArray, false otherwise.
*
* @example
* const arr = new Uint8Array([1, 2, 3]);
* isTypedArray(arr); // true
*
* const regularArray = [1, 2, 3];
* isTypedArray(regularArray); // false
*
* const buffer = new ArrayBuffer(16);
* isTypedArray(buffer); // false
*/
function isTypedArray$1(x) {
	return ArrayBuffer.isView(x) && !(x instanceof DataView);
}
//#endregion
//#region node_modules/es-toolkit/dist/object/clone.mjs
/**
* Creates a shallow clone of the given object.
*
* @template T - The type of the object.
* @param obj - The object to clone.
* @returns A shallow clone of the given object.
*
* @example
* // Clone a primitive value
* const num = 29;
* const clonedNum = clone(num);
* console.log(clonedNum); // 29
* console.log(clonedNum === num); // true
*
* @example
* // Clone an array
* const arr = [1, 2, 3];
* const clonedArr = clone(arr);
* console.log(clonedArr); // [1, 2, 3]
* console.log(clonedArr === arr); // false
*
* @example
* // Clone an object
* const obj = { a: 1, b: 'es-toolkit', c: [1, 2, 3] };
* const clonedObj = clone(obj);
* console.log(clonedObj); // { a: 1, b: 'es-toolkit', c: [1, 2, 3] }
* console.log(clonedObj === obj); // false
*/
function clone(obj) {
	if (isPrimitive(obj)) return obj;
	if (Array.isArray(obj) || isTypedArray$1(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;
}
//#endregion
//#region node_modules/es-toolkit/dist/predicate/isBuffer.mjs
/**
* Checks if the given value is a Buffer instance.
*
* This function tests whether the provided value is an instance of Buffer.
* It returns `true` if the value is a Buffer, and `false` otherwise.
*
* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to `Buffer`.
*
* @param x - The value to check if it is a Buffer.
* @returns Returns `true` if `x` is a Buffer, else `false`.
*
* @example
* const buffer = Buffer.from("test");
* console.log(isBuffer(buffer)); // true
*
* const notBuffer = "not a buffer";
* console.log(isBuffer(notBuffer)); // false
*/
function isBuffer(x) {
	return typeof globalThis_.Buffer !== "undefined" && globalThis_.Buffer.isBuffer(x);
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/_internal/getSymbols.mjs
function getSymbols(object) {
	return Object.getOwnPropertySymbols(object).filter((symbol) => Object.prototype.propertyIsEnumerable.call(object, symbol));
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/_internal/getTag.mjs
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {T} value The value to query.
* @returns {string} Returns the `Object.prototype.toString.call` result.
*/
function getTag(value) {
	if (value == null) return value === void 0 ? "[object Undefined]" : "[object Null]";
	return Object.prototype.toString.call(value);
}
//#endregion
//#region 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]";
//#endregion
//#region node_modules/es-toolkit/dist/object/cloneDeepWith.mjs
/**
* Deeply clones the given object.
*
* You can customize the deep cloning process using the `cloneValue` function.
* The function takes the current value `value`, the property name `key`, and the entire object `obj` as arguments.
* If the function returns a value, that value is used;
* if it returns `undefined`, the default cloning method is used.
*
* @template T - The type of the object.
* @param obj - The object to clone.
* @param [cloneValue] - A function to customize the cloning process.
* @returns A deep clone of the given object.
*
* @example
* // Clone a primitive value
* const num = 29;
* const clonedNum = cloneDeepWith(num);
* console.log(clonedNum); // 29
* console.log(clonedNum === num); // true
*
* @example
* // Clone an object with a customizer
* const obj = { a: 1, b: 2 };
* const clonedObj = cloneDeepWith(obj, (value) => {
*   if (typeof value === 'number') {
*     return value * 2; // Double the number
*   }
* });
* console.log(clonedObj); // { a: 2, b: 4 }
* console.log(clonedObj === obj); // false
*
* @example
* // Clone an array with a customizer
* const arr = [1, 2, 3];
* const clonedArr = cloneDeepWith(arr, (value) => {
*   return value + 1; // Increment each value
* });
* console.log(clonedArr); // [2, 3, 4]
* console.log(clonedArr === arr); // false
*/
function cloneDeepWith$1(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 result = new Array(valueToClone.length);
		stack.set(valueToClone, result);
		for (let i = 0; i < valueToClone.length; i++) result[i] = cloneDeepWithImpl(valueToClone[i], i, objectToClone, stack, cloneValue);
		if (Object.hasOwn(valueToClone, "index")) result.index = valueToClone.index;
		if (Object.hasOwn(valueToClone, "input")) result.input = valueToClone.input;
		return result;
	}
	if (valueToClone instanceof Date) return new Date(valueToClone.getTime());
	if (valueToClone instanceof RegExp) {
		const result = new RegExp(valueToClone.source, valueToClone.flags);
		result.lastIndex = valueToClone.lastIndex;
		return result;
	}
	if (valueToClone instanceof Map) {
		const result = /* @__PURE__ */ new Map();
		stack.set(valueToClone, result);
		for (const [key, value] of valueToClone) result.set(key, cloneDeepWithImpl(value, key, objectToClone, stack, cloneValue));
		return result;
	}
	if (valueToClone instanceof Set) {
		const result = /* @__PURE__ */ new Set();
		stack.set(valueToClone, result);
		for (const value of valueToClone) result.add(cloneDeepWithImpl(value, void 0, objectToClone, stack, cloneValue));
		return result;
	}
	if (isBuffer(valueToClone)) return valueToClone.subarray();
	if (isTypedArray$1(valueToClone)) {
		const result = new (Object.getPrototypeOf(valueToClone)).constructor(valueToClone.length);
		stack.set(valueToClone, result);
		for (let i = 0; i < valueToClone.length; i++) result[i] = cloneDeepWithImpl(valueToClone[i], i, objectToClone, stack, cloneValue);
		return result;
	}
	if (valueToClone instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && valueToClone instanceof SharedArrayBuffer) return valueToClone.slice(0);
	if (valueToClone instanceof DataView) {
		const result = new DataView(valueToClone.buffer.slice(0), valueToClone.byteOffset, valueToClone.byteLength);
		stack.set(valueToClone, result);
		copyProperties(result, valueToClone, objectToClone, stack, cloneValue);
		return result;
	}
	if (typeof File !== "undefined" && valueToClone instanceof File) {
		const result = new File([valueToClone], valueToClone.name, { type: valueToClone.type });
		stack.set(valueToClone, result);
		copyProperties(result, valueToClone, objectToClone, stack, cloneValue);
		return result;
	}
	if (typeof Blob !== "undefined" && valueToClone instanceof Blob) {
		const result = new Blob([valueToClone], { type: valueToClone.type });
		stack.set(valueToClone, result);
		copyProperties(result, valueToClone, objectToClone, stack, cloneValue);
		return result;
	}
	if (valueToClone instanceof Error) {
		const result = structuredClone(valueToClone);
		stack.set(valueToClone, result);
		result.message = valueToClone.message;
		result.name = valueToClone.name;
		result.stack = valueToClone.stack;
		result.cause = valueToClone.cause;
		result.constructor = valueToClone.constructor;
		copyProperties(result, valueToClone, objectToClone, stack, cloneValue);
		return result;
	}
	if (valueToClone instanceof Boolean) {
		const result = new Boolean(valueToClone.valueOf());
		stack.set(valueToClone, result);
		copyProperties(result, valueToClone, objectToClone, stack, cloneValue);
		return result;
	}
	if (valueToClone instanceof Number) {
		const result = new Number(valueToClone.valueOf());
		stack.set(valueToClone, result);
		copyProperties(result, valueToClone, objectToClone, stack, cloneValue);
		return result;
	}
	if (valueToClone instanceof String) {
		const result = new String(valueToClone.valueOf());
		stack.set(valueToClone, result);
		copyProperties(result, valueToClone, objectToClone, stack, cloneValue);
		return result;
	}
	if (typeof valueToClone === "object" && isCloneableObject(valueToClone)) {
		const result = Object.create(Object.getPrototypeOf(valueToClone));
		stack.set(valueToClone, result);
		copyProperties(result, valueToClone, objectToClone, stack, cloneValue);
		return result;
	}
	return valueToClone;
}
function copyProperties(target, source, objectToClone = target, stack, cloneValue) {
	const keys = [...Object.keys(source), ...getSymbols(source)];
	for (let i = 0; i < keys.length; i++) {
		const key = keys[i];
		const descriptor = Object.getOwnPropertyDescriptor(target, key);
		if (descriptor == null || descriptor.writable) target[key] = cloneDeepWithImpl(source[key], key, 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;
	}
}
//#endregion
//#region node_modules/es-toolkit/dist/object/cloneDeep.mjs
/**
* Creates a deep clone of the given object.
*
* @template T - The type of the object.
* @param obj - The object to clone.
* @returns A deep clone of the given object.
*
* @example
* // Clone a primitive value
* const num = 29;
* const clonedNum = cloneDeep(num);
* console.log(clonedNum); // 29
* console.log(clonedNum === num); // true
*
* @example
* // Clone an array
* const arr = [1, 2, 3];
* const clonedArr = cloneDeep(arr);
* console.log(clonedArr); // [1, 2, 3]
* console.log(clonedArr === arr); // false
*
* @example
* // Clone an array with nested objects
* const arr = [1, { a: 1 }, [1, 2, 3]];
* const clonedArr = cloneDeep(arr);
* arr[1].a = 2;
* console.log(arr); // [1, { a: 2 }, [1, 2, 3]]
* console.log(clonedArr); // [1, { a: 1 }, [1, 2, 3]]
* console.log(clonedArr === arr); // false
*
* @example
* // Clone an object
* const obj = { a: 1, b: 'es-toolkit', c: [1, 2, 3] };
* const clonedObj = cloneDeep(obj);
* console.log(clonedObj); // { a: 1, b: 'es-toolkit', c: [1, 2, 3] }
* console.log(clonedObj === obj); // false
*
* @example
* // Clone an object with nested objects
* const obj = { a: 1, b: { c: 1 } };
* const clonedObj = cloneDeep(obj);
* obj.b.c = 2;
* console.log(obj); // { a: 1, b: { c: 2 } }
* console.log(clonedObj); // { a: 1, b: { c: 1 } }
* console.log(clonedObj === obj); // false
*/
function cloneDeep$1(obj) {
	return cloneDeepWithImpl(obj, void 0, obj, /* @__PURE__ */ new Map(), void 0);
}
//#endregion
//#region node_modules/es-toolkit/dist/predicate/isPlainObject.mjs
/**
* Checks if a given value is a plain object.
*
* @param value - The value to check.
* @returns True if the value is a plain object, otherwise false.
*
* @example
* ```typescript
* // ✅👇 True
*
* isPlainObject({ });                       // ✅
* isPlainObject({ key: 'value' });          // ✅
* isPlainObject({ key: new Date() });       // ✅
* isPlainObject(new Object());              // ✅
* isPlainObject(Object.create(null));       // ✅
* isPlainObject({ nested: { key: true} });  // ✅
* isPlainObject(new Proxy({}, {}));         // ✅
* isPlainObject({ [Symbol('tag')]: 'A' });  // ✅
*
* // ✅👇 (cross-realms, node context, workers, ...)
* const runInNewContext = await import('node:vm').then(
*     (mod) => mod.runInNewContext
* );
* isPlainObject(runInNewContext('({})'));   // ✅
*
* // ❌👇 False
*
* class Test { };
* isPlainObject(new Test())           // ❌
* isPlainObject(10);                  // ❌
* isPlainObject(null);                // ❌
* isPlainObject('hello');             // ❌
* isPlainObject([]);                  // ❌
* isPlainObject(new Date());          // ❌
* isPlainObject(new Uint8Array([1])); // ❌
* isPlainObject(Buffer.from('ABC'));  // ❌
* isPlainObject(Promise.resolve({})); // ❌
* isPlainObject(Object.create({}));   // ❌
* isPlainObject(new (class Cls {}));  // ❌
* isPlainObject(globalThis);          // ❌,
* ```
*/
function isPlainObject$2(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]";
}
//#endregion
//#region node_modules/es-toolkit/dist/_internal/isUnsafeProperty.mjs
/**
* Checks if a property key is unsafe to modify directly.
*
* This function is used in functions like `merge` to prevent prototype pollution attacks
* by identifying property keys that could modify the object's prototype chain or constructor.
*
* @param key - The property key to check
* @returns `true` if the property is unsafe to modify directly, `false` otherwise
* @internal
*/
function isUnsafeProperty(key) {
	return key === "__proto__";
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/predicate/isPlainObject.mjs
/**
* Checks if a given value is a plain object.
*
* A plain object is an object created by the `{}` literal, `new Object()`, or
* `Object.create(null)`.
*
* This function also handles objects with custom
* `Symbol.toStringTag` properties.
*
* `Symbol.toStringTag` is a built-in symbol that a constructor can use to customize the
* default string description of objects.
*
* @param [object] - The value to check.
* @returns True if the value is a plain object, otherwise false.
*
* @example
* console.log(isPlainObject({})); // true
* console.log(isPlainObject([])); // false
* console.log(isPlainObject(null)); // false
* console.log(isPlainObject(Object.create(null))); // true
* console.log(isPlainObject(new Map())); // false
*/
function isPlainObject$1(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;
}
//#endregion
//#region node_modules/es-toolkit/dist/_internal/isEqualsSameValueZero.mjs
/**
* Performs a `SameValueZero` comparison between two values to determine if they are equivalent.
*
* @param {any} value - The value to compare.
* @param {any} other - The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*
* @example
* eq(1, 1); // true
* eq(0, -0); // true
* eq(NaN, NaN); // true
* eq('a', Object('a')); // false
*/
function isEqualsSameValueZero(value, other) {
	return value === other || Number.isNaN(value) && Number.isNaN(other);
}
//#endregion
//#region node_modules/es-toolkit/dist/predicate/isEqualWith.mjs
/**
* Compares two values for equality using a custom comparison function.
*
* The custom function allows for fine-tuned control over the comparison process. If it returns a boolean, that result determines the equality. If it returns undefined, the function falls back to the default equality comparison.
*
* This function also uses the custom equality function to compare values inside objects,
* arrays, maps, sets, and other complex structures, ensuring a deep comparison.
*
* This approach provides flexibility in handling complex comparisons while maintaining efficient default behavior for simpler cases.
*
* The custom comparison function can take up to six parameters:
* - `x`: The value from the first object `a`.
* - `y`: The value from the second object `b`.
* - `property`: The property key used to get `x` and `y`.
* - `xParent`: The parent of the first value `x`.
* - `yParent`: The parent of the second value `y`.
* - `stack`: An internal stack (Map) to handle circular references.
*
* @param a - The first value to compare.
* @param b - The second value to compare.
* @param areValuesEqual - A function to customize the comparison.
*   If it returns a boolean, that result will be used. If it returns undefined,
*   the default equality comparison will be used.
* @returns `true` if the values are equal according to the customizer, otherwise `false`.
*
* @example
* const customizer = (a, b) => {
*   if (typeof a === 'string' && typeof b === 'string') {
*     return a.toLowerCase() === b.toLowerCase();
*   }
* };
* isEqualWith('Hello', 'hello', customizer); // true
* isEqualWith({ a: 'Hello' }, { a: 'hello' }, customizer); // true
* isEqualWith([1, 2, 3], [1, 2, 3], customizer); // true
*/
function isEqualWith(a, b, areValuesEqual) {
	return isEqualWithImpl(a, b, void 0, void 0, void 0, void 0, areValuesEqual);
}
function isEqualWithImpl(a, b, property, aParent, bParent, stack, areValuesEqual) {
	const result = areValuesEqual(a, b, property, aParent, bParent, stack);
	if (result !== void 0) return result;
	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 [key, value] of a.entries()) if (!b.has(key) || !isEqualWithImpl(value, b.get(key), key, 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$2(a) && isPlainObject$2(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);
	}
}
//#endregion
//#region node_modules/es-toolkit/dist/predicate/isEqual.mjs
/**
* Checks if two values are equal, including support for `Date`, `RegExp`, and deep object comparison.
*
* @param a - The first value to compare.
* @param b - The second value to compare.
* @returns `true` if the values are equal, otherwise `false`.
*
* @example
* isEqual(1, 1); // true
* isEqual({ a: 1 }, { a: 1 }); // true
* isEqual(/abc/g, /abc/g); // true
* isEqual(new Date('2020-01-01'), new Date('2020-01-01')); // true
* isEqual([1, 2, 3], [1, 2, 3]); // true
*/
function isEqual(a, b) {
	return isEqualWith(a, b, noop$2);
}
//#endregion
//#region node_modules/es-toolkit/dist/predicate/isLength.mjs
/**
* Checks if a given value is a valid length.
*
* A valid length is of type `number`, is a non-negative integer, and is less than or equal to
* JavaScript's maximum safe integer (`Number.MAX_SAFE_INTEGER`).
* It returns `true` if the value is a valid length, and `false` otherwise.
*
* This function can also serve as a type predicate in TypeScript, narrowing the type of the
* argument to a valid length (`number`).
*
* @param value The value to check.
* @returns Returns `true` if `value` is a valid length, else `false`.
*
* @example
* isLength(0); // true
* isLength(42); // true
* isLength(-1); // false
* isLength(1.5); // false
* isLength(Number.MAX_SAFE_INTEGER); // true
* isLength(Number.MAX_SAFE_INTEGER + 1); // false
*/
function isLength(value) {
	return Number.isSafeInteger(value) && value >= 0;
}
//#endregion
//#region node_modules/es-toolkit/dist/string/escape.mjs
var htmlEscapes = {
	"&": "&amp;",
	"<": "&lt;",
	">": "&gt;",
	"\"": "&quot;",
	"'": "&#39;"
};
/**
* Converts the characters "&", "<", ">", '"', and "'" in `str` to their corresponding HTML entities.
* For example, "<" becomes "&lt;".
*
* @param str  The string to escape.
* @returns Returns the escaped string.
*
* @example
* escape('This is a <div> element.'); // returns 'This is a &lt;div&gt; element.'
* escape('This is a "quote"'); // returns 'This is a &quot;quote&quot;'
* escape("This is a 'quote'"); // returns 'This is a &#39;quote&#39;'
* escape('This is a & symbol'); // returns 'This is a &amp; symbol'
*/
function escape$1(str) {
	return str.replace(/[&<>"']/g, (match) => htmlEscapes[match]);
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/predicate/isArrayLike.mjs
/**
* Checks if `value` is array-like.
*
* @param value The value to check.
* @returns Returns `true` if `value` is array-like, else `false`.
*
* @example
* isArrayLike([1, 2, 3]); // true
* isArrayLike('abc'); // true
* isArrayLike({ 0: 'a', length: 1 }); // true
* isArrayLike({}); // false
* isArrayLike(null); // false
* isArrayLike(undefined); // false
*/
function isArrayLike(value) {
	return value != null && typeof value !== "function" && isLength(value.length);
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/util/toString.mjs
/**
* Converts `value` to a string.
*
* An empty string is returned for `null` and `undefined` values.
* The sign of `-0` is preserved.
*
* @param value - The value to convert.
* @returns Returns the converted string.
*
* @example
* toString(null) // returns ''
* toString(undefined) // returns ''
* toString(-0) // returns '-0'
* toString([1, 2, -0]) // returns '1,2,-0'
* toString([Symbol('a'), Symbol('b')]) // returns 'Symbol(a),Symbol(b)'
*/
function toString(value) {
	if (value == null) return "";
	if (typeof value === "string") return value;
	if (Array.isArray(value)) return value.map(toString).join(",");
	const result = String(value);
	if (result === "0" && Object.is(Number(value), -0)) return "-0";
	return result;
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/_internal/toKey.mjs
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
	if (typeof value === "string" || typeof value === "symbol") return value;
	if (Object.is(value?.valueOf?.(), -0)) return "-0";
	return String(value);
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/util/toPath.mjs
/**
* Converts a deep key string into an array of path segments.
*
* This function takes a string representing a deep key (e.g., 'a.b.c' or 'a[b][c]') and breaks it down into an array of strings, each representing a segment of the path.
*
* @param deepKey - The deep key string to convert.
* @returns An array of strings, each representing a segment of the path.
*
* Examples:
*
* toPath('a.b.c') // Returns ['a', 'b', 'c']
* toPath('a[b][c]') // Returns ['a', 'b', 'c']
* toPath('.a.b.c') // Returns ['', 'a', 'b', 'c']
* toPath('a["b.c"].d') // Returns ['a', 'b.c', 'd']
* toPath('') // Returns []
* toPath('.a[b].c.d[e]["f.g"].h') // Returns ['', 'a', 'b', 'c', 'd', 'e', 'f.g', 'h']
*/
function toPath(deepKey) {
	if (Array.isArray(deepKey)) return deepKey.map(toKey);
	if (typeof deepKey === "symbol") return [deepKey];
	deepKey = toString(deepKey);
	const result = [];
	const length = deepKey.length;
	if (length === 0) return result;
	let index = 0;
	let key = "";
	let quoteChar = "";
	let bracket = false;
	if (deepKey.charCodeAt(0) === 46) {
		result.push("");
		index++;
	}
	while (index < length) {
		const char = deepKey[index];
		if (quoteChar) if (char === "\\" && index + 1 < length) {
			index++;
			key += deepKey[index];
		} else if (char === quoteChar) quoteChar = "";
		else key += char;
		else if (bracket) if (char === "\"" || char === "'") quoteChar = char;
		else if (char === "]") {
			bracket = false;
			result.push(key);
			key = "";
		} else key += char;
		else if (char === "[") {
			bracket = true;
			if (key) {
				result.push(key);
				key = "";
			}
		} else if (char === ".") {
			if (key) {
				result.push(key);
				key = "";
			}
		} else key += char;
		index++;
	}
	if (key) result.push(key);
	return result;
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/_internal/isDeepKey.mjs
/**
* Checks if a given key is a deep key.
*
* A deep key is a string that contains a dot (.) or square brackets with a property accessor.
*
* @param {PropertyKey} key - The key to check.
* @returns {boolean} - Returns true if the key is a deep key, otherwise false.
*
* Examples:
*
* isDeepKey('a.b') // true
* isDeepKey('a[b]') // true
* isDeepKey('a') // false
* isDeepKey(123) // false
* isDeepKey('a.b.c') // true
* isDeepKey('a[b][c]') // true
*/
function isDeepKey(key) {
	switch (typeof key) {
		case "number":
		case "symbol": return false;
		case "string": return key.includes(".") || key.includes("[") || key.includes("]");
	}
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/object/get.mjs
/**
* Retrieves the value at a given path from an object. If the resolved value is undefined, the defaultValue is returned instead.
*
* @param object - The object to query.
* @param path - The path of the property to get.
* @param [defaultValue] - The value returned if the resolved value is undefined.
* @returns Returns the resolved value.
*
* @example
* const object = { a: { b: { c: 1 } } };
* get(object, 'a.b.c');
* // => 1
*
* get(object, ['a', 'b', 'c']);
* // => 1
*
* get(object, 'a.b.d', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
	if (object == null) return defaultValue;
	switch (typeof path) {
		case "string": {
			if (isUnsafeProperty(path)) return defaultValue;
			const result = object[path];
			if (result === void 0) if (isDeepKey(path)) return get(object, toPath(path), defaultValue);
			else return defaultValue;
			return result;
		}
		case "number":
		case "symbol": {
			if (typeof path === "number") path = toKey(path);
			const result = object[path];
			if (result === void 0) return defaultValue;
			return result;
		}
		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 result = object[path];
			if (result === void 0) return defaultValue;
			return result;
		}
	}
}
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;
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/predicate/isObject.mjs
/**
* Checks if the given value is an object. An object is a value that is
* not a primitive type (string, number, boolean, symbol, null, or undefined).
*
* This function tests whether the provided value is an object or not.
* It returns `true` if the value is an object, and `false` otherwise.
*
* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to an object value.
*
* @param value - The value to check if it is an object.
* @returns `true` if the value is an object, `false` otherwise.
*
* @example
* const value1 = {};
* const value2 = [1, 2, 3];
* const value3 = () => {};
* const value4 = null;
*
* console.log(isObject(value1)); // true
* console.log(isObject(value2)); // true
* console.log(isObject(value3)); // true
* console.log(isObject(value4)); // false
*/
function isObject(value) {
	return value !== null && (typeof value === "object" || typeof value === "function");
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/object/cloneDeepWith.mjs
/**
* Creates a deep clone of the given object using a customizer function.
*
* @template T - The type of the object.
* @param obj - The object to clone.
* @param [cloneValue] - A function to customize the cloning process.
* @returns A deep clone of the given object.
*
* @example
* // Clone a primitive value
* const num = 29;
* const clonedNum = cloneDeepWith(num);
* console.log(clonedNum); // 29
* console.log(clonedNum === num); // true
*
* @example
* // Clone an object with a customizer
* const obj = { a: 1, b: 2 };
* const clonedObj = cloneDeepWith(obj, (value) => {
*   if (typeof value === 'number') {
*     return value * 2; // Double the number
*   }
* });
* console.log(clonedObj); // { a: 2, b: 4 }
* console.log(clonedObj === obj); // false
*
* @example
* // Clone an array with a customizer
* const arr = [1, 2, 3];
* const clonedArr = cloneDeepWith(arr, (value) => {
*   return value + 1; // Increment each value
* });
* console.log(clonedArr); // [2, 3, 4]
* console.log(clonedArr === arr); // false
*/
function cloneDeepWith(obj, customizer) {
	return cloneDeepWith$1(obj, (value, key, object, stack) => {
		const cloned = customizer?.(value, key, object, stack);
		if (cloned !== void 0) return cloned;
		if (typeof obj !== "object") return;
		if (getTag(obj) === "[object Object]" && typeof obj.constructor !== "function") {
			const result = {};
			stack.set(obj, result);
			copyProperties(result, obj, object, stack);
			return result;
		}
		switch (Object.prototype.toString.call(obj)) {
			case numberTag:
			case stringTag:
			case booleanTag: {
				const result = new obj.constructor(obj?.valueOf());
				copyProperties(result, obj);
				return result;
			}
			case argumentsTag: {
				const result = {};
				copyProperties(result, obj);
				result.length = obj.length;
				result[Symbol.iterator] = obj[Symbol.iterator];
				return result;
			}
			default: return;
		}
	});
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/object/cloneDeep.mjs
/**
* Creates a deep clone of the given object.
*
* @template T - The type of the object.
* @param obj - The object to clone.
* @returns A deep clone of the given object.
*
* @example
* // Clone a primitive value
* const num = 29;
* const clonedNum = clone(num);
* console.log(clonedNum); // 29
* console.log(clonedNum === num); // true
*
* @example
* // Clone an array
* const arr = [1, 2, 3];
* const clonedArr = clone(arr);
* console.log(clonedArr); // [1, 2, 3]
* console.log(clonedArr === arr); // false
*
* @example
* // Clone an array with nested objects
* const arr = [1, { a: 1 }, [1, 2, 3]];
* const clonedArr = clone(arr);
* arr[1].a = 2;
* console.log(arr); // [2, { a: 2 }, [1, 2, 3]]
* console.log(clonedArr); // [1, { a: 1 }, [1, 2, 3]]
* console.log(clonedArr === arr); // false
*
* @example
* // Clone an object
* const obj = { a: 1, b: 'es-toolkit', c: [1, 2, 3] };
* const clonedObj = clone(obj);
* console.log(clonedObj); // { a: 1, b: 'es-toolkit', c: [1, 2, 3] }
* console.log(clonedObj === obj); // false
*
* @example
* // Clone an object with nested objects
* const obj = { a: 1, b: { c: 1 } };
* const clonedObj = clone(obj);
* obj.b.c = 2;
* console.log(obj); // { a: 1, b: { c: 2 } }
* console.log(clonedObj); // { a: 1, b: { c: 1 } }
* console.log(clonedObj === obj); // false
*/
function cloneDeep(obj) {
	return cloneDeepWith(obj);
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/predicate/isArguments.mjs
/**
* Checks if the given value is an arguments object.
*
* This function tests whether the provided value is an arguments object or not.
* It returns `true` if the value is an arguments object, and `false` otherwise.
*
* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to an arguments object.
*
* @param value - The value to test if it is an arguments object.
* @returns `true` if the value is an arguments, `false` otherwise.
*
* @example
* const args = (function() { return arguments; })();
* const strictArgs = (function() { 'use strict'; return arguments; })();
* const value = [1, 2, 3];
*
* console.log(isArguments(args)); // true
* console.log(isArguments(strictArgs)); // true
* console.log(isArguments(value)); // false
*/
function isArguments(value) {
	return value !== null && typeof value === "object" && getTag(value) === "[object Arguments]";
}
//#endregion
//#region 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);
	}
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/object/has.mjs
/**
* Checks if a given path exists within an object.
*
* You can provide the path as a single property key, an array of property keys,
* or a string representing a deep path.
*
* If the path is an index and the object is an array or an arguments object, the function will verify
* if the index is valid and within the bounds of the array or arguments object, even if the array or
* arguments object is sparse (i.e., not all indexes are defined).
*
* @param object - The object to query.
* @param path - The path to check. This can be a single property key,
*        an array of property keys, or a string representing a deep path.
* @returns Returns `true` if the path exists in the object, `false` otherwise.
*
* @example
*
* const obj = { a: { b: { c: 3 } } };
*
* has(obj, 'a'); // true
* has(obj, ['a', 'b']); // true
* has(obj, ['a', 'b', 'c']); // true
* has(obj, 'a.b.c'); // true
* has(obj, 'a.b.d'); // false
* has(obj, ['a', 'b', 'c', 'd']); // false
* has([], 0); // false
* has([1, 2, 3], 2); // true
* has([1, 2, 3], 5); // false
*/
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 key = resolvedPath[i];
		if (current == null || !Object.hasOwn(current, key)) {
			if (!((Array.isArray(current) || isArguments(current)) && isIndex(key) && key < current.length)) return false;
		}
		current = current[key];
	}
	return true;
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/predicate/isObjectLike.mjs
/**
* Checks if the given value is object-like.
*
* A value is object-like if its type is object and it is not null.
*
* This function can also serve as a type predicate in TypeScript, narrowing the type of the argument to an object-like value.
*
* @param value - The value to test if it is an object-like.
* @returns `true` if the value is an object-like, `false` otherwise.
*
* @example
* const value1 = { a: 1 };
* const value2 = [1, 2, 3];
* const value3 = 'abc';
* const value4 = () => {};
* const value5 = null;
*
* console.log(isObjectLike(value1)); // true
* console.log(isObjectLike(value2)); // true
* console.log(isObjectLike(value3)); // false
* console.log(isObjectLike(value4)); // false
* console.log(isObjectLike(value5)); // false
*/
function isObjectLike(value) {
	return typeof value === "object" && value !== null;
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/predicate/isArrayLikeObject.mjs
/**
* Checks if the given value is a non-primitive, array-like object.
*
* @param value The value to check.
* @returns `true` if the value is a non-primitive, array-like object, `false` otherwise.
*
* @example
* isArrayLikeObject([1, 2, 3]); // true
* isArrayLikeObject({ 0: 'a', length: 1 }); // true
* isArrayLikeObject('abc'); // false
* isArrayLikeObject(()=>{}); // false
*/
function isArrayLikeObject(value) {
	return isObjectLike(value) && isArrayLike(value);
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/_internal/isKey.mjs
/**  Matches any deep property path. (e.g. `a.b[0].c`)*/
var regexIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
/**  Matches any word character (alphanumeric & underscore).*/
var regexIsPlainProp = /^\w*$/;
/**
* Checks if `value` is a property name and not a property path. (It's ok that the `value` is not in the keys of the `object`)
* @param {unknown} value The value to check.
* @param {unknown} object The object to query.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*
* @example
* isKey('a', { a: 1 });
* // => true
*
* isKey('a.b', { a: { b: 2 } });
* // => false
*/
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);
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/_internal/assignValue.mjs
var assignValue = (object, key, value) => {
	const objValue = object[key];
	if (!(Object.hasOwn(object, key) && isEqualsSameValueZero(objValue, value)) || value === void 0 && !(key in object)) object[key] = value;
};
//#endregion
//#region node_modules/es-toolkit/dist/compat/object/updateWith.mjs
/**
* Updates the value at the specified path of the given object using an updater function and a customizer.
* If any part of the path does not exist, it will be created.
*
* @template T - The type of the object.
* @template R - The type of the return value.
* @param obj - The object to modify.
* @param path - The path of the property to update.
* @param updater - The function to produce the updated value.
* @param customizer - The function to customize the update process.
* @returns The modified object.
*
* @example
* const object = { 'a': [{ 'b': { 'c': 3 } }] };
* updateWith(object, 'a[0].b.c', (n) => n * n);
* // => { 'a': [{ 'b': { 'c': 9 } }] }
*/
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 key = toKey(resolvedPath[i]);
		if (isUnsafeProperty(key)) continue;
		let newValue;
		if (i === resolvedPath.length - 1) newValue = updateValue;
		else {
			const objValue = current[key];
			const customizerResult = customizer?.(objValue, key, obj);
			newValue = customizerResult !== void 0 ? customizerResult : isObject(objValue) ? objValue : isIndex(resolvedPath[i + 1]) ? [] : {};
		}
		assignValue(current, key, newValue);
		current = current[key];
	}
	return obj;
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/object/set.mjs
/**
* Sets the value at the specified path of the given object. If any part of the path does not exist, it will be created.
*
* @template T - The type of the object.
* @param obj - The object to modify.
* @param path - The path of the property to set.
* @param value - The value to set.
* @returns The modified object.
*
* @example
* // Set a value in a nested object
* const obj = { a: { b: { c: 3 } } };
* set(obj, 'a.b.c', 4);
* console.log(obj.a.b.c); // 4
*
* @example
* // Set a value in an array
* const arr = [1, 2, 3];
* set(arr, 1, 4);
* console.log(arr[1]); // 4
*
* @example
* // Create non-existent path and set value
* const obj = {};
* set(obj, 'a.b.c', 4);
* console.log(obj); // { a: { b: { c: 4 } } }
*/
function set(obj, path, value) {
	return updateWith(obj, path, () => value, () => void 0);
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/function/debounce.mjs
function debounce$1(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 result = void 0;
	let pendingAt = null;
	const _debounced = debounce$2(function(...args) {
		result = 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) {
				result = func.apply(this, args);
				pendingAt = Date.now();
				_debounced.cancel();
				_debounced.schedule();
				return result;
			}
		}
		_debounced.apply(this, args);
		return result;
	};
	const flush = () => {
		_debounced.flush();
		return result;
	};
	debounced.cancel = _debounced.cancel;
	debounced.flush = flush;
	return debounced;
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/predicate/isTypedArray.mjs
/**
* Checks if a value is a TypedArray.
* @param x The value to check.
* @returns Returns true if `x` is a TypedArray, false otherwise.
*
* @example
* const arr = new Uint8Array([1, 2, 3]);
* isTypedArray(arr); // true
*
* const regularArray = [1, 2, 3];
* isTypedArray(regularArray); // false
*
* const buffer = new ArrayBuffer(16);
* isTypedArray(buffer); // false
*/
function isTypedArray(x) {
	return isTypedArray$1(x);
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/object/mergeWith.mjs
/**
* Merges the properties of one or more source objects into the target object using a customizer function.
*
* This function performs a deep merge, recursively merging nested objects and arrays.
* If a property in the source object is an array or object and the corresponding property in the target object is also an array or object, they will be merged.
* If a property in the source object is `undefined`, it will not overwrite a defined property in the target object.
*
* You can provide a custom `merge` function to control how properties are merged. The `merge` function is called for each property that is being merged and receives the following arguments:
*
* - `targetValue`: The current value of the property in the target object.
* - `sourceValue`: The value of the property in the source object.
* - `key`: The key of the property being merged.
* - `target`: The target object.
* - `source`: The source object.
* - `stack`: A `Map` used to keep track of objects that have already been processed to handle circular references.
*
* The `merge` function should return the value to be set in the target object. If it returns `undefined`, a default deep merge will be applied for arrays and objects.
*
* The function can handle multiple source objects and will merge them all into the target object.
*
* @param object - The target object into which the source object properties will be merged. This object is modified in place.
* @param otherArgs - Additional source objects to merge into the target object, including the custom `merge` function.
* @returns The updated target object with properties from the source object(s) merged in.
*
* @example
* const target = { a: 1, b: 2 };
* const source = { b: 3, c: 4 };
*
* mergeWith(target, source, (targetValue, sourceValue) => {
*   if (typeof targetValue === 'number' && typeof sourceValue === 'number') {
*     return targetValue + sourceValue;
*   }
* });
* // Returns { a: 1, b: 5, c: 4 }
* @example
* const target = { a: [1], b: [2] };
* const source = { a: [3], b: [4] };
*
* const result = mergeWith(target, source, (objValue, srcValue) => {
*   if (Array.isArray(objValue)) {
*     return objValue.concat(srcValue);
*   }
* });
*
* expect(result).toEqual({ a: [1, 3], b: [2, 4] });
*/
function mergeWith(object, ...otherArgs) {
	const sources = otherArgs.slice(0, -1);
	const merge = otherArgs[otherArgs.length - 1];
	let result = object;
	for (let i = 0; i < sources.length; i++) {
		const source = sources[i];
		result = mergeWithDeep(result, source, merge, /* @__PURE__ */ new Map());
	}
	return result;
}
function mergeWithDeep(target, source, merge, 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 key = sourceKeys[i];
		if (isUnsafeProperty(key)) continue;
		let sourceValue = source[key];
		let targetValue = target[key];
		if (isArguments(sourceValue)) sourceValue = { ...sourceValue };
		if (isArguments(targetValue)) targetValue = { ...targetValue };
		if (isBuffer(sourceValue)) sourceValue = cloneDeep(sourceValue);
		if (Array.isArray(sourceValue)) if (Array.isArray(targetValue)) {
			const cloned = [];
			const targetKeys = Reflect.ownKeys(targetValue);
			for (let i = 0; i < targetKeys.length; i++) {
				const targetKey = targetKeys[i];
				cloned[targetKey] = targetValue[targetKey];
			}
			targetValue = cloned;
		} else if (isArrayLikeObject(targetValue)) {
			const cloned = [];
			for (let i = 0; i < targetValue.length; i++) cloned[i] = targetValue[i];
			targetValue = cloned;
		} else targetValue = [];
		const merged = merge(targetValue, sourceValue, key, target, source, stack);
		if (merged !== void 0) target[key] = merged;
		else if (Array.isArray(sourceValue)) target[key] = mergeWithDeep(targetValue, sourceValue, merge, stack);
		else if (isObjectLike(targetValue) && isObjectLike(sourceValue) && (isPlainObject$1(targetValue) || isPlainObject$1(sourceValue) || isTypedArray(targetValue) || isTypedArray(sourceValue))) target[key] = mergeWithDeep(targetValue, sourceValue, merge, stack);
		else if (targetValue == null && isPlainObject$1(sourceValue)) target[key] = mergeWithDeep({}, sourceValue, merge, stack);
		else if (targetValue == null && isTypedArray(sourceValue)) target[key] = cloneDeep(sourceValue);
		else if (targetValue === void 0 || sourceValue !== void 0) target[key] = sourceValue;
	}
	return target;
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/object/merge.mjs
/**
* Merges the properties of one or more source objects into the target object.
*
* This function performs a deep merge, recursively merging nested objects and arrays.
* If a property in the source object is an array or object and the corresponding property in the target object is also an array or object, they will be merged.
* If a property in the source object is `undefined`, it will not overwrite a defined property in the target object.
*
* The function can handle multiple source objects and will merge them all into the target object.
*
* @param object - The target object into which the source object properties will be merged. This object is modified in place.
* @param sources - The source objects whose properties will be merged into the target object.
* @returns The updated target object with properties from the source object(s) merged in.
*
* @example
* const target = { a: 1, b: { x: 1, y: 2 } };
* const source = { b: { y: 3, z: 4 }, c: 5 };
*
* const result = merge(target, source);
* console.log(result);
* // Output: { a: 1, b: { x: 1, y: 3, z: 4 }, c: 5 }
*
* @example
* const target = { a: [1, 2], b: { x: 1 } };
* const source = { a: [3], b: { y: 2 } };
*
* const result = merge(target, source);
* console.log(result);
* // Output: { a: [3], b: { x: 1, y: 2 } }
*
* @example
* const target = { a: null };
* const source = { a: [1, 2, 3] };
*
* const result = merge(target, source);
* console.log(result);
* // Output: { a: [1, 2, 3] }
*/
function merge(object, ...sources) {
	return mergeWith(object, ...sources, noop$2);
}
//#endregion
//#region node_modules/es-toolkit/dist/compat/string/escape.mjs
/**
* Converts the characters "&", "<", ">", '"', and "'" in `str` to their corresponding HTML entities.
* For example, "<" becomes "&lt;".
*
* @param str  The string to escape.
* @returns Returns the escaped string.
*
* @example
* escape('This is a <div> element.'); // returns 'This is a &lt;div&gt; element.'
* escape('This is a "quote"'); // returns 'This is a &quot;quote&quot;'
* escape("This is a 'quote'"); // returns 'This is a &#39;quote&#39;'
* escape('This is a & symbol'); // returns 'This is a &amp; symbol'
*/
function escape(string) {
	return escape$1(toString(string));
}
//#endregion
//#region node_modules/laravel-precognition/dist/form.js
/**
* Determine if the value is a file.
*/
var isFile$1 = (value) => typeof File !== "undefined" && value instanceof File || value instanceof Blob || typeof FileList !== "undefined" && value instanceof FileList && value.length > 0;
/**
* Determine if the payload has any files.
*
* @see https://github.com/inertiajs/inertia/blob/master/packages/core/src/files.ts
*/
var hasFiles$1 = (data) => {
	if (data instanceof FormData) return true;
	return isFile$1(data) || typeof data === "object" && data !== null && Object.values(data).some((value) => hasFiles$1(value));
};
//#endregion
//#region node_modules/laravel-precognition/dist/http/errors.js
/**
* Error thrown when the server responds with a 4xx or 5xx status code.
*/
var HttpResponseError$1 = class extends Error {
	response;
	constructor(response) {
		super(`HTTP error ${response.status}`);
		this.name = "HttpResponseError";
		this.response = response;
	}
};
/**
* Error thrown when a request is cancelled/aborted.
*/
var HttpCancelledError$1 = class extends Error {
	constructor(message = "Request was cancelled") {
		super(message);
		this.name = "HttpCancelledError";
	}
};
/**
* Error thrown when a network error occurs (e.g., no connection).
*/
var HttpNetworkError$1 = class extends Error {
	constructor(message = "Network error") {
		super(message);
		this.name = "HttpNetworkError";
	}
};
//#endregion
//#region node_modules/laravel-precognition/dist/http/url.js
/**
* Build a query string from params.
*/
function buildQueryString(params) {
	const searchParams = new URLSearchParams();
	Object.entries(params).forEach(([key, value]) => {
		if (value === void 0 || value === null) return;
		if (Array.isArray(value)) value.forEach((item) => searchParams.append(`${key}[]`, String(item)));
		else if (typeof value === "object") searchParams.append(key, JSON.stringify(value));
		else searchParams.append(key, String(value));
	});
	return searchParams.toString();
}
/**
* Build the full URL with base URL and query params.
*/
function buildUrl(url, baseURL, params) {
	if (baseURL && !url.startsWith("http://") && !url.startsWith("https://")) url = baseURL.replace(/\/$/, "") + "/" + url.replace(/^\//, "");
	if (params && Object.keys(params).length > 0) {
		const queryString = buildQueryString(params);
		if (queryString) url += (url.includes("?") ? "&" : "?") + queryString;
	}
	return url;
}
//#endregion
//#region node_modules/laravel-precognition/dist/http/fetchClient.js
/**
* Get the X-Requested-With header from Laravel's bootstrap config if available.
*/
function getAjaxHeader() {
	if (typeof window === "undefined") return null;
	return window.axios?.defaults?.headers?.common?.["X-Requested-With"] ?? null;
}
/**
* Convert data to FormData recursively.
*/
function toFormData(data, formData = new FormData(), parentKey = null) {
	for (const key in data) if (Object.prototype.hasOwnProperty.call(data, key)) appendToFormData(formData, parentKey ? `${parentKey}[${key}]` : key, data[key]);
	return formData;
}
function appendToFormData(formData, key, value) {
	if (Array.isArray(value)) return value.forEach((val, index) => appendToFormData(formData, `${key}[${index}]`, val));
	else if (value instanceof Date) return formData.append(key, value.toISOString());
	else if (typeof File !== "undefined" && value instanceof File) return formData.append(key, value, value.name);
	else if (value instanceof Blob) return formData.append(key, value);
	else if (typeof value === "boolean") return formData.append(key, value ? "1" : "0");
	else if (typeof value === "string") return formData.append(key, value);
	else if (typeof value === "number") return formData.append(key, `${value}`);
	else if (value === null || value === void 0) return formData.append(key, "");
	toFormData(value, formData, key);
}
/**
* Prepare the request body.
*/
function prepareBody(data, headers) {
	if (data === void 0 || data === null) return;
	if (data instanceof FormData) return data;
	if (typeof data === "object" && hasFiles$1(data)) return toFormData(data);
	if (typeof data === "object" || headers["Content-Type"]?.includes("application/json")) return JSON.stringify(data);
	return String(data);
}
/**
* Parse response headers into a plain object.
*/
function parseHeaders$1(headers) {
	const result = {};
	headers.forEach((value, key) => {
		result[key.toLowerCase()] = value;
	});
	return result;
}
/**
* Create a fetch-based HTTP client.
*/
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(config) {
			const url = buildUrl(config.url, config.baseURL, config.params);
			const method = config.method.toUpperCase();
			const headers = {};
			const ajaxHeader = getAjaxHeader();
			if (ajaxHeader) headers["X-Requested-With"] = ajaxHeader;
			if (config.data !== void 0 && !["GET", "DELETE"].includes(method)) {
				if (!(config.data instanceof FormData) && !hasFiles$1(config.data)) headers["Content-Type"] = "application/json";
			}
			if (config.headers) Object.entries(config.headers).forEach(([key, value]) => {
				if (value !== void 0) headers[key] = String(value);
			});
			const xsrfToken = getXsrfToken();
			if (xsrfToken && ![
				"GET",
				"HEAD",
				"OPTIONS"
			].includes(method)) headers[xsrfHeaderName] = xsrfToken;
			let signal = config.signal;
			let timeoutId;
			const timeout = config.timeout ?? 3e4;
			if (timeout > 0 && !signal) {
				const controller = new AbortController();
				signal = controller.signal;
				timeoutId = setTimeout(() => controller.abort(), timeout);
			}
			const body = ["GET", "DELETE"].includes(method) ? void 0 : prepareBody(config.data, headers);
			if (body instanceof FormData) delete headers["Content-Type"];
			try {
				const response = await fetch(url, {
					method,
					headers,
					body,
					signal,
					credentials: config.credentials ?? "same-origin"
				});
				if (timeoutId) clearTimeout(timeoutId);
				let data;
				if (response.headers.get("content-type")?.includes("application/json")) data = await response.json();
				else data = await response.text();
				const httpResponse = {
					status: response.status,
					data,
					headers: parseHeaders$1(response.headers)
				};
				if (!response.ok) throw new HttpResponseError$1(httpResponse);
				return httpResponse;
			} catch (error) {
				if (timeoutId) clearTimeout(timeoutId);
				if (error instanceof HttpResponseError$1) throw error;
				if (error instanceof DOMException && error.name === "AbortError") throw new HttpCancelledError$1();
				if (error instanceof TypeError) throw new HttpNetworkError$1(error.message);
				throw error;
			}
		}
	};
}
/**
* Default fetch HTTP client instance.
*/
var fetchHttpClient = createFetchClient();
//#endregion
//#region node_modules/laravel-precognition/dist/client.js
/**
* The configured HTTP client.
*/
var httpClient$1 = fetchHttpClient;
/**
* The configured base URL.
*/
var baseURL = void 0;
/**
* The configured default timeout.
*/
var timeout = void 0;
/**
* The configured credentials mode.
*/
var credentials = "same-origin";
/**
* The request fingerprint resolver.
*/
var requestFingerprintResolver = (config) => `${config.method}:${config.baseURL ?? baseURL ?? ""}${config.url}`;
/**
* The precognition success resolver.
*/
var successResolver = (response) => response.status === 204 && response.headers["precognition-success"] === "true";
/**
* The abort controller cache.
*/
var abortControllers = {};
/**
* The precognitive HTTP client instance.
*/
var client = {
	get: (url, data = {}, config = {}) => request(mergeConfig("get", url, data, config)),
	post: (url, data = {}, config = {}) => request(mergeConfig("post", url, data, config)),
	patch: (url, data = {}, config = {}) => request(mergeConfig("patch", url, data, config)),
	put: (url, data = {}, config = {}) => request(mergeConfig("put", url, data, config)),
	delete: (url, data = {}, config = {}) => request(mergeConfig("delete", url, data, config)),
	useHttpClient(newHttpClient) {
		httpClient$1 = newHttpClient;
		return client;
	},
	withBaseURL(url) {
		baseURL = url;
		return client;
	},
	withTimeout(duration) {
		timeout = 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;
	}
};
/**
* Merge the client specified arguments with the provided configuration.
*/
var mergeConfig = (method, url, data, config) => ({
	url,
	method,
	...config,
	...["get", "delete"].includes(method) ? { params: merge({}, data, config?.params) } : { data: merge({}, data, config?.data) }
});
/**
* Send and handle a new request.
*/
var request = (userConfig = {}) => {
	const config = [
		resolveConfig,
		abortMatchingRequests,
		refreshAbortController
	].reduce((config, callback) => callback(config), userConfig);
	if ((config.onBefore ?? (() => true))() === false) return Promise.resolve(null);
	(config.onStart ?? (() => null))();
	return httpClient$1.request({
		method: config.method,
		url: config.url,
		baseURL: config.baseURL ?? baseURL,
		data: config.data,
		params: config.params,
		headers: config.headers,
		signal: config.signal,
		timeout: config.timeout,
		credentials
	}).then(async (response) => {
		if (config.precognitive) validatePrecognitionResponse(response);
		const status = response.status;
		let payload = response;
		if (config.precognitive && config.onPrecognitionSuccess && successResolver(response)) payload = await Promise.resolve(config.onPrecognitionSuccess(response) ?? payload);
		if (config.onSuccess && isSuccess(status)) payload = await Promise.resolve(config.onSuccess(payload) ?? payload);
		return (resolveStatusHandler(config, status) ?? ((response) => response))(payload) ?? payload;
	}, (error) => {
		if (isNotServerGeneratedError(error)) return Promise.reject(error);
		const httpError = error;
		if (config.precognitive) validatePrecognitionResponse(httpError.response);
		return (resolveStatusHandler(config, httpError.response.status) ?? ((_, error) => Promise.reject(error)))(httpError.response, httpError);
	}).finally(config.onFinish ?? (() => null));
};
/**
* Resolve the configuration.
*/
var resolveConfig = (config) => {
	const only = config.only ?? config.validate;
	return {
		...config,
		timeout: config.timeout ?? timeout,
		precognitive: config.precognitive !== false,
		fingerprint: typeof config.fingerprint === "undefined" ? requestFingerprintResolver(config, httpClient$1) : config.fingerprint,
		headers: {
			...config.headers,
			"Accept": "application/json",
			"Content-Type": resolveContentType(config),
			...config.precognitive !== false ? { Precognition: true } : {},
			...only ? { "Precognition-Validate-Only": Array.from(only).join() } : {}
		}
	};
};
/**
* Determine if the status is successful.
*/
var isSuccess = (status) => status >= 200 && status < 300;
/**
* Abort an existing request with the same configured fingerprint.
*/
var abortMatchingRequests = (config) => {
	if (typeof config.fingerprint !== "string") return config;
	abortControllers[config.fingerprint]?.abort();
	delete abortControllers[config.fingerprint];
	return config;
};
/**
* Create and configure the abort controller for a new request.
*/
var refreshAbortController = (config) => {
	if (typeof config.fingerprint !== "string" || config.signal || !config.precognitive) return config;
	abortControllers[config.fingerprint] = new AbortController();
	return {
		...config,
		signal: abortControllers[config.fingerprint].signal
	};
};
/**
* Ensure that the response is a Precognition response.
*/
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.");
};
/**
* Determine if the error was not triggered by a server response.
*/
var isNotServerGeneratedError = (error) => {
	return !(error instanceof HttpResponseError$1) || typeof error.response?.status !== "number";
};
/**
* Resolve the handler for the given HTTP response status.
*/
var resolveStatusHandler = (config, code) => ({
	401: config.onUnauthorized,
	403: config.onForbidden,
	404: config.onNotFound,
	409: config.onConflict,
	422: config.onValidationError,
	423: config.onLocked
})[code];
/**
* Resolve the request's "Content-Type" header.
*/
var resolveContentType = (config) => config.headers?.["Content-Type"] ?? config.headers?.["Content-type"] ?? config.headers?.["content-type"] ?? (hasFiles$1(config.data) ? "multipart/form-data" : "application/json");
//#endregion
//#region node_modules/laravel-precognition/dist/validator.js
/**
* Expand a wildcard path to concrete paths using the given data.
*
* Examples:
* - 'users.*' with {users: [{name: 'A'}, {name: 'B'}]} => ['users.0', 'users.1']
* - 'users.*.name' with {users: [{name: 'A'}, {name: 'B'}]} => ['users.0.name', 'users.1.name']
* - 'author.*' with {author: {name: 'John', bio: 'Dev'}} => ['author.name', 'author.bio']
*/
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 key of Object.keys(value)) expanded.push(path ? `${path}.${key}` : key);
		}
		paths = expanded;
	} else paths = paths.map((path) => path ? `${path}.${part}` : part);
	return paths;
};
/**
* Determine if a key matches the given pattern.
*/
var keyMatchesPattern = (key, pattern) => {
	if (!pattern.includes("*")) return key === pattern;
	return new RegExp("^" + pattern.replace(/\./g, "\\.").replace(/\*/g, "[^.]+") + "$").test(key);
};
/**
* Omit entries from an object whose keys match the given patterns.
*/
var omitByPattern = (obj, patterns) => {
	return Object.fromEntries(Object.entries(obj).filter(([key]) => {
		return !patterns.some((pattern) => keyMatchesPattern(key, pattern));
	}));
};
var createValidator = (callback, initialData = {}) => {
	/**
	* Event listener state.
	*/
	const listeners = {
		errorsChanged: [],
		touchedChanged: [],
		validatingChanged: [],
		validatedChanged: []
	};
	/**
	* Validate files state.
	*/
	let validateFiles = false;
	/**
	* Processing validation state.
	*/
	let validating = false;
	/**
	* Set the validating inputs.
	*
	* Returns an array of listeners that should be invoked once all state
	* changes have taken place.
	*/
	const setValidating = (value) => {
		if (value !== validating) {
			validating = value;
			return listeners.validatingChanged;
		}
		return [];
	};
	/**
	* Inputs that have been validated.
	*/
	let validated = [];
	/**
	* Set the validated inputs.
	*
	* Returns an array of listeners that should be invoked once all state
	* changes have taken place.
	*/
	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 [];
	};
	/**
	* Valid validation state.
	*/
	const valid = () => validated.filter((name) => typeof errors[name] === "undefined");
	/**
	* Touched input state.
	*/
	let touched = [];
	/**
	* Set the touched inputs.
	*
	* Returns an array of listeners that should be invoked once all state
	* changes have taken place.
	*/
	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 [];
	};
	/**
	* Validation errors state.
	*/
	let errors = {};
	/**
	* Set the input errors.
	*
	* Returns an array of listeners that should be invoked once all state
	* changes have taken place.
	*/
	const setErrors = (value) => {
		const prepared = toValidationErrors(value);
		if (!isEqual(errors, prepared)) {
			errors = prepared;
			return listeners.errorsChanged;
		}
		return [];
	};
	/**
	* Forget the given input's errors.
	*
	* Returns an array of listeners that should be invoked once all state
	* changes have taken place.
	*/
	const forgetError = (name) => {
		const newErrors = { ...errors };
		delete newErrors[resolveName(name)];
		return setErrors(newErrors);
	};
	/**
	* Has errors state.
	*/
	const hasErrors = () => Object.keys(errors).length > 0;
	/**
	* Debouncing timeout state.
	*/
	let debounceTimeoutDuration = 1500;
	const setDebounceTimeout = (value) => {
		debounceTimeoutDuration = value;
		validator.cancel();
		validator = createValidator();
	};
	/**
	* The old data.
	*/
	let oldData = initialData;
	/**
	* The data currently being validated.
	*/
	let validatingData = null;
	/**
	* The old touched.
	*/
	let oldTouched = [];
	/**
	* The touched currently being validated.
	*/
	let validatingTouched = null;
	/**
	* Create a debounced validation callback.
	*/
	const createValidator = () => debounce$1((instanceConfig) => {
		callback({
			get: (url, data = {}, globalConfig = {}) => client.get(url, parseData(data), resolveConfig(globalConfig, instanceConfig, data)),
			post: (url, data = {}, globalConfig = {}) => client.post(url, parseData(data), resolveConfig(globalConfig, instanceConfig, data)),
			patch: (url, data = {}, globalConfig = {}) => client.patch(url, parseData(data), resolveConfig(globalConfig, instanceConfig, data)),
			put: (url, data = {}, globalConfig = {}) => client.put(url, parseData(data), resolveConfig(globalConfig, instanceConfig, data)),
			delete: (url, data = {}, globalConfig = {}) => client.delete(url, parseData(data), resolveConfig(globalConfig, instanceConfig, data))
		}).catch((error) => {
			if (error instanceof HttpCancelledError$1) return null;
			if (error instanceof HttpResponseError$1 && error.response?.status === 422) return null;
			return Promise.reject(error);
		});
	}, debounceTimeoutDuration, {
		leading: true,
		trailing: true
	});
	/**
	* Validator state.
	*/
	let validator = createValidator();
	/**
	* Resolve the configuration.
	*/
	const resolveConfig = (globalConfig, instanceConfig, data = {}) => {
		const config = {
			...globalConfig,
			...instanceConfig
		};
		const only = Array.from(config.only ?? config.validate ?? touched);
		return {
			...instanceConfig,
			...merge({}, globalConfig, instanceConfig),
			only,
			timeout: config.timeout ?? 5e3,
			onValidationError: (response, error) => {
				[...setValidated([...validated, ...only]), ...setErrors(merge(omitByPattern({ ...errors }, only), response.data.errors))].forEach((listener) => listener());
				return config.onValidationError ? config.onValidationError(response, error) : Promise.reject(error);
			},
			onSuccess: (response) => {
				setValidated([...validated, ...only]).forEach((listener) => listener());
				return config.onSuccess ? config.onSuccess(response) : response;
			},
			onPrecognitionSuccess: (response) => {
				[...setValidated([...validated, ...only]), ...setErrors(omitByPattern({ ...errors }, only))].forEach((listener) => listener());
				return config.onPrecognitionSuccess ? config.onPrecognitionSuccess(response) : response;
			},
			onBefore: () => {
				const hasWildcards = touched.some((name) => name.includes("*"));
				const expandedTouched = hasWildcards ? [...new Set(touched.flatMap((name) => expandWildcardPaths(name, data)))] : touched;
				if (config.onBeforeValidation && config.onBeforeValidation({
					data,
					touched: expandedTouched
				}, {
					data: oldData,
					touched: oldTouched
				}) === false) return false;
				if ((config.onBefore || (() => true))() === false) return false;
				if (hasWildcards) setTouched(expandedTouched).forEach((listener) => listener());
				validatingTouched = touched;
				validatingData = data;
				return true;
			},
			onStart: () => {
				setValidating(true).forEach((listener) => listener());
				(config.onStart ?? (() => null))();
			},
			onFinish: () => {
				setValidating(false).forEach((listener) => listener());
				oldTouched = validatingTouched;
				oldData = validatingData;
				validatingTouched = validatingData = null;
				(config.onFinish ?? (() => null))();
			}
		};
	};
	/**
	* Validate the given input.
	*/
	const validate = (name, value, config) => {
		if (typeof name === "undefined") {
			const only = Array.from(config?.only ?? config?.validate ?? []);
			setTouched([...touched, ...only]).forEach((listener) => listener());
			validator(config ?? {});
			return;
		}
		if (isFile$1(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(config ?? {});
		}
	};
	/**
	* Parse the validated data.
	*/
	const parseData = (data) => validateFiles === false ? forgetFiles(data) : data;
	/**
	* The form validator instance.
	*/
	const form = {
		touched: () => touched,
		validate(name, value, config) {
			if (typeof name === "object" && !("target" in name)) {
				config = name;
				name = value = void 0;
			}
			validate(name, value, config);
			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, callback) {
			listeners[event].push(callback);
			return form;
		},
		validateFiles() {
			validateFiles = true;
			return form;
		},
		withoutFileValidation() {
			validateFiles = false;
			return form;
		}
	};
	return form;
};
/**
* Normalise the validation errors as Inertia formatted errors.
*/
var toSimpleValidationErrors = (errors) => {
	return Object.keys(errors).reduce((carry, key) => ({
		...carry,
		[key]: Array.isArray(errors[key]) ? errors[key][0] : errors[key]
	}), {});
};
/**
* Normalise the validation errors as Laravel formatted errors.
*/
var toValidationErrors = (errors) => {
	return Object.keys(errors).reduce((carry, key) => ({
		...carry,
		[key]: typeof errors[key] === "string" ? [errors[key]] : errors[key]
	}), {});
};
/**
* Resolve the input's "name" attribute.
*/
var resolveName = (name) => {
	return typeof name !== "string" ? name.target.name : name;
};
/**
* Forget any files from the payload.
*/
var forgetFiles = (data) => {
	const newData = { ...data };
	Object.keys(newData).forEach((name) => {
		const value = newData[name];
		if (value === null) return;
		if (isFile$1(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;
};
//#endregion
//#region node_modules/@inertiajs/core/dist/index.js
var Config = class {
	config = {};
	defaults;
	constructor(defaults) {
		this.defaults = defaults;
	}
	extend(defaults) {
		if (defaults) this.defaults = {
			...this.defaults,
			...defaults
		};
		return this;
	}
	replace(newConfig) {
		this.config = newConfig;
	}
	get(key) {
		return has(this.config, key) ? get(this.config, key) : get(this.defaults, key);
	}
	set(keyOrValues, value) {
		if (typeof keyOrValues === "string") set(this.config, keyOrValues, value);
		else Object.entries(keyOrValues).forEach(([key, val]) => {
			set(this.config, key, val);
		});
	}
};
var config$1 = new Config({
	form: {
		recentlySuccessfulDuration: 2e3,
		forceIndicesArrayFormatInFormData: true,
		withAllErrors: false
	},
	prefetch: {
		cacheFor: 3e4,
		hoverDelay: 75
	}
});
function debounce(fn, delay) {
	let timeoutID;
	return function(...args) {
		clearTimeout(timeoutID);
		timeoutID = setTimeout(() => fn.apply(this, args), delay);
	};
}
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, { page: page2, visitId } = {}) => {
	return fireEvent("error", { detail: {
		errors,
		page: page2,
		visitId
	} });
};
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 = (page2) => {
	return fireEvent("beforeUpdate", { detail: { page: page2 } });
};
var fireNavigateEvent = (page2, { cached = false, visitId } = {}) => {
	return fireEvent("navigate", { detail: {
		page: page2,
		cached,
		visitId
	} });
};
var fireClientVisitEvent = (page2, { replace, visitId }) => {
	return fireEvent("clientVisit", { detail: {
		page: page2,
		replace,
		visitId
	} });
};
var fireProgressEvent = (progress3) => {
	return fireEvent("progress", { detail: { progress: progress3 } });
};
var fireStartEvent = (visit) => {
	return fireEvent("start", { detail: { visit } });
};
var fireSuccessEvent = (page2, { visitId } = {}) => {
	return fireEvent("success", { detail: {
		page: page2,
		visitId
	} });
};
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(key, value) {
		if (typeof window !== "undefined") window.sessionStorage.setItem(key, JSON.stringify(value));
	}
	static get(key) {
		if (typeof window !== "undefined") return JSON.parse(window.sessionStorage.getItem(key) || "null");
	}
	static merge(key, value) {
		const existing = this.get(key);
		if (existing === null) this.set(key, value);
		else this.set(key, {
			...existing,
			...value
		});
	}
	static remove(key) {
		if (typeof window !== "undefined") window.sessionStorage.removeItem(key);
	}
	static removeNested(key, nestedKey) {
		const existing = this.get(key);
		if (existing !== null) {
			delete existing[nestedKey];
			this.set(key, existing);
		}
	}
	static exists(key) {
		try {
			return this.get(key) !== 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 key = await getOrCreateKey(await getKeyFromSessionStorage());
	if (!key) throw new Error("Unable to encrypt history");
	return await encryptData(iv, key, data);
};
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, key, 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 result = textEncoder.encodeInto(str, encoded);
	return window.crypto.subtle.encrypt({
		name: "AES-GCM",
		iv
	}, key, encoded.subarray(0, result.written));
};
var decryptData = async (iv, key, 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
	}, key, 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 (key) => {
	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", key);
	SessionStorage.set(historySessionStorageKeys.key, Array.from(new Uint8Array(keyData)));
};
var getOrCreateKey = async (key) => {
	if (key) return key;
	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;
	return await window.crypto.subtle.importKey("raw", new Uint8Array(stringKey), {
		name: "AES-GCM",
		length: 256
	}, true, ["encrypt", "decrypt"]);
};
var stripTopLevelUndefined = (obj) => {
	const result = {};
	for (const key of Object.keys(obj)) if (obj[key] !== void 0) result[key] = obj[key];
	return result;
};
var objectsAreEqual = (obj1, obj2, excludeKeys) => {
	if (obj1 === obj2) return true;
	for (const key in obj1) {
		if (excludeKeys.includes(key)) continue;
		if (obj1[key] === obj2[key]) continue;
		if (!compareValues(obj1[key], obj2[key])) return false;
	}
	for (const key in obj2) {
		if (excludeKeys.includes(key)) continue;
		if (!(key in obj1)) return false;
	}
	return true;
};
var compareValues = (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 }) {
		if (this.findInFlight(params)) 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, reject) => {
			sendFunc({
				...params,
				onCancel: () => {
					this.remove(params);
					params.onCancel();
					reject();
				},
				onError: (error) => {
					this.remove(params);
					params.onError(error);
					reject();
				},
				onPrefetching(visitParams) {
					params.onPrefetching(visitParams);
				},
				onPrefetched(response, visit) {
					params.onPrefetched(response, visit);
				},
				onPrefetchResponse(response) {
					resolve(response);
				},
				onPrefetchError(error) {
					prefetchedRequests.removeFromInFlight(params);
					reject(error);
				}
			});
		}).then((response) => {
			this.remove(params);
			const pageResponse = response.getPageResponse();
			page$1.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;
		const consumedParams = {
			...params,
			cached: true
		};
		return prefetched.response.then((response) => {
			if (this.currentUseId !== id) return;
			response.mergeParams({
				...consumedParams,
				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$1(params);
		if (newParams.headers["Purpose"] === "prefetch") delete newParams.headers["Purpose"];
		return newParams;
	}
	paramsAreEqual(params1, params2) {
		return objectsAreEqual(this.withoutPurposePrefetchHeader(params1), this.withoutPurposePrefetchHeader(params2), [
			"id",
			"showProgress",
			"replace",
			"prefetch",
			"preserveScroll",
			"preserveState",
			"onBefore",
			"onBeforeUpdate",
			"onStart",
			"onProgress",
			"onFinish",
			"onCancel",
			"onSuccess",
			"onError",
			"onFlash",
			"onPrefetched",
			"onCancelToken",
			"onPrefetching",
			"async",
			"viewTransition",
			"optimistic",
			"component",
			"pageProps",
			"cached"
		]);
	}
	updateCachedOncePropsFromCurrentPage() {
		this.cached.forEach((prefetched) => {
			prefetched.response.then((response) => {
				const pageResponse = response.getPageResponse();
				page$1.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(page2) {
		const expiryTimestamps = Object.values(page2.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, times = 1) => {
	window.requestAnimationFrame(() => {
		if (times > 1) requestAnimationFrame(cb, times - 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() {
		if (!(isServer ? null : window.location.hash)) 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 isFile = (value) => typeof File !== "undefined" && value instanceof File || value instanceof Blob || typeof FileList !== "undefined" && value instanceof FileList && value.length > 0;
function hasFiles(data) {
	return isFile(data) || data instanceof FormData && Array.from(data.values()).some((value) => hasFiles(value)) || typeof data === "object" && data !== null && Object.values(data).some((value) => hasFiles(value));
}
var isFormData = (value) => value instanceof FormData;
function objectToFormData(source, form = new FormData(), parentKey = null, queryStringArrayFormat = "brackets") {
	source = source || {};
	for (const key in source) if (Object.prototype.hasOwnProperty.call(source, key)) append(form, composeKey(parentKey, key, "indices"), source[key], queryStringArrayFormat);
	return form;
}
function composeKey(parent, key, format) {
	if (!parent) return key;
	return format === "brackets" ? `${parent}[]` : `${parent}[${key}]`;
}
function append(form, key, value, format) {
	if (Array.isArray(value)) return Array.from(value.keys()).forEach((index) => append(form, composeKey(key, index.toString(), format), value[index], format));
	else if (value instanceof Date) return form.append(key, value.toISOString());
	else if (value instanceof File) return form.append(key, value, value.name);
	else if (value instanceof Blob) return form.append(key, value);
	else if (typeof value === "boolean") return form.append(key, value ? "1" : "0");
	else if (typeof value === "string") return form.append(key, value);
	else if (typeof value === "number") return form.append(key, `${value}`);
	else if (value === null || value === void 0) return form.append(key, "");
	objectToFormData(value, form, key, format);
}
function hasIndices(url) {
	return /\[\d+\]/.test(decodeURIComponent(url.search));
}
function parse(query) {
	if (!query || query === "?") return {};
	const result = {};
	query.replace(/^\?/, "").split("&").filter(Boolean).forEach((segment) => {
		const [rawKey, rawValue] = splitPair(segment);
		set2(result, decode(rawKey), decode(rawValue));
	});
	return result;
}
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, key, value) {
	const keys = parseKey(key);
	if (keys.some((k) => k === "__proto__")) return;
	let current = target;
	while (keys.length > 1) {
		const segment = keys.shift();
		const nextIsArrayPush = keys[0] === "";
		if (typeof current[segment] !== "object" || current[segment] === null) current[segment] = nextIsArrayPush ? [] : {};
		current = current[segment];
	}
	const final = keys.shift();
	if (final === "" && Array.isArray(current)) current.push(value);
	else current[final] = value;
}
function parseKey(key) {
	const segments = [];
	const base = key.split("[")[0];
	if (base) segments.push(base);
	let match;
	const pattern = /\[([^\]]*)\]/g;
	while ((match = pattern.exec(key)) !== 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) => {
			build(item, arrayFormat === "indices" ? `${prefix}[${index}]` : `${prefix}[]`, pairs, arrayFormat);
		});
		return;
	}
	if (typeof value === "object") {
		Object.keys(value).forEach((key) => {
			build(value[key], prefix ? `${prefix}[${key}]` : key, 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, method, forceFormData, queryStringArrayFormat) => {
	let url = typeof href === "string" ? hrefToUrl(href) : href;
	if ((hasFiles(data) || forceFormData) && !isFormData(data)) {
		if (config$1.get("form.forceIndicesArrayFormatInFormData")) queryStringArrayFormat = "indices";
		data = objectToFormData(data, new FormData(), null, queryStringArrayFormat);
	}
	if (isFormData(data)) return [url, data];
	const [_href, _data] = mergeDataIntoQueryString(method, url, data, queryStringArrayFormat);
	return [hrefToUrl(_href), _data];
};
function mergeDataIntoQueryString(method, href, data, qsArrayFormat = "brackets") {
	const hasDataForQueryString = method === "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(page2, { replace = false, preserveScroll = false, preserveState = false, viewTransition = false, cached = false, visitId } = {}) {
		if (Object.keys(page2.deferredProps || {}).length) {
			this.pendingDeferredProps = {
				deferredProps: page2.deferredProps,
				component: page2.component,
				url: page2.url
			};
			if (page2.initialDeferredProps === void 0) page2.initialDeferredProps = page2.deferredProps;
		}
		this.componentId = {};
		const componentId = this.componentId;
		if (page2.clearHistory) history.clear();
		return this.resolve(page2.component, page2).then((component) => {
			if (componentId !== this.componentId) return;
			page2.rememberedState ??= {};
			const isServer3 = typeof window === "undefined";
			const location = !isServer3 ? window.location : new URL(page2.url);
			const scrollRegions = !isServer3 && preserveScroll ? Scroll.getScrollRegions() : [];
			replace = replace || isSameUrlWithoutHash(hrefToUrl(page2.url), location);
			const pageForHistory = {
				...page2,
				flash: {}
			};
			return new Promise((resolve) => replace ? history.replaceState(pageForHistory, resolve) : history.pushState(pageForHistory, resolve)).then(() => {
				const isNewComponent = !this.isTheSame(page2);
				if (!isNewComponent && Object.keys(page2.props.errors || {}).length > 0) viewTransition = false;
				this.page = page2;
				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,
					page: page2,
					preserveState,
					viewTransition
				}).then(() => {
					if (preserveScroll) window.requestAnimationFrame(() => Scroll.restoreScrollRegions(scrollRegions));
					else Scroll.reset();
					if (this.pendingDeferredProps && this.pendingDeferredProps.component === page2.component && this.pendingDeferredProps.url === page2.url) eventHandler.fireInternalEvent("loadDeferredProps", this.pendingDeferredProps.deferredProps);
					this.pendingDeferredProps = null;
					if (!replace) fireNavigateEvent(page2, {
						cached,
						visitId
					});
				});
			});
		});
	}
	setQuietly(page2, { preserveState = false } = {}) {
		return this.resolve(page2.component, page2).then((component) => {
			this.page = page2;
			this.cleared = false;
			history.setCurrent(page2);
			return this.swap({
				component,
				page: page2,
				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((component) => {
			return this.swap({
				component,
				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, page: page2, preserveState, viewTransition }) {
		const doSwap = () => this.swapComponent({
			component,
			page: page2,
			preserveState
		});
		if (!viewTransition || !document?.startViewTransition || document.visibilityState === "hidden") return doSwap();
		const viewTransitionCallback = typeof viewTransition === "boolean" ? () => null : viewTransition;
		return new Promise((resolve) => {
			viewTransitionCallback(document.startViewTransition(() => doSwap().then(resolve)));
		});
	}
	resolve(component, page2) {
		return Promise.resolve(this.resolveComponent(component, page2));
	}
	nextOptimisticId() {
		return ++this.optimisticCounter;
	}
	setBaseline(key, value) {
		if (!(key in this.optimisticBaseline)) this.optimisticBaseline[key] = value;
	}
	updateBaseline(key, value) {
		if (key in this.optimisticBaseline) this.optimisticBaseline[key] = value;
	}
	hasBaseline(key) {
		return key 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$1(this.page.props);
		for (const key of baselineKeys) props[key] = cloneDeep$1(this.optimisticBaseline[key]);
		for (const { callback } of this.pendingOptimistics) {
			const result = callback(cloneDeep$1(props));
			if (result) Object.assign(props, result);
		}
		const replayedProps = {};
		for (const key of baselineKeys) replayedProps[key] = props[key];
		return replayedProps;
	}
	pendingOptimisticCount() {
		return this.pendingOptimistics.length;
	}
	clearOptimisticState() {
		this.optimisticBaseline = {};
		this.pendingOptimistics = [];
	}
	isTheSame(page2) {
		return this.page.component === page2.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(([key, onceProp]) => {
			const existingOnceProp = this.page.onceProps?.[key];
			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[key].expiresAt = existingOnceProp.expiresAt;
			}
		});
	}
};
var page$1 = 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 = {};
	initialState = null;
	remember(data, key) {
		this.replaceState({
			...page$1.getWithoutFlashData(),
			rememberedState: {
				...page$1.get()?.rememberedState ?? {},
				[key]: data
			}
		});
	}
	restore(key) {
		if (!isServer2) return this.current[this.rememberedState]?.[key] !== void 0 ? this.current[this.rememberedState]?.[key] : this.initialState?.[this.rememberedState]?.[key];
	}
	pushState(page2, cb = null) {
		if (isServer2) return;
		if (this.preserveUrl) {
			cb && cb();
			return;
		}
		this.current = page2;
		queue.add(() => {
			return this.getPageData(page2).then((data) => {
				const doPush = () => this.doPushState({ page: data }, page2.url).then(() => cb?.());
				if (isChromeIOS) return new Promise((resolve) => {
					setTimeout(() => doPush().then(resolve));
				});
				return doPush();
			});
		});
	}
	clonePageProps(page2) {
		try {
			structuredClone(page2.props);
			return page2;
		} catch {
			return {
				...page2,
				props: cloneDeep$1(page2.props)
			};
		}
	}
	getPageData(page2) {
		const pageWithClonedProps = this.clonePageProps(page2);
		return new Promise((resolve) => {
			return page2.encryptHistory ? encryptHistory(pageWithClonedProps).then(resolve) : resolve(pageWithClonedProps);
		});
	}
	processQueue() {
		return queue.process();
	}
	decrypt(page2 = null) {
		if (isServer2) return Promise.resolve(page2 ?? page$1.get());
		const pageData = page2 ?? 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(page2, cb = null) {
		if (isEqual(this.current, page2)) {
			cb && cb();
			return;
		}
		const { flash, ...pageWithoutFlash } = page2;
		page$1.merge(pageWithoutFlash);
		if (isServer2) return;
		if (this.preserveUrl) {
			cb && cb();
			return;
		}
		this.current = page2;
		queue.add(() => {
			return this.getPageData(page2).then((data) => {
				const doReplace = () => this.doReplaceState({ page: data }, page2.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(key, defaultValue) {
		return this.current?.[key] ?? defaultValue;
	}
	deleteState(key) {
		if (this.current[key] !== void 0) {
			delete this.current[key];
			this.replaceState(this.current);
		}
	}
	clearInitialState(key) {
		if (this.initialState && this.initialState[key] !== void 0) delete this.initialState[key];
	}
	browserHasHistoryEntry() {
		return !isServer2 && !!window.history.state?.page;
	}
	clear() {
		SessionStorage.remove(historySessionStorageKeys.key);
		SessionStorage.remove(historySessionStorageKeys.iv);
	}
	setCurrent(page2) {
		this.current = page2;
	}
	isValidState(state) {
		return !!state.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", debounce(Scroll.onWindowScroll.bind(Scroll), 100), true);
		}
		if (typeof document !== "undefined") document.addEventListener("scroll", debounce(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$1.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);
	}
	handlePageshowEvent(event) {
		if (event.persisted) history.decrypt().catch(() => this.onMissingHistoryItem());
	}
	handlePopstateEvent(event) {
		const state = event.state || null;
		if (state === null) {
			const url = hrefToUrl(page$1.get().url);
			url.hash = window.location.hash;
			history.replaceState({
				...page$1.getWithoutFlashData(),
				url: url.href
			});
			Scroll.reset();
			return;
		}
		if (!history.isValidState(state)) return this.onMissingHistoryItem();
		history.decrypt(state.page).then((data) => {
			if (page$1.get().version !== data.version) {
				this.onMissingHistoryItem();
				return;
			}
			router.cancelAll({ prefetch: false });
			page$1.setQuietly(data, { preserveState: false }).then(() => {
				Scroll.restore(history.getScrollRegions());
				fireNavigateEvent(page$1.get());
				const pendingDeferred = {};
				const pageProps = page$1.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";
		return (window.performance?.getEntriesByType("navigation")[0])?.type ?? "navigate";
	}
	get() {
		return this.type;
	}
	isBackForward() {
		return this.type === "back_forward";
	}
	isReload() {
		return this.type === "reload";
	}
};
var navigationType = new NavigationType();
function uid() {
	const cryptoObj = typeof window !== "undefined" ? window.crypto : void 0;
	if (cryptoObj?.randomUUID) return cryptoObj.randomUUID();
	const randomByte = () => cryptoObj?.getRandomValues ? cryptoObj.getRandomValues(new Uint8Array(1))[0] : Math.floor(Math.random() * 256);
	return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16));
}
var InitialVisit = class {
	static handle() {
		this.clearRememberedStateOnReload();
		[
			this.handleBackForward,
			this.handleLocation,
			this.handleDefault
		].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) => {
			const visitId = uid();
			page$1.set(data, {
				preserveScroll: true,
				preserveState: true,
				visitId
			}).then(() => {
				Scroll.restore(scrollRegions);
				fireNavigateEvent(page$1.get(), { visitId });
			});
		}).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$1.setUrlHash(window.location.hash);
		history.decrypt(page$1.get()).then(() => {
			const visitId = uid();
			const rememberedState = history.getState(history.rememberedState, {});
			const scrollRegions = history.getScrollRegions();
			page$1.remember(rememberedState);
			page$1.set(page$1.get(), {
				preserveScroll: locationVisit.preserveScroll,
				preserveState: true,
				visitId
			}).then(() => {
				if (locationVisit.preserveScroll) Scroll.restore(scrollRegions);
				this.fireInitialEvents(visitId);
			});
		}).catch(() => {
			eventHandler.onMissingHistoryItem();
		});
		return true;
	}
	static handleDefault() {
		if (typeof window !== "undefined") page$1.setUrlHash(window.location.hash);
		const visitId = uid();
		page$1.set(page$1.get(), {
			preserveScroll: true,
			preserveState: true,
			visitId
		}).then(() => {
			if (navigationType.isReload()) Scroll.restore(history.getScrollRegions());
			else Scroll.scrollToAnchor();
			this.fireInitialEvents(visitId);
		});
	}
	static fireInitialEvents(visitId) {
		const page2 = page$1.get();
		fireNavigateEvent(page2, { visitId });
		if (Object.keys(page2.flash).length > 0) queueMicrotask(() => fireFlashEvent(page2.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((h) => h !== handler);
		};
	}
	onResponse(handler) {
		this.responseHandlers.push(handler);
		return () => {
			this.responseHandlers = this.responseHandlers.filter((h) => h !== handler);
		};
	}
	onError(handler) {
		this.errorHandlers.push(handler);
		return () => {
			this.errorHandlers = this.errorHandlers.filter((h) => h !== handler);
		};
	}
	async processRequest(config2) {
		let result = config2;
		for (const handler of this.requestHandlers) result = await handler(result);
		return result;
	}
	async processResponse(response) {
		let result = response;
		for (const handler of this.responseHandlers) result = await handler(result);
		return result;
	}
	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 HttpResponseError = class extends HttpError {
	response;
	constructor(message, response, url) {
		super(message, "ERR_HTTP_RESPONSE", url);
		this.name = "HttpResponseError";
		this.response = response;
	}
};
var HttpCancelledError = class extends HttpError {
	constructor(message = "Request was cancelled", url) {
		super(message, "ERR_CANCELLED", url);
		this.name = "HttpCancelledError";
	}
};
var HttpNetworkError = 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 parseHeaders(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, config2) {
	if (!config2.headers) return;
	const isFormData2 = config2.data instanceof FormData;
	Object.entries(config2.headers).forEach(([key, value]) => {
		if (key.toLowerCase() !== "content-type" || !isFormData2) xhr.setRequestHeader(key, 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(config2) {
		const processedConfig = await httpHandlers.processRequest(config2);
		try {
			const response = await this.doRequest(processedConfig);
			return await httpHandlers.processResponse(response);
		} catch (error) {
			if (error instanceof HttpResponseError || error instanceof HttpNetworkError || error instanceof HttpCancelledError) await httpHandlers.processError(error);
			throw error;
		}
	}
	doRequest(config2) {
		return new Promise((resolve, reject) => {
			const xhr = new XMLHttpRequest();
			const url = buildUrlWithParams(config2.url, config2.params);
			xhr.open(config2.method.toUpperCase(), url, true);
			const xsrfToken = getCookie(this.xsrfCookieName);
			if (xsrfToken) xhr.setRequestHeader(this.xsrfHeaderName, xsrfToken);
			let body = null;
			if (config2.data !== null && config2.data !== void 0) if (config2.data instanceof FormData) body = config2.data;
			else if (typeof config2.data === "object") {
				body = JSON.stringify(config2.data);
				if (!config2.headers?.["Content-Type"] && !config2.headers?.["content-type"]) xhr.setRequestHeader("Content-Type", "application/json");
			} else body = String(config2.data);
			setHeaders(xhr, config2);
			if (config2.onUploadProgress) xhr.upload.onprogress = (event) => {
				const progress3 = event.lengthComputable ? event.loaded / event.total : void 0;
				config2.onUploadProgress({
					progress: progress3,
					percentage: progress3 ? Math.round(progress3 * 100) : 0,
					loaded: event.loaded,
					total: event.lengthComputable ? event.total : void 0
				});
			};
			if (config2.signal) config2.signal.addEventListener("abort", () => xhr.abort());
			xhr.onabort = () => reject(new HttpCancelledError("Request was cancelled", config2.url));
			xhr.onerror = () => reject(new HttpNetworkError("Network error", config2.url));
			xhr.onload = () => {
				const response = {
					status: xhr.status,
					data: xhr.responseText,
					headers: parseHeaders(xhr)
				};
				if (xhr.status >= 400) reject(new HttpResponseError(`Request failed with status ${xhr.status}`, response, config2.url));
				else resolve(response);
			};
			xhr.send(body);
		});
	}
};
var httpClient = new XhrHttpClient();
function isHttpClientOptions(client) {
	return !("request" in client);
}
var http = {
	/**
	* Get the current HTTP client
	*/
	getClient() {
		return httpClient;
	},
	/**
	* Set the HTTP client to use for all Inertia requests
	*/
	setClient(clientOrOptions) {
		if (!isHttpClientOptions(clientOrOptions)) {
			httpClient = clientOrOptions;
			return;
		}
		httpClient = 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 VisitInterceptors = class {
	requestHandlers = [];
	responseHandlers = [];
	onVisitRequest(handler) {
		this.requestHandlers.push(handler);
		return () => {
			this.requestHandlers = this.requestHandlers.filter((h) => h !== handler);
		};
	}
	onVisitResponse(handler) {
		this.responseHandlers.push(handler);
		return () => {
			this.responseHandlers = this.responseHandlers.filter((h) => h !== handler);
		};
	}
	async processRequest(visit, config2) {
		let result = config2;
		for (const handler of this.requestHandlers) result = await handler(visit, result);
		return result;
	}
	async processResponse(visit, response) {
		let result = response;
		for (const handler of this.responseHandlers) result = await handler(visit, result);
		return result;
	}
};
var interceptors = new VisitInterceptors();
function exposeInterceptors() {
	if (typeof window === "undefined") return;
	window.__inertia_interceptors__ = interceptors;
}
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$1.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(page2) {
		this.params.preserveScroll = _RequestParams.resolvePreserveOption(this.params.preserveScroll, page2);
		this.params.preserveState = _RequestParams.resolvePreserveOption(this.params.preserveState, page2);
	}
	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, page2) {
		if (typeof value === "function") return value(page2);
		if (value === "errors") return Object.keys(page2.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 page2 = document.createElement("html");
		page2.innerHTML = html;
		page2.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: page2
		};
	},
	show(html) {
		const { iframe, page: page2 } = 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$1.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 = page2.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$1.get();
		if (Object.keys(flash).length > 0 && !this.requestParams.isDeferredPropsRequest()) {
			fireFlashEvent(flash);
			this.requestParams.all().onFlash(flash);
		}
		const errors = page$1.get().props.errors || {};
		if (Object.keys(errors).length > 0) {
			const scopedErrors = this.getScopedErrors(errors);
			fireErrorEvent(scopedErrors, {
				page: page$1.get(),
				visitId: this.requestParams.all().id
			});
			return this.requestParams.all().onError(scopedErrors);
		}
		router.flushByCacheTags(this.requestParams.all().invalidateCacheTags || []);
		if (!this.wasPrefetched) router.flush(page$1.get().url);
		fireSuccessEvent(page$1.get(), { visitId: this.requestParams.all().id });
		await this.requestParams.all().onSuccess(page$1.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.response = await interceptors.processResponse(this.requestParams.all(), this.response);
		this.mergeProps(pageResponse);
		page$1.mergeOncePropsIntoResponse(pageResponse);
		this.preserveOptimisticProps(pageResponse);
		this.preserveEqualProps(pageResponse);
		await this.setRememberedState(pageResponse);
		this.requestParams.setPreserveOptions(pageResponse);
		pageResponse.url = history.preserveUrl ? page$1.get().url : this.pageUrl(pageResponse);
		this.requestParams.all().onBeforeUpdate(pageResponse);
		fireBeforeUpdateEvent(pageResponse);
		return page$1.set(pageResponse, {
			replace: this.requestParams.all().replace,
			preserveScroll: this.requestParams.all().preserveScroll,
			preserveState: this.requestParams.all().preserveState,
			viewTransition: this.requestParams.all().viewTransition,
			cached: this.requestParams.all().cached,
			visitId: this.requestParams.all().id
		});
	}
	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$1.get().component) return false;
		const originatingUrl = hrefToUrl(this.originatingPage.url);
		const currentPageUrl = hrefToUrl(page$1.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 key of Object.keys(pageResponse.props)) if (page$1.hasBaseline(key)) {
			page$1.updateBaseline(key, pageResponse.props[key]);
			pageResponse.props[key] = page$1.get().props[key];
		}
	}
	preserveEqualProps(pageResponse) {
		if (pageResponse.component !== page$1.get().component) return;
		const currentPageProps = page$1.get().props;
		Object.entries(pageResponse.props).forEach(([key, value]) => {
			if (isEqual(value, currentPageProps[key])) pageResponse.props[key] = currentPageProps[key];
		});
	}
	mergeProps(pageResponse) {
		if (!this.requestParams.isPartial() || pageResponse.component !== page$1.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$1.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$1.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, key) => {
					acc[key] = deepMerge(target ? target[key] : void 0, source[key], `${matchProp}.${key}`);
					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 key of nestedTopKeys) {
			const currentValue = page$1.get().props[key];
			if (this.isObject(currentValue) && this.isObject(pageResponse.props[key])) pageResponse.props[key] = this.deepMergeObjects(currentValue, pageResponse.props[key]);
		}
		pageResponse.props = {
			...page$1.get().props,
			...pageResponse.props
		};
		if (this.shouldPreserveErrors(pageResponse)) pageResponse.props.errors = page$1.get().props.errors;
		if (page$1.get().scrollProps) pageResponse.scrollProps = {
			...page$1.get().scrollProps || {},
			...pageResponse.scrollProps || {}
		};
		if (page$1.hasOnceProps()) pageResponse.onceProps = {
			...page$1.get().onceProps || {},
			...pageResponse.onceProps || {}
		};
		if (this.requestParams.isDeferredPropsRequest()) pageResponse.flash = { ...page$1.get().flash };
		const currentOriginalDeferred = page$1.get().initialDeferredProps;
		if (currentOriginalDeferred && Object.keys(currentOriginalDeferred).length > 0) pageResponse.initialDeferredProps = currentOriginalDeferred;
		pageResponse.rescuedProps = this.mergeRescuedProps(pageResponse);
	}
	mergeRescuedProps(pageResponse) {
		const currentRescued = page$1.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$1.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 result = { ...target };
		for (const key of Object.keys(source)) {
			const targetValue = target[key];
			const sourceValue = source[key];
			if (this.isObject(targetValue) && this.isObject(sourceValue)) result[key] = this.deepMergeObjects(targetValue, sourceValue);
			else result[key] = sourceValue;
		}
		return result;
	}
	mergeOrMatchItems(existingItems, newItems, matchProp, matchPropsOn, shouldAppend = true) {
		const items = Array.isArray(existingItems) ? existingItems : [];
		const matchingKey = matchPropsOn.find((key) => {
			return key.split(".").slice(0, -1).join(".") === 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, property) {
		return item && typeof item === "object" && property in item;
	}
	async setRememberedState(pageResponse) {
		const rememberedState = await history.getState(history.rememberedState, {});
		if (this.requestParams.all().preserveState && rememberedState && pageResponse.component === page$1.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, page2, { optimistic = false } = {}) {
		this.page = page2;
		this.requestParams = RequestParams.create(params);
		this.cancelToken = new AbortController();
		this.optimistic = optimistic;
	}
	response;
	cancelToken;
	requestParams;
	requestHasFinished = false;
	optimistic;
	static create(params, page2, options) {
		return new _Request(params, page2, 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;
		const config2 = {
			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)
		};
		const processedConfig = await interceptors.processRequest(this.requestParams.all(), config2);
		return http.getClient().request(processedConfig).then((response) => {
			this.response = Response.create(this.requestParams, response, this.page);
			return this.response.handle();
		}).catch((error) => {
			if (error instanceof HttpResponseError) {
				this.response = Response.create(this.requestParams, error.response, this.page);
				return this.response.handle();
			}
			return Promise.reject(error);
		}).catch((error) => {
			if (error instanceof HttpCancelledError) 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 page2 = page$1.get();
		if (page2.version) headers["X-Inertia-Version"] = page2.version;
		const onceProps = Object.entries(page2.onceProps || {}).filter(([, onceProp]) => {
			if (get(page2.props, onceProp.prop) === void 0) return false;
			return !onceProp.expiresAt || onceProp.expiresAt > Date.now();
		}).map(([key]) => key);
		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(request) {
		this.requests.push(request);
		request.send().finally(() => {
			this.requests = this.requests.filter((r) => r !== request);
		});
	}
	interruptInFlight() {
		this.cancel({ interrupted: true }, false);
	}
	cancelInFlight({ prefetch = true, optimistic = true } = {}) {
		this.requests.filter((request) => prefetch || !request.isPrefetch()).filter((request) => optimistic || !request.isOptimistic()).forEach((request) => request.cancel({ cancelled: true }));
	}
	cancel({ cancelled = false, interrupted = false } = {}, force = false) {
		if (!force && !this.shouldCancel()) return;
		this.requests.shift()?.cancel({
			cancelled,
			interrupted
		});
	}
	shouldCancel() {
		return this.interruptible && this.requests.length >= this.maxConcurrent;
	}
	hasPendingOptimistic() {
		return this.requests.some((request) => request.isPendingOptimistic());
	}
};
var noop$1 = () => {};
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$1.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, key = "default") {
		history.remember(data, key);
	}
	restore(key = "default") {
		return history.restore(key);
	}
	on(type, callback) {
		if (typeof window === "undefined") return () => {};
		return eventHandler.onGlobalEvent(type, callback);
	}
	once(type, callback) {
		if (typeof window === "undefined") return () => {};
		const remove2 = this.on(type, (event) => {
			remove2();
			return callback(event);
		});
		return remove2;
	}
	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$1.get().url);
		if (!(visit.only.length > 0 || visit.except.length > 0 || visit.reset.length > 0 ? isSameUrlWithoutQueryOrHash(visit.url, currentPageUrl) : isSameUrlWithoutHash(visit.url, currentPageUrl))) this.asyncRequestStream.cancelInFlight({
			prefetch: false,
			optimistic: false
		});
		if (!visit.async) this.syncRequestStream.interruptInFlight();
		if (options.optimistic) this.applyOptimisticUpdate(options.optimistic, events);
		if (!page$1.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);
				(visit.async ? this.asyncRequestStream : this.syncRequestStream).send(Request.create(requestParams, page$1.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.preserveScroll = true;
				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 = {}) {
		if ((options.method ?? (isUrlMethodPair(href) ? href.method : "get")) !== "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
		});
		if (visit.url.origin + visit.url.pathname + visit.url.search === window.location.origin + window.location.pathname + window.location.search) 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$1.get()) resolve();
					else setTimeout(checkIfPageIsDefined, 50);
				};
				checkIfPageIsDefined();
			});
		};
		ensureCurrentPageIsSet().then(() => {
			prefetchedRequests.add(requestParams, (params) => {
				this.asyncRequestStream.send(Request.create(params, page$1.get()));
			}, {
				cacheFor: config$1.get("prefetch.cacheFor"),
				cacheTags: [],
				...prefetchOptions
			});
		});
	}
	clearHistory() {
		history.clear();
	}
	decryptHistory() {
		return history.decrypt();
	}
	resolveComponent(component, page2) {
		return page$1.resolve(component, page2);
	}
	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$1(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$1.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$1.setFlash(flash);
		if (Object.keys(flash).length) fireFlashEvent(flash);
	}
	clientVisit(params, { replace = false } = {}) {
		this.clientVisitQueue.add(() => this.performClientVisit(params, { replace }));
	}
	performClientVisit(params, { replace = false } = {}) {
		const current = page$1.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 page2 = {
			...current,
			...pageParams,
			flash: flash ?? {},
			props
		};
		const preserveScroll = RequestParams.resolvePreserveOption(params.preserveScroll ?? false, page2);
		const preserveState = RequestParams.resolvePreserveOption(params.preserveState ?? false, page2);
		const visitId = this.createVisitId();
		return page$1.set(page2, {
			replace,
			preserveScroll,
			preserveState,
			viewTransition,
			visitId
		}).then(() => {
			fireClientVisitEvent(page$1.get(), {
				replace,
				visitId
			});
			const currentFlash = page$1.get().flash;
			if (Object.keys(currentFlash).length > 0) {
				fireFlashEvent(currentFlash);
				onFlash?.(currentFlash);
			}
			const errors = page$1.get().props.errors || {};
			if (Object.keys(errors).length === 0) {
				onSuccess?.(page$1.get());
				return;
			}
			const scopedErrors = params.errorBag ? errors[params.errorBag || ""] || {} : errors;
			onError?.(scopedErrors);
		}).finally(() => onFinish?.(params));
	}
	performInstantSwap(visit) {
		const current = page$1.get();
		const sharedProps = Object.fromEntries((current.sharedProps ?? []).filter((key) => key in current.props).map((key) => [key, current.props[key]]));
		const resolvedPageProps = typeof visit.pageProps === "function" ? visit.pageProps(cloneDeep$1(current.props), cloneDeep$1(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$1.set(intermediatePage, {
			replace: visit.replace,
			preserveScroll: RequestParams.resolvePreserveOption(visit.preserveScroll, intermediatePage),
			preserveState: false,
			viewTransition: visit.viewTransition,
			visitId: visit.id
		});
	}
	getPrefetchParams(href, options) {
		return {
			...this.getPendingVisit(href, {
				...options,
				async: true,
				showProgress: false,
				prefetch: true,
				viewTransition: false
			}),
			...this.getVisitEvents(options)
		};
	}
	createVisitId() {
		return uid();
	}
	getPendingVisit(href, options) {
		if (isUrlMethodPair(href)) {
			const urlMethodPair = href;
			href = urlMethodPair.url;
			options.method = options.method ?? urlMethodPair.method;
		}
		const defaultVisitOptionsCallback = config$1.get("visitOptions");
		const configuredOptions = defaultVisitOptionsCallback ? defaultVisitOptionsCallback(href.toString(), cloneDeep$1(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,
			cached: false,
			...stripTopLevelUndefined(options),
			...stripTopLevelUndefined(configuredOptions)
		};
		const [url, _data] = transformUrlAndData(href, mergedOptions.data, mergedOptions.method, mergedOptions.forceFormData, mergedOptions.queryStringArrayFormat);
		const visit = {
			id: this.createVisitId(),
			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 || noop$1,
			onBefore: options.onBefore || noop$1,
			onBeforeUpdate: options.onBeforeUpdate || noop$1,
			onStart: options.onStart || noop$1,
			onProgress: options.onProgress || noop$1,
			onFinish: options.onFinish || noop$1,
			onCancel: options.onCancel || noop$1,
			onSuccess: options.onSuccess || noop$1,
			onError: options.onError || noop$1,
			onHttpException: options.onHttpException || noop$1,
			onNetworkError: options.onNetworkError || noop$1,
			onFlash: options.onFlash || noop$1,
			onPrefetched: options.onPrefetched || noop$1,
			onPrefetching: options.onPrefetching || noop$1
		};
	}
	applyOptimisticUpdate(optimistic, events) {
		const currentProps = page$1.get().props;
		const optimisticProps = optimistic(cloneDeep$1(currentProps));
		if (!optimisticProps) return;
		const changedKeys = [];
		for (const key of Object.keys(optimisticProps)) if (!isEqual(currentProps[key], optimisticProps[key])) changedKeys.push(key);
		if (changedKeys.length === 0) return;
		const id = page$1.nextOptimisticId();
		const component = page$1.get().component;
		for (const key of changedKeys) page$1.setBaseline(key, cloneDeep$1(currentProps[key]));
		page$1.registerOptimistic(id, optimistic);
		page$1.setPropsQuietly({
			...currentProps,
			...optimisticProps
		});
		let shouldRestore = true;
		const originalOnSuccess = events.onSuccess;
		events.onSuccess = (page2) => {
			shouldRestore = false;
			return originalOnSuccess(page2);
		};
		const originalOnFinish = events.onFinish;
		events.onFinish = (visit) => {
			page$1.unregisterOptimistic(id);
			if (shouldRestore && page$1.get().component === component) {
				const replayedProps = page$1.replayOptimistics();
				if (Object.keys(replayedProps).length > 0) page$1.setPropsQuietly({
					...page$1.get().props,
					...replayedProps
				});
			}
			if (page$1.pendingOptimisticCount() === 0) page$1.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, config2, headers) {
		const merge = (config3) => {
			config3.headers = {
				...headers ?? {},
				...config3.headers ?? {}
			};
			return config3;
		};
		if (field && typeof field === "object" && !("target" in field)) field = merge(field);
		else if (config2 && typeof config2 === "object") config2 = merge(config2);
		else if (typeof field === "string") config2 = merge(config2 ?? {});
		else field = merge(field ?? {});
		return [field, config2];
	}
};
function undotKey(key) {
	if (!key.includes(".")) return key;
	const transformSegment = (segment) => {
		if (segment.startsWith("[") && segment.endsWith("]")) return segment;
		return segment.split(".").reduce((result, part, index) => index === 0 ? part : `${result}[${part}]`);
	};
	return key.replace(/\\\./g, "__ESCAPED_DOT__").split(/(\[[^\]]*\])/).filter(Boolean).map(transformSegment).join("").replace(/__ESCAPED_DOT__/g, ".");
}
function parseKey2(key) {
	const path = [];
	const pattern = /([^\[\]]+)|\[(\d*)\]/g;
	let match;
	while ((match = pattern.exec(key)) !== 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 keys = Object.keys(value);
	const numericKeys = keys.filter((k) => /^\d+$/.test(k)).map(Number).sort((a, b) => a - b);
	return keys.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 || isFile(value)) return value;
	if (objectHasSequentialNumericKeys(value)) {
		const result2 = [];
		for (let i = 0; i < Object.keys(value).length; i++) result2[i] = convertSequentialObjectsToArrays(value[i]);
		return result2;
	}
	const result = {};
	for (const key in value) result[key] = convertSequentialObjectsToArrays(value[key]);
	return result;
}
function formDataToObject(source) {
	const form = {};
	for (const [key, value] of source.entries()) {
		if (value instanceof File && value.size === 0 && value.name === "") continue;
		const path = parseKey2(undotKey(key));
		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" && !isFile(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 template = document.createElement("template");
		template.innerHTML = tag;
		const node = template.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 key = element.getAttribute("data-inertia");
		if (key !== null) return elements.findIndex((element2) => element2.getAttribute("data-inertia") === key);
		return -1;
	},
	update: debounce(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 update(id, elements = []) {
		if (id !== null && Object.keys(states).indexOf(id) > -1) states[id] = elements;
		commit();
	}
	function collect() {
		const title = titleCallback("");
		const defaults = { ...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;
		}, defaults);
		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) => update(id, elements),
				disconnect: () => disconnect(id)
			};
		}
	};
}
var MERGE_INTENT_HEADER = "X-Inertia-Infinite-Scroll-Merge-Intent";
var useInfiniteScrollData = (options) => {
	const getScrollPropFromCurrentPage = () => {
		const scrollProp = page$1.get().scrollProps?.[options.getPropName()];
		if (scrollProp) return scrollProp;
		throw new Error(`The page object does not contain a scroll prop named "${options.getPropName()}".`);
	};
	const state = {
		component: null,
		loading: false,
		previousPage: null,
		nextPage: null,
		lastLoadedPage: null,
		requestCount: 0
	};
	const resetState = () => {
		const scrollProp = getScrollPropFromCurrentPage();
		state.component = page$1.get().component;
		state.loading = false;
		state.previousPage = scrollProp.previousPage;
		state.nextPage = scrollProp.nextPage;
		state.lastLoadedPage = scrollProp.currentPage;
		state.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) {
			state.previousPage = rememberedState.previousPage;
			state.nextPage = rememberedState.nextPage;
			state.lastLoadedPage = rememberedState.lastLoadedPage;
			state.requestCount = rememberedState.requestCount || 0;
		}
	}
	const removeEventListener = router.on("success", (event) => {
		if (state.component === event.detail.page.component && getScrollPropFromCurrentPage().reset) {
			resetState();
			options.onReset?.();
		}
	});
	const getScrollPropKeyForSide = (side) => {
		return side === "next" ? "nextPage" : "previousPage";
	};
	const findPageToLoad = (side) => {
		return state[getScrollPropKeyForSide(side)];
	};
	const syncStateOnSuccess = (side) => {
		const scrollProp = getScrollPropFromCurrentPage();
		const paginationProp = getScrollPropKeyForSide(side);
		state.lastLoadedPage = scrollProp.currentPage;
		state[paginationProp] = scrollProp[paginationProp];
		state.requestCount += 1;
		router.remember({
			previousPage: state.previousPage,
			nextPage: state.nextPage,
			lastLoadedPage: state.lastLoadedPage,
			requestCount: state.requestCount
		}, getRememberKey());
	};
	const getPageName = () => getScrollPropFromCurrentPage().pageName;
	const getRequestCount = () => state.requestCount;
	const fetchPage = (side, reloadOptions = {}) => {
		const page2 = findPageToLoad(side);
		if (state.loading || page2 === null) return;
		state.loading = true;
		router.reload({
			preserveErrors: true,
			...reloadOptions,
			data: {
				...reloadOptions.data || {},
				[getPageName()]: page2
			},
			only: [...reloadOptions.only || [], options.getPropName()],
			preserveUrl: true,
			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) => {
				state.loading = false;
				const completed = visit.completed;
				const page3 = completed ? state.lastLoadedPage : null;
				side === "next" ? options.onCompleteNextRequest(page3, {
					page: page3,
					completed
				}) : options.onCompletePreviousRequest(page3, {
					page: page3,
					completed
				});
				reloadOptions.onFinish?.(visit);
			}
		});
	};
	const getLastLoadedPage = () => state.lastLoadedPage;
	const hasPrevious = () => !!state.previousPage;
	const hasNext = () => !!state.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 page2 = getPageFromElement(node);
			if (typeof page2 === "undefined") continue;
			if (!(page2 in pageElementRange)) pageElementRange[page2] = {
				from: index,
				to: index
			};
			else pageElementRange[page2].to = index;
		}
		router.remember(pageElementRange, getElementsRememberKey());
	};
	const rememberElementsDebounced = debounce(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 [page2, range] of Object.entries(pageElementRange)) if (index >= range.from && index <= range.to) {
				elementPage = page2;
				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 = (page2) => {
		queue3.add(() => {
			return new Promise((resolve) => {
				if (!enabled) {
					initialUrl = payloadUrl = null;
					return resolve();
				}
				if (!initialUrl || !payloadUrl) {
					const currentPageUrl = page$1.get().url;
					initialUrl = hrefToUrl(currentPageUrl);
					payloadUrl = hrefToUrl(currentPageUrl);
					initialUrlWasAbsolute = urlHasProtocol(currentPageUrl);
				}
				const pageName = options.getPageName();
				const searchParams = payloadUrl.searchParams;
				if (page2 === "1") searchParams.delete(pageName);
				else searchParams.set(pageName, page2);
				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;
		});
	};
	return {
		onItemIntersected: debounce((itemElement) => {
			const itemsElement = options.getItemsElement();
			if (!enabled || options.shouldPreserveUrl() || !itemElement || !itemsElement) return;
			const pageMap = /* @__PURE__ */ new Map();
			getElementsInViewportFromCollection([...itemsElement.children], itemElement).forEach((element) => {
				const page2 = getPageFromElement(element) ?? "1";
				if (pageMap.has(page2)) pageMap.set(page2, pageMap.get(page2) + 1);
				else pageMap.set(page2, 1);
			});
			const mostVisiblePage = Array.from(pageMap.entries()).sort((a, b) => b[1] - a[1])[0]?.[0];
			if (mostVisiblePage !== void 0) queuePageUpdate(mostVisiblePage);
		}, 250),
		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;
				referenceElementTop = referenceElement.getBoundingClientRect().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 adjustment = referenceElement.getBoundingClientRect().top - containerTop - 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,
		onItemIntersected: queryStringManager.onItemIntersected,
		onPreviousTriggered: () => dataManager.fetchPrevious(),
		onNextTriggered: () => dataManager.fetchNext()
	});
	const dataManager = useInfiniteScrollData({
		...options,
		onBeforeUpdate: elementManager.processManuallyAddedElements,
		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 = (page2) => {
			originalOnBeforeUpdate(page2);
			captureScrollPosition();
		};
		reloadOptions.onSuccess = (page2) => {
			originalOnSuccess(page2);
			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 isPlainObject(value) {
	return typeof value === "object" && value !== null && !Array.isArray(value);
}
function hasComponentKey(value) {
	return isPlainObject(value) && "component" in value;
}
function hasComponentEntry(value, isComponent) {
	return "component" in value && isComponent(value.component);
}
function isNamedLayouts(value, isComponent) {
	if (!isPlainObject(value) || isComponent(value) || hasComponentEntry(value, isComponent)) return false;
	return Object.values(value).every((v) => isComponent(v) || Array.isArray(v) && isComponent(v[0]) || hasComponentKey(v) && isComponent(v.component));
}
function isPropsObject(value, isComponent) {
	return isPlainObject(value) && !isComponent(value) && !hasComponentEntry(value, isComponent) && !isNamedLayouts(value, isComponent);
}
function isPropsObjectOrCallback(value, isComponent) {
	if (isPropsObject(value, isComponent)) return true;
	if (!isPlainObject(value) || isComponent(value) || hasComponentEntry(value, isComponent)) return false;
	const values = Object.values(value);
	return values.length > 0 && values.every((v) => typeof v === "function");
}
function isTuple(value, isComponent) {
	return Array.isArray(value) && value.length === 2 && isComponent(value[0]) && isPlainObject(value[1]) && !isComponent(value[1]);
}
function extract(item, isComponent) {
	if (Array.isArray(item) && isComponent(item[0])) return {
		component: item[0],
		props: item[1] ?? {}
	};
	if (hasComponentKey(item) && isComponent(item.component)) return {
		component: item.component,
		props: item.props ?? {}
	};
	if (isComponent(item)) return {
		component: item,
		props: {}
	};
	throw new Error(`Invalid layout definition: received ${typeof item}`);
}
function normalizeLayouts(layout, isComponent, isRenderFunction) {
	if (!layout || isRenderFunction && isRenderFunction(layout)) return [];
	if (isNamedLayouts(layout, isComponent)) return Object.entries(layout).map(([name, value]) => ({
		...extract(value, isComponent),
		name
	}));
	if (isTuple(layout, isComponent)) return [{
		component: layout[0],
		props: layout[1] ?? {}
	}];
	if (Array.isArray(layout)) return layout.map((item) => extract(item, isComponent));
	if (hasComponentKey(layout) && isComponent(layout.component)) return [{
		component: layout.component,
		props: layout.props ?? {}
	}];
	if (isComponent(layout)) return [{
		component: layout,
		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: .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 = clamp(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 key in barStyles) bar.style[key] = barStyles[key];
		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(() => {
				remove();
				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(.3 + .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 = {
			.1: [0, .2],
			.04: [.2, .5],
			.02: [.5, .8],
			.005: [.8, .99]
		};
		for (const r in ranges) if (n >= ranges[r][0] && n < ranges[r][1]) return parseFloat(r);
		return 0;
	})();
	return set7(clamp(n + amount, 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 remove = () => {
	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 clamp(n, min, max) {
	if (n < min) return min;
	if (n > max) return max;
	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$1.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,
	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(delay) {
	document.addEventListener("inertia:start", (e) => handleStartEvent(e, delay));
	document.addEventListener("inertia:progress", handleProgressEvent);
}
function handleStartEvent(event, delay) {
	if (!event.detail.visit.showProgress) progress.hide();
	const timeout = setTimeout(() => progress.start(), delay);
	document.addEventListener("inertia:finish", (e) => finish(e, timeout), { once: true });
}
function handleProgressEvent(event) {
	if (progress.isStarted() && event.detail.progress?.percentage) progress.set(Math.max(progress.getStatus(), event.detail.progress.percentage / 100 * .9));
}
function finish(event, timeout) {
	clearTimeout(timeout);
	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 = 250, color = "#29d", includeCSS = true, showSpinner = false, popover = null } = {}) {
	addEventListeners(delay);
	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);
	return select.multiple ? JSON.stringify(oldSelectedOptions.sort()) !== JSON.stringify(newSelectedOptions.sort()) : select.value !== oldValue;
}
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 if (resetFormElement(node, defaultValues[index] !== void 0 ? [defaultValues[index]] : [defaultValues[0] ?? null].filter(Boolean))) hasChanged = true;
		}
	});
	else if (isFormElement(elements)) hasChanged = resetFormElement(elements, defaultValues);
	return hasChanged;
}
function resetFormFields(formElement, defaults, 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([
			...defaults.keys(),
			...formData.keys(),
			...formElementNames
		])];
	}
	let hasChanged = false;
	fieldNames.forEach((fieldName) => {
		const elements = formElement.elements.namedItem(fieldName);
		if (elements) {
			if (resetFieldElements(elements, defaults.getAll(fieldName))) hasChanged = true;
		}
	});
	if (hasChanged && resetEntireForm) formElement.dispatchEvent(new CustomEvent("reset", {
		bubbles: true,
		cancelable: true,
		detail: { [FormComponentResetSymbol]: true }
	}));
}
function buildSSRBody(id, page2, html) {
	return `<script data-page="${id}" type="application/json">${JSON.stringify(page2).replace(/\//g, "\\/")}<\/script><div data-server-rendered="true" id="${id}">${html}</div>`;
}
var router = new Router();
/* NProgress, (c) 2013, 2014 Rico Sta. Cruz - http://ricostacruz.com/nprogress
* @license MIT */
//#endregion
//#region 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_default = { 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$1(hasCallbacks(key3) ? this[key3].__remember() : this[key3])
			}), {}), rememberKey);
		}, {
			immediate: true,
			deep: true
		});
	});
} };
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;
	let defaults = cloneDeep$1(restored?.data ?? cloneDeep$1(resolveData()));
	let transform = (data) => data;
	let validatorRef = null;
	let withAllErrors = null;
	const withAllErrorsEnabled = () => withAllErrors ?? config.get("form.withAllErrors");
	let recentlySuccessfulTimeoutId;
	let defaultsCalledInOnSuccess = false;
	let rememberExcludeKeys = [];
	const typedForm = reactive({
		...cloneDeep$1(defaults),
		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((client) => {
				const { method, url } = precognitionEndpoint();
				const transformedData = cloneDeep$1(transform(this.data()));
				return client[method](url, transformedData);
			}, cloneDeep$1(defaults));
			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 = transform(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(defaults).reduce((carry, key2) => {
				return set(carry, key2, get(this, key2));
			}, {});
		},
		transform(callback) {
			transform = 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") {
				defaults = cloneDeep$1(this.data());
				this.isDirty = false;
			} else defaults = typeof fieldOrFields === "string" ? set(cloneDeep$1(defaults), fieldOrFields, maybeValue) : Object.assign({}, cloneDeep$1(defaults), fieldOrFields);
			validatorRef?.defaults(defaults);
			return this;
		},
		reset(...fields) {
			const clonedData = cloneDeep$1(isDataFunction ? cloneDeep$1(resolveData()) : defaults);
			if (fields.length === 0) {
				if (isDataFunction) defaults = clonedData;
				Object.assign(this, clonedData);
			} else fields.filter((key2) => has(clonedData, key2)).forEach((key2) => {
				if (isDataFunction) set(defaults, 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);
		}
	});
	if (restored?.errors) typedForm.setError(restored.errors);
	watch(typedForm, () => {
		typedForm.isDirty = !isEqual(typedForm.data(), defaults);
	}, {
		immediate: true,
		deep: true
	});
	watch(typedForm, (newValue) => {
		if (!rememberKey) return;
		const storedData = router.restore(rememberKey);
		const newData = cloneDeep$1(newValue.__remember());
		if (!isEqual(storedData, newData)) router.remember(newData, rememberKey);
	}, {
		immediate: true,
		deep: true
	});
	if (precognitionEndpoint) typedForm.withPrecognition(precognitionEndpoint);
	return {
		form: typedForm,
		setDefaults: (newDefaults) => {
			defaults = newDefaults;
		},
		getTransform: () => transform,
		getPrecognitionEndpoint: () => precognitionEndpoint ?? null,
		markAsSuccessful: () => {
			typedForm.clearErrors();
			typedForm.wasSuccessful = true;
			typedForm.recentlySuccessful = true;
			recentlySuccessfulTimeoutId = setTimeout(() => typedForm.recentlySuccessful = false, config.get("form.recentlySuccessfulDuration"));
		},
		wasDefaultsCalledInOnSuccess: () => defaultsCalledInOnSuccess,
		resetDefaultsCalledInOnSuccess: () => {
			defaultsCalledInOnSuccess = false;
		},
		setRememberExcludeKeys: (keys) => {
			rememberExcludeKeys = keys;
		},
		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);
	validateFormDataKeys(typeof data === "function" ? cloneDeep$1(data()) : cloneDeep$1(data));
	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 = (method) => (url, options = {}) => {
		form.submit(method, url, options);
	};
	Object.assign(form, {
		submit(...args2) {
			const { method, 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 (page2) => {
					markAsSuccessful();
					const onSuccess = options.onSuccess ? await options.onSuccess(page2) : null;
					if (!wasDefaultsCalledInOnSuccess()) {
						setDefaults(cloneDeep$1(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 (method === "delete") router.delete(url, {
				..._options,
				data: transformedData
			});
			else router[method](url, transformedData, _options);
		},
		get: createSubmitMethod("get"),
		post: createSubmitMethod("post"),
		put: createSubmitMethod("put"),
		patch: createSubmitMethod("patch"),
		delete: createSubmitMethod("delete"),
		cancel() {
			if (cancelToken) cancelToken.cancel();
		},
		dontRemember(...keys) {
			setRememberExcludeKeys(keys);
			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 page = ref();
var pageAccessor = null;
var layout = shallowRef(null);
var key = ref(void 0);
var headManager;
var app_default = 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;
		page.value = {
			...initialPage,
			flash: initialPage.flash ?? {}
		};
		key.value = void 0;
		const isServer = typeof window === "undefined";
		headManager = createHeadManager(isServer, titleCallback || ((title) => title), onHeadUpdate || (() => {}));
		if (!isServer) {
			router.init({
				initialPage,
				resolveComponent,
				swapComponent: async (options) => {
					if (!options.preserveState) resetLayoutProps();
					component.value = markRaw(options.component);
					page.value = options.page;
					key.value = options.preserveState ? key.value : Date.now();
				},
				onFlash: (flash) => {
					page.value = {
						...page.value,
						flash
					};
				}
			});
			router.on("navigate", () => headManager.forceUpdate());
		}
		return () => {
			if (component.value) {
				component.value.inheritAttrs = !!component.value.inheritAttrs;
				const child = h(component.value, {
					...page.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 result = layoutValue(page.value.props);
					if (isPropsObjectOrCallback(result, isComponent)) {
						effectiveLayout = defaultLayout?.(page.value.component, page.value);
						callbackProps = result;
					} else effectiveLayout = result;
				} else if (isPropsObject(layoutValue, isComponent)) {
					effectiveLayout = defaultLayout?.(page.value.component, page.value);
					callbackProps = layoutValue;
				} else effectiveLayout = layoutValue ?? defaultLayout?.(page.value.component, page.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 = isServer ? {
							shared: {},
							named: {}
						} : state.value;
						return layouts.reduceRight((childNode, layout2) => {
							const layoutComponent = layout2.component;
							layoutComponent.inheritAttrs = !!layoutComponent.inheritAttrs;
							return h(layoutComponent, {
								...page.value.props,
								...layout2.props,
								...dynamicProps.shared,
								...layout2.name ? dynamicProps.named[layout2.name] || {} : {}
							}, () => childNode);
						}, child);
					}
				}
				return child;
			}
		};
	}
});
var plugin = { install(app) {
	router.form = useForm;
	Object.defineProperty(app.config.globalProperties, "$inertia", { get: () => router });
	Object.defineProperty(app.config.globalProperties, "$page", { get: () => page.value });
	Object.defineProperty(app.config.globalProperties, "$headManager", { get: () => headManager });
	app.mixin(remember_default);
} };
function usePage() {
	if (!pageAccessor) pageAccessor = reactive({
		props: computed(() => page.value?.props),
		url: computed(() => page.value?.url),
		component: computed(() => page.value?.component),
		version: computed(() => page.value?.version),
		clearHistory: computed(() => page.value?.clearHistory),
		deferredProps: computed(() => page.value?.deferredProps),
		rescuedProps: computed(() => page.value?.rescuedProps),
		mergeProps: computed(() => page.value?.mergeProps),
		prependProps: computed(() => page.value?.prependProps),
		deepMergeProps: computed(() => page.value?.deepMergeProps),
		matchPropsOn: computed(() => page.value?.matchPropsOn),
		rememberedState: computed(() => page.value?.rememberedState),
		encryptHistory: computed(() => page.value?.encryptHistory),
		scrollProps: computed(() => page.value?.scrollProps),
		flash: computed(() => page.value?.flash)
	});
	return pageAccessor;
}
async function createInertiaApp({ id = "app", resolve, setup, title, progress: progress2 = {}, page: page2, render, defaults = {}, nonce, http: http3, layout: layout2, withApp, dev = !!import.meta.env?.DEV } = {}) {
	config.replace(defaults);
	if (nonce) config.set("nonce", nonce);
	if (http3) http.setClient(http3);
	if (dev) exposeInterceptors();
	const isServer = typeof window === "undefined";
	const resolveComponent = (name, page3) => Promise.resolve(resolve(name, page3)).then((module) => module.default || module);
	if (isServer && !page2 && !render) return async (page3, renderToString) => {
		let head2 = [];
		const props = {
			initialPage: page3,
			initialComponent: await resolveComponent(page3.component, page3),
			resolveComponent,
			titleCallback: title,
			onHeadUpdate: (elements) => head2 = 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 body = buildSSRBody(id, page3, await renderToString(vueApp2));
		return {
			head: head2,
			body
		};
	};
	const initialPage = page2 || getInitialPageFromDOM(id);
	let head = [];
	const vueApp = await Promise.all([resolveComponent(initialPage.component, initialPage), router.decryptHistory().catch(() => {})]).then(([initialComponent]) => {
		const props = {
			initialPage,
			initialComponent,
			resolveComponent,
			titleCallback: title,
			onHeadUpdate: isServer ? (elements) => head = elements : void 0,
			defaultLayout: layout2
		};
		if (isServer) 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 (!isServer && progress2) setupProgress(progress2);
	if (isServer && render && vueApp) {
		const body = buildSSRBody(id, initialPage, await render(vueApp));
		return {
			head,
			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 page2 = usePage();
		const keys = computed(() => Array.isArray(props.data) ? props.data : [props.data]);
		const rescuedKeys = computed(() => new Set(page2.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, keys.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 = keys.value.every((key2) => get(page2.props, key2) !== void 0);
			const hasRescuedProps = keys.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 noop = () => 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: noop
		},
		onBefore: {
			type: Function,
			default: noop
		},
		onStart: {
			type: Function,
			default: noop
		},
		onProgress: {
			type: Function,
			default: noop
		},
		onFinish: {
			type: Function,
			default: noop
		},
		onCancel: {
			type: Function,
			default: noop
		},
		onSuccess: {
			type: Function,
			default: noop
		},
		onError: {
			type: Function,
			default: noop
		},
		onSubmitComplete: {
			type: Function,
			default: noop
		},
		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(() => method.value, () => getUrlAndData()[0]).transform(getTransformedData).setValidationTimeout(props.validationTimeout);
		if (props.validateFiles) form.validateFiles();
		if (props.withAllErrors ?? config$1.get("form.withAllErrors")) form.withAllErrors();
		const formElement = ref();
		const method = 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(method.value, isUrlMethodPair(props.action) ? props.action.url : props.action, getData(submitter), props.queryStringArrayFormat);
		};
		const submit = (submitter) => {
			const [url, data] = getUrlAndData(submitter);
			if (submitter?.getAttribute("formtarget") === "_blank" && method.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 result = await props.onSuccess?.(...args);
					props.onSubmitComplete?.(exposed);
					maybeReset(props.resetOnSuccess);
					if (props.setDefaultsOnSuccess === true) defaults();
					return result;
				},
				onError: (...args) => {
					props.onError?.(...args);
					maybeReset(props.resetOnError);
				},
				...props.options
			};
			form.transform(() => props.transform(data)).submit(method.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 defaults = () => {
			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,
			getData,
			getFormData,
			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: method.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}="${escape(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="">${escape(title)}</title>`);
	return elements;
}
function renderNodes(nodes, title) {
	return addTitleElement(nodes.flatMap((node) => resolveNode(node)).map((node) => renderTag(node)).filter((node) => node), 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_default = 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 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_default = 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({
			getPropName: () => props.data,
			inReverseMode: () => props.reverse,
			shouldFetchNext: () => !props.onlyPrevious,
			shouldFetchPrevious: () => !props.onlyNext,
			shouldPreserveUrl: () => props.preserveUrl,
			getReloadOptions: () => props.params,
			getTriggerMargin: () => props.buffer,
			getStartElement: () => startElement.value,
			getEndElement: () => endElement.value,
			getItemsElement: () => itemsElement.value,
			getScrollableParent: () => scrollableParent.value,
			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());
			if (props.autoScroll !== void 0 ? props.autoScroll : props.reverse) 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 noop2 = () => {};
var link_default = 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: noop2
		},
		onProgress: {
			type: Function,
			default: noop2
		},
		onFinish: {
			type: Function,
			default: noop2
		},
		onBefore: {
			type: Function,
			default: noop2
		},
		onCancel: {
			type: Function,
			default: noop2
		},
		onSuccess: {
			type: Function,
			default: noop2
		},
		onError: {
			type: Function,
			default: noop2
		},
		onCancelToken: {
			type: Function,
			default: noop2
		},
		onPrefetching: {
			type: Function,
			default: noop2
		},
		onPrefetched: {
			type: Function,
			default: noop2
		},
		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 config.get("prefetch.cacheFor");
		});
		onMounted(() => {
			if (prefetchModes.value.includes("mount")) prefetch();
		});
		onUnmounted(() => {
			clearTimeout(hoverTimeout.value);
		});
		const method = 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 method.value !== "get" ? "button" : props.as.toLowerCase();
		});
		const mergeDataArray = computed(() => mergeDataIntoQueryString(method.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: method.value,
			replace: props.replace,
			preserveScroll: props.preserveScroll,
			preserveState: props.preserveState ?? method.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();
				}, config.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);
		};
	}
});
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 (method, url, options) => {
		if (options.onBefore?.() === false) return Promise.reject(/* @__PURE__ */ new Error("Request cancelled by onBefore"));
		resetDefaultsCalledInOnSuccess();
		resetBeforeSubmit();
		abortController = new AbortController();
		options.onCancelToken?.({ cancel: () => abortController?.abort() });
		options.optimistic = options.optimistic ?? pendingOptimisticCallback ?? void 0;
		pendingOptimisticCallback = null;
		let snapshot;
		if (options.optimistic) {
			snapshot = cloneDeep$1(form.data());
			const optimisticData = options.optimistic(cloneDeep$1(snapshot));
			if (optimisticData) Object.keys(optimisticData).forEach((key2) => {
				form[key2] = optimisticData[key2];
			});
		}
		form.processing = true;
		options.onStart?.();
		const transformedData = getTransform()(form.data());
		const useFormData = hasFiles(transformedData);
		let requestUrl = url;
		let requestData;
		let contentType;
		if (method === "get") {
			const [urlWithParams] = mergeDataIntoQueryString(method, 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,
				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$1(form.data()));
				form.isDirty = false;
				return responseData;
			}
			throw new HttpResponseError(`Request failed with status ${response.status}`, response, url);
		} catch (error) {
			if (snapshot) Object.keys(snapshot).forEach((key2) => {
				form[key2] = snapshot[key2];
			});
			if (error instanceof HttpResponseError) {
				if (error.response.status === 422) {
					const validationErrors = JSON.parse(error.response.data).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 HttpCancelledError || error instanceof Error && error.name === "AbortError") {
				options.onCancel?.();
				throw new HttpCancelledError("Request was cancelled", url);
			}
			options.onNetworkError?.(error instanceof Error ? error : /* @__PURE__ */ new Error("Unknown error"));
			throw error;
		} finally {
			finishProcessing();
			abortController = null;
			options.onFinish?.();
		}
	};
	const createSubmitMethod = (method) => async (url, options = {}) => {
		return submit(method, 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(...keys) {
			setRememberExcludeKeys(keys);
			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, destroy } = router.poll(interval, requestOptions, {
		...options,
		autoStart: false
	});
	onMounted(() => {
		if (options.autoStart ?? true) start();
	});
	onUnmounted(() => {
		destroy();
	});
	return {
		stop,
		start
	};
}
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$1(restored)) : cloneDeep$1(restored));
	watch(remembered, (newValue) => {
		router.remember(cloneDeep$1(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 page2 = usePage();
		const keys = 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(() => keys.value.map((key2) => get(page2.props, key2)), () => {
			const exists = keys.value.length > 0 && keys.value.every((key2) => get(page2.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 config = config$1.extend({});
//#endregion
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, config, createForm, createInertiaApp, http, progress, resetLayoutProps, router, setLayoutProps, useForm, useFormContext, useHttp, usePage, usePoll, usePrefetch, useRemember };

//# sourceMappingURL=@inertiajs_vue3.js.map