UNPKG

marko

Version:

Optimized runtime for Marko templates.

4,163 lines • 148 kB
//#region src/common/attr-tag.ts
const empty = [];
const rest = Symbol("Attribute Tag");
function attrTag(attrs) {
	attrs[Symbol.iterator] = attrTagIterator;
	attrs[rest] = empty;
	return attrs;
}
function attrTags(first, attrs) {
	if (first) {
		if (first[rest] === empty) first[rest] = [attrs];
		else first[rest].push(attrs);
		return first;
	}
	return attrTag(attrs);
}
function* attrTagIterator() {
	yield this;
	yield* this[rest];
}
//#endregion
//#region src/common/constants/accessor-prefix.debug.ts
const BranchScopes = "BranchScopes:";
const ConditionalRenderer = "ConditionalRenderer:";
const ControlledHandler = "ControlledHandler:";
const ControlledType = "ControlledType:";
const ControlledValue = "ControlledValue:";
const EventAttributes = "EventAttributes:";
const CatchContent = "#CatchContent";
const ClosestBranchId = "#ClosestBranchId";
const LoopKey = "#LoopKey";
const PlaceholderBranch = "#PlaceholderBranch";
const PlaceholderContent = "#PlaceholderContent";
const Renderer = "#Renderer";
const TagVariable = "#TagVariable";
const Owner = "owner";
const Embed = "embed";
const Lazy = "lazy";
//#endregion
//#region src/common/helpers.ts
const invalidNativeAttrNameReg = /^[^a-z_]|[^a-z0-9._:-]/i;
const knownWrongAttrs = {
	className: "class",
	classList: "class",
	htmlFor: "for",
	acceptCharset: "accept-charset",
	httpEquiv: "http-equiv",
	defaultValue: "value",
	defaultChecked: "checked",
	dangerouslySetInnerHTML: "$!{html}",
	key: "<for by>",
	ref: "<tag/ref>",
	"v-if": "<if>",
	"v-else": "<else>",
	"v-else-if": "<else if>",
	"v-for": "<for>",
	"v-show": "<if>",
	"v-model": "value:=state",
	"v-bind": "...attrs",
	"v-html": "$!{html}",
	"v-text": "${text}"
};
function getWrongAttrSuggestion(name) {
	if (Object.hasOwn(knownWrongAttrs, name)) return knownWrongAttrs[name];
	const colon = name.indexOf(":");
	if (colon > 0) {
		const rest = name.slice(colon + 1);
		switch (name.slice(0, colon)) {
			case "class": return `class={ ${rest}: condition }`;
			case "style": return `style={ ${rest}: value }`;
			case "on":
			case "v-on": return `on${rest.charAt(0).toUpperCase()}${rest.slice(1)}`;
			case "bind":
			case "v-model": return `${rest}:=state`;
			case "v-bind": return rest;
		}
	}
}
function stringifyClassEntry(name, value) {
	return value ? name : "";
}
const warnedStyleKeys = /* @__PURE__ */ new Set();
function stringifyStyleEntry(name, value) {
	if (/[A-Z]/.test(name) && !name.includes("-") && !warnedStyleKeys.has(name)) {
		warnedStyleKeys.add(name);
		console.warn(`\`${name}\` is not a CSS property name; \`style\` object keys are written verbatim, so it renders as invalid CSS. Use \`${name.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase()).replace(/^ms-/, "-ms-")}\`.`);
	}
	if (value !== value || typeof value === "bigint" && !value) console.warn(`The \`${name}\` style value \`${value !== value ? "NaN" : "0n"}\` drops the declaration; convert it to a string or number to render it.`);
	return value || value === 0 ? escapeStyleAttr(name) + ":" + escapeStyleAttr(value + "") : "";
}
const unsafeStyleAttrReg = /[\\;]/g;
const replaceUnsafeStyleAttr = (c) => c === ";" ? "\\3B " : "\\\\";
function escapeStyleAttr(str) {
	return unsafeStyleAttrReg.test(str) ? str.replace(unsafeStyleAttrReg, replaceUnsafeStyleAttr) : str;
}
function escapeStyleValue(str) {
	let closers = "";
	const result = str.replace(/[\\"'{};<>]|\/(?=\*)/g, (c) => c === "<" ? "\\3C " : c === ";" ? "\\3B " : c === "{" ? "\\7B " : "\\" + c);
	for (const c of result) if (c === "(") closers = ")" + closers;
	else if (c === "[") closers = "]" + closers;
	else if (c === closers[0]) closers = closers.slice(1);
	return result + closers;
}
const toDelimitedString = function toDelimitedString(val, delimiter, stringify) {
	let str = "";
	let sep = "";
	let part;
	if (val) {
		if (typeof val !== "object") str += val;
		else if (Array.isArray(val)) for (const v of val) {
			part = toDelimitedString(v, delimiter, stringify);
			if (part) {
				str += sep + part;
				sep = delimiter;
			}
		}
		else for (const name in val) {
			part = stringify(name, val[name]);
			if (part) {
				str += sep + part;
				sep = delimiter;
			}
		}
	}
	return str;
};
function isEventHandler(name) {
	return /^on[A-Z-]/.test(name);
}
function getEventType(name) {
	return name[2] === "-" ? name.slice(3) : name.slice(2).toLowerCase();
}
function hasKeys(obj) {
	for (const _ in obj) return true;
	return false;
}
function isNullishOrFalse(value) {
	return value == null || value === false;
}
function isNotNullishOrFalse(value) {
	return value != null && value !== false;
}
function isPromise(value) {
	return value != null && typeof value.then === "function";
}
function normalizeDynamicRenderer(value) {
	if (value) {
		if (typeof value === "string") return value;
		const normalized = value.content || value.default || value;
		if (!((typeof normalized === "object" || typeof normalized === "function") && "id" in normalized)) {
			if (value.content) throw new Error(`A dynamic tag must be a string tag name (like \`"div"\`) or a Marko template/component, but received an object whose \`content\` is not a template/component.`);
			if (typeof value !== "object" && typeof value !== "function") throw new Error(`A dynamic tag must be a string tag name (like \`"div"\`) or a Marko template/component, but received a ${typeof value}.`);
		}
		if ("id" in normalized) return normalized;
	}
}
//#endregion
//#region src/common/errors.ts
const lowercaseOnAttrReg = /^on[a-z]/;
function assertValidAttrValue(name, value) {
	if (value && typeof value !== "string" && lowercaseOnAttrReg.test(name)) throw new Error(`The \`${name}\` attribute must be a string or a falsey value (\`null\`, \`undefined\`, \`false\`, \`0\`, …), but received type "${typeof value}". To attach an event listener, use the \`on${name[2].toUpperCase()}${name.slice(3)}\` event handler instead.`);
	if (typeof value === "function") throw new Error(`The \`${name}\` attribute cannot be a function.${/Change$/.test(name) ? " A change handler is only used when its matching controllable attribute combination applies." : ""}`);
	const unrenderable = describeUnrenderable(value);
	if (unrenderable) throw new Error(`The \`${name}\` attribute cannot be ${unrenderable}.`);
}
function _assert_class_toggles(classes, toggles) {
	{
		const written = new Set(classes.split(" "));
		for (const toggle of toggles) {
			const names = new Set(toggle.split(" "));
			for (const name of names) if (written.has(name)) throw new Error(`The toggled class \`${name}\` is also written by another part of the \`class\` value; a toggled class may appear only once.`);
			for (const name of names) written.add(name);
		}
	}
}
function assertValidTextValue(value) {
	const unrenderable = describeUnrenderable(value);
	if (unrenderable) throw new Error(`Text content cannot be ${unrenderable}.`);
	if (isSilentlyDropped(value)) console.warn(`Text content of \`${describeDropped(value)}\` renders as nothing; convert it to a string or number to render it.`);
}
function isSilentlyDropped(value) {
	return value !== value || typeof value === "bigint" && !value;
}
function describeDropped(value) {
	return value !== value ? "NaN" : "0n";
}
function describeUnrenderable(value) {
	if (typeof value === "symbol") return "a symbol";
	if (typeof value === "object" && value !== null) {
		let stringified;
		try {
			stringified = `${value}`;
		} catch {
			stringified = "[object Object]";
		}
		if (/^\[object \w+\]$/.test(stringified)) return stringified === "[object Promise]" ? "a promise (use the `<await>` tag to render its resolved value)" : stringified === "[object Object]" ? "a plain object (it would render as `[object Object]`)" : `a value that renders as \`${stringified}\``;
	}
}
function assertValidLoopKey(key, seenKeys) {
	if (typeof key !== "string" && typeof key !== "number" || key !== key) throw new Error(`A \`<for>\` tag's \`by\` attribute must return a string or number for each item, but received ${key === null || key !== key ? key : `type "${typeof key}"`}.`);
	if (seenKeys) {
		if (seenKeys.has(key)) throw new Error(`A \`<for>\` tag's \`by\` attribute must return a unique value for each item, but \`${key}\` was used more than once.`);
		seenKeys.add(key);
	}
}
function assertValidList(value) {
	if (value && typeof value[Symbol.iterator] !== "function") throw new Error(`A \`<for>\` tag's \`of\` attribute must be an iterable, such as an array, but received ${describeForValue(value)}.`);
}
function assertOptionalRangeNumber(name, value) {
	if (value && (typeof value !== "number" || !isFinite(value))) throw new Error(`A \`<for>\` tag's \`${name}\` attribute must be a finite number, but received ${describeForValue(value)}.`);
}
function assertValidRangeBound(name, value) {
	if (!isFinite(value)) throw new Error(`A \`<for>\` tag's \`${name}\` attribute must be a finite number, but received ${describeForValue(value)}.`);
}
function describeForValue(value) {
	return typeof value === "number" || typeof value === "bigint" ? `\`${value}\`` : value === null ? "null" : `type "${typeof value}"`;
}
function assertValidAttrName(name) {
	if (invalidNativeAttrNameReg.test(name)) throw new Error(`Invalid attribute name: ${JSON.stringify(name)}`);
	const suggestion = getWrongAttrSuggestion(name);
	if (suggestion) throw new Error(`\`${name}\` is not a valid attribute, did you mean \`${suggestion}\`?`);
}
function _el_read_error() {
	throw new Error("Element references can only be read in scripts and event handlers.");
}
function _hoist_read_error() {
	throw new Error("Hoisted values can only be read in scripts and event handlers.");
}
function _assert_hoist(value) {
	if (value !== void 0 && typeof value !== "function") throw new Error(`Hoisted values must be functions, received type "${typeof value}".`);
}
function assertExclusiveAttrs(attrs, onError = throwErr, isSet = isTruthy) {
	if (attrs) {
		let exclusiveAttrs;
		if (isSet(attrs.checkedChange)) (exclusiveAttrs ||= []).push("checkedChange");
		if ("checkedValue" in attrs) {
			(exclusiveAttrs ||= []).push("checkedValue");
			if ("checked" in attrs) exclusiveAttrs.push("checked");
		} else if (isSet(attrs.checkedValueChange)) {
			(exclusiveAttrs ||= []).push("checkedValueChange");
			if ("checked" in attrs) exclusiveAttrs.push("checked");
		}
		if (isSet(attrs.valueChange)) {
			(exclusiveAttrs ||= []).push("valueChange");
			if ("checked" in attrs && !exclusiveAttrs.includes("checked")) exclusiveAttrs.push("checked");
		}
		if (exclusiveAttrs && exclusiveAttrs.length > 1) onError(`The attributes ${joinWithAnd(exclusiveAttrs)} are mutually exclusive.`);
	}
}
function assertNoValueBindingOnCheckable(type, valueChange) {
	if (valueChange && /^(?:button|checkbox|hidden|image|radio|reset|submit)$/i.test(type)) console.error(`\`valueChange\` cannot be used on a \`type="${type}"\` \`<input>\` — user interaction can never change its \`value\`.` + (/^[cr]/i.test(type) ? " Bind `checked` or `checkedValue` instead." : ""));
}
function assertHandlerIsFunction(name, value) {
	if (value && typeof value !== "function") throw new Error(`The \`${name}\` handler must be a function or a falsey value (\`null\`, \`undefined\`, \`false\`, \`0\`, …), but received type "${typeof value}".`);
}
function assertValidTagName(tagName) {
	if (!/^[a-z][a-z0-9._-]*$/i.test(tagName)) throw new Error(`Invalid tag name: "${tagName}". Tag names must start with a letter and contain only letters, numbers, periods, hyphens, and underscores.`);
}
function isTruthy(value) {
	return value;
}
function throwErr(msg) {
	throw new Error(msg);
}
function joinWithAnd(a) {
	switch (a.length) {
		case 0: return "";
		case 1: return a[0];
		case 2: return `${a[0]} and ${a[1]}`;
		default: return `${a.slice(0, -1).join(", ")}, and ${a[a.length - 1]}`;
	}
}
//#endregion
//#region src/common/meta.ts
const DYNAMIC_TAG_SCRIPT_REGISTER_ID = "_dynamicTagScript";
const DYNAMIC_TAG_VAR_REGISTER_ID = "_dynamicTagVar";
const PLACEHOLDER_DISMISS_REGISTER_ID = "_placeholderDismiss";
//#endregion
//#region src/common/opt.ts
function reduce(opt, cb, acc) {
	if (opt) {
		if (Array.isArray(opt)) for (const item of opt) acc = cb(acc, item);
		else acc = cb(acc, opt);
	}
	return acc;
}
function push(opt, item) {
	return opt ? Array.isArray(opt) ? (opt.push(item), opt) : [opt, item] : item;
}
function concat(opt, other) {
	if (!opt) return other;
	if (!other) return opt;
	if (Array.isArray(opt)) {
		if (Array.isArray(other)) for (const item of other) opt.push(item);
		else opt.push(other);
		return opt;
	}
	return Array.isArray(other) ? [opt, ...other] : [opt, other];
}
//#endregion
//#region src/html/serializer.ts
const K_SCOPE_ID = Symbol("Scope ID");
const kTouchedIterator = /* @__PURE__ */ Symbol.for("marko.touchedIterator");
const { hasOwnProperty } = {};
const objectProto = Object.prototype;
const arrayProto = Array.prototype;
const Generator = (/* @__PURE__ */ (function* () {})()).constructor;
const AsyncGenerator = (/* @__PURE__ */ (async function* () {})()).constructor;
patchIteratorNext(Generator.prototype);
patchIteratorNext(AsyncGenerator.prototype);
const REGISTRY = /* @__PURE__ */ new WeakMap();
const KNOWN_SYMBOLS = /* @__PURE__ */ (() => {
	const KNOWN_SYMBOLS = /* @__PURE__ */ new Map();
	for (const name of Object.getOwnPropertyNames(Symbol)) {
		const symbol = Symbol[name];
		if (typeof symbol === "symbol") KNOWN_SYMBOLS.set(symbol, "Symbol." + name);
	}
	return KNOWN_SYMBOLS;
})();
const KNOWN_FUNCTIONS = /* @__PURE__ */ (() => /* @__PURE__ */ new Map([
	[AggregateError, "AggregateError"],
	[Array, "Array"],
	[Array.from, "Array.from"],
	[Array.isArray, "Array.isArray"],
	[Array.of, "Array.of"],
	[ArrayBuffer, "ArrayBuffer"],
	[ArrayBuffer.isView, "ArrayBuffer.isView"],
	[Atomics.add, "Atomics.add"],
	[Atomics.and, "Atomics.and"],
	[Atomics.compareExchange, "Atomics.compareExchange"],
	[Atomics.exchange, "Atomics.exchange"],
	[Atomics.isLockFree, "Atomics.isLockFree"],
	[Atomics.load, "Atomics.load"],
	[Atomics.notify, "Atomics.notify"],
	[Atomics.or, "Atomics.or"],
	[Atomics.store, "Atomics.store"],
	[Atomics.sub, "Atomics.sub"],
	[Atomics.wait, "Atomics.wait"],
	[BigInt, "BigInt"],
	[BigInt.asIntN, "BigInt.asIntN"],
	[BigInt.asUintN, "BigInt.asUintN"],
	[BigInt64Array, "BigInt64Array"],
	[BigInt64Array.from, "BigInt64Array.from"],
	[BigInt64Array.of, "BigInt64Array.of"],
	[BigUint64Array, "BigUint64Array"],
	[BigUint64Array.from, "BigUint64Array.from"],
	[BigUint64Array.of, "BigUint64Array.of"],
	[Boolean, "Boolean"],
	[console.assert, "console.assert"],
	[console.clear, "console.clear"],
	[console.count, "console.count"],
	[console.countReset, "console.countReset"],
	[console.debug, "console.debug"],
	[console.dir, "console.dir"],
	[console.dirxml, "console.dirxml"],
	[console.error, "console.error"],
	[console.group, "console.group"],
	[console.groupCollapsed, "console.groupCollapsed"],
	[console.groupEnd, "console.groupEnd"],
	[console.info, "console.info"],
	[console.log, "console.log"],
	[console.table, "console.table"],
	[console.time, "console.time"],
	[console.timeEnd, "console.timeEnd"],
	[console.timeLog, "console.timeLog"],
	[console.timeStamp, "console.timeStamp"],
	[console.trace, "console.trace"],
	[console.warn, "console.warn"],
	[DataView, "DataView"],
	[Date, "Date"],
	[Date.now, "Date.now"],
	[Date.parse, "Date.parse"],
	[Date.UTC, "Date.UTC"],
	[decodeURI, "decodeURI"],
	[decodeURIComponent, "decodeURIComponent"],
	[encodeURI, "encodeURI"],
	[encodeURIComponent, "encodeURIComponent"],
	[Error, "Error"],
	[EvalError, "EvalError"],
	[Float32Array, "Float32Array"],
	[Float32Array.from, "Float32Array.from"],
	[Float32Array.of, "Float32Array.of"],
	[Float64Array, "Float64Array"],
	[Float64Array.from, "Float64Array.from"],
	[Float64Array.of, "Float64Array.of"],
	[Function, "Function"],
	[globalThis.atob, "atob"],
	[globalThis.btoa, "btoa"],
	[globalThis.clearInterval, "clearInterval"],
	[globalThis.clearTimeout, "clearTimeout"],
	[globalThis.crypto?.getRandomValues, "crypto.getRandomValues"],
	[globalThis.crypto?.randomUUID, "crypto.randomUUID"],
	[globalThis.fetch, "fetch"],
	[globalThis.performance?.now, "performance.now"],
	[globalThis.queueMicrotask, "queueMicrotask"],
	[globalThis.setInterval, "setInterval"],
	[globalThis.setTimeout, "setTimeout"],
	[globalThis.structuredClone, "structuredClone"],
	[globalThis.URL, "URL"],
	[globalThis.URLSearchParams, "URLSearchParams"],
	[globalThis.WritableStream, "WritableStream"],
	[Int16Array, "Int16Array"],
	[Int16Array.from, "Int16Array.from"],
	[Int16Array.of, "Int16Array.of"],
	[Int32Array, "Int32Array"],
	[Int32Array.from, "Int32Array.from"],
	[Int32Array.of, "Int32Array.of"],
	[Int8Array, "Int8Array"],
	[Int8Array.from, "Int8Array.from"],
	[Int8Array.of, "Int8Array.of"],
	[Intl.Collator, "Intl.Collator"],
	[Intl.DateTimeFormat, "Intl.DateTimeFormat"],
	[Intl.DisplayNames, "Intl.DisplayNames"],
	[Intl.getCanonicalLocales, "Intl.getCanonicalLocales"],
	[Intl.ListFormat, "Intl.ListFormat"],
	[Intl.Locale, "Intl.Locale"],
	[Intl.NumberFormat, "Intl.NumberFormat"],
	[Intl.PluralRules, "Intl.PluralRules"],
	[Intl.RelativeTimeFormat, "Intl.RelativeTimeFormat"],
	[Intl.Segmenter, "Intl.Segmenter"],
	[Intl.supportedValuesOf, "Intl.supportedValuesOf"],
	[isFinite, "isFinite"],
	[isNaN, "isNaN"],
	[JSON.parse, "JSON.parse"],
	[JSON.stringify, "JSON.stringify"],
	[Map, "Map"],
	[Map.groupBy, "Map.groupBy"],
	[Math.abs, "Math.abs"],
	[Math.acos, "Math.acos"],
	[Math.acosh, "Math.acosh"],
	[Math.asin, "Math.asin"],
	[Math.asinh, "Math.asinh"],
	[Math.atan, "Math.atan"],
	[Math.atan2, "Math.atan2"],
	[Math.atanh, "Math.atanh"],
	[Math.cbrt, "Math.cbrt"],
	[Math.ceil, "Math.ceil"],
	[Math.clz32, "Math.clz32"],
	[Math.cos, "Math.cos"],
	[Math.cosh, "Math.cosh"],
	[Math.exp, "Math.exp"],
	[Math.expm1, "Math.expm1"],
	[Math.floor, "Math.floor"],
	[Math.fround, "Math.fround"],
	[Math.hypot, "Math.hypot"],
	[Math.imul, "Math.imul"],
	[Math.log, "Math.log"],
	[Math.log10, "Math.log10"],
	[Math.log1p, "Math.log1p"],
	[Math.log2, "Math.log2"],
	[Math.max, "Math.max"],
	[Math.min, "Math.min"],
	[Math.pow, "Math.pow"],
	[Math.random, "Math.random"],
	[Math.round, "Math.round"],
	[Math.sign, "Math.sign"],
	[Math.sin, "Math.sin"],
	[Math.sinh, "Math.sinh"],
	[Math.sqrt, "Math.sqrt"],
	[Math.tan, "Math.tan"],
	[Math.tanh, "Math.tanh"],
	[Math.trunc, "Math.trunc"],
	[Number, "Number"],
	[Number.isFinite, "Number.isFinite"],
	[Number.isInteger, "Number.isInteger"],
	[Number.isNaN, "Number.isNaN"],
	[Number.isSafeInteger, "Number.isSafeInteger"],
	[Number.parseFloat, "Number.parseFloat"],
	[Number.parseInt, "Number.parseInt"],
	[Object, "Object"],
	[Object.assign, "Object.assign"],
	[Object.create, "Object.create"],
	[Object.defineProperties, "Object.defineProperties"],
	[Object.defineProperty, "Object.defineProperty"],
	[Object.entries, "Object.entries"],
	[Object.freeze, "Object.freeze"],
	[Object.fromEntries, "Object.fromEntries"],
	[Object.getOwnPropertyDescriptor, "Object.getOwnPropertyDescriptor"],
	[Object.getOwnPropertyDescriptors, "Object.getOwnPropertyDescriptors"],
	[Object.getOwnPropertyNames, "Object.getOwnPropertyNames"],
	[Object.getOwnPropertySymbols, "Object.getOwnPropertySymbols"],
	[Object.getPrototypeOf, "Object.getPrototypeOf"],
	[Object.is, "Object.is"],
	[Object.isExtensible, "Object.isExtensible"],
	[Object.isFrozen, "Object.isFrozen"],
	[Object.isSealed, "Object.isSealed"],
	[Object.keys, "Object.keys"],
	[Object.preventExtensions, "Object.preventExtensions"],
	[Object.seal, "Object.seal"],
	[Object.setPrototypeOf, "Object.setPrototypeOf"],
	[Object.values, "Object.values"],
	[parseFloat, "parseFloat"],
	[parseInt, "parseInt"],
	[Promise, "Promise"],
	[Proxy, "Proxy"],
	[RangeError, "RangeError"],
	[ReferenceError, "ReferenceError"],
	[Reflect.apply, "Reflect.apply"],
	[Reflect.construct, "Reflect.construct"],
	[Reflect.defineProperty, "Reflect.defineProperty"],
	[Reflect.deleteProperty, "Reflect.deleteProperty"],
	[Reflect.get, "Reflect.get"],
	[Reflect.getOwnPropertyDescriptor, "Reflect.getOwnPropertyDescriptor"],
	[Reflect.getPrototypeOf, "Reflect.getPrototypeOf"],
	[Reflect.has, "Reflect.has"],
	[Reflect.isExtensible, "Reflect.isExtensible"],
	[Reflect.ownKeys, "Reflect.ownKeys"],
	[Reflect.preventExtensions, "Reflect.preventExtensions"],
	[Reflect.set, "Reflect.set"],
	[Reflect.setPrototypeOf, "Reflect.setPrototypeOf"],
	[RegExp, "RegExp"],
	[Set, "Set"],
	[String, "String"],
	[String.fromCharCode, "String.fromCharCode"],
	[String.fromCodePoint, "String.fromCodePoint"],
	[String.raw, "String.raw"],
	[Symbol, "Symbol"],
	[Symbol.for, "Symbol.for"],
	[SyntaxError, "SyntaxError"],
	[TypeError, "TypeError"],
	[Uint16Array, "Uint16Array"],
	[Uint16Array.from, "Uint16Array.from"],
	[Uint16Array.of, "Uint16Array.of"],
	[Uint32Array, "Uint32Array"],
	[Uint32Array.from, "Uint32Array.from"],
	[Uint32Array.of, "Uint32Array.of"],
	[Uint8Array, "Uint8Array"],
	[Uint8Array.from, "Uint8Array.from"],
	[Uint8Array.of, "Uint8Array.of"],
	[Uint8ClampedArray, "Uint8ClampedArray"],
	[Uint8ClampedArray.from, "Uint8ClampedArray.from"],
	[Uint8ClampedArray.of, "Uint8ClampedArray.of"],
	[URIError, "URIError"],
	[WeakMap, "WeakMap"],
	[WeakSet, "WeakSet"]
]))();
const KNOWN_OBJECTS = /* @__PURE__ */ (() => /* @__PURE__ */ new Map([
	[Atomics, "Atomics"],
	[console, "console"],
	[globalThis, "globalThis"],
	[globalThis.crypto, "crypto"],
	[Intl, "Intl"],
	[JSON, "JSON"],
	[Math, "Math"],
	[Reflect, "Reflect"]
]))();
var State$1 = class {
	ids = 0;
	flushId = 0;
	wroteUndefined = false;
	buf = [];
	strs = /* @__PURE__ */ new Map();
	refs = /* @__PURE__ */ new WeakMap();
	deferredRefs = /* @__PURE__ */ new Set();
	boundary;
	channel = void 0;
	channelDeps = null;
	queuedCalls = [];
	queuedReadyCalls = [];
	scopeRef(scope, scopeId) {
		return this.refs.get(scope) || newScopeReference(this, scope, scopeId);
	}
	writeScopeProps(props, ref) {
		return writeObjectProps(this, props, ref);
	}
	scopesCursor(scopeId) {
		return scopeId + ",";
	}
	writeTrailing(scopesIndex) {
		const { buf } = this;
		if (~scopesIndex) {
			buf[scopesIndex] = "_([" + buf[scopesIndex];
			buf.push("])");
		}
		writeDeferred(this);
		return ",0)";
	}
	wrapPayload(result, extras) {
		const arrow = this.wroteUndefined ? "(_,$)=>" : "_=>";
		this.wroteUndefined = false;
		return extras ? arrow + result : arrow + "[" + result + "]";
	}
	writeScopedRegistration(val, parent, accessor, registered) {
		const ref = new Reference(parent, accessor, this.flushId, this.buf.length);
		ref.channel = this.channel;
		this.refs.set(val, ref);
		ref.debug = DEBUG.get(val);
		const scope = registered.scope;
		const scopeId = scope[K_SCOPE_ID];
		trackScope(this, scope, scopeId);
		const locals = registered.locals?.(this.boundary.state.scope);
		if (locals) {
			this.buf.push(registered.access + "(_(" + scopeId + ")");
			for (const local of locals) {
				this.buf.push(",");
				writePlainObject(this, local, newArgReference(this, ref, local));
			}
		} else this.buf.push("_(" + scopeId + "," + quoteRegisterId(registered.id));
		this.buf.push(")");
	}
};
var Reference = class {
	assignments = null;
	deferredMembers = null;
	scopeId = void 0;
	channel = void 0;
	parent;
	accessor;
	flushId;
	pos;
	id;
	path = null;
	constructor(parent, accessor, flushId, pos = null, id = null) {
		this.parent = parent;
		this.accessor = accessor;
		this.flushId = flushId;
		this.pos = pos;
		this.id = id;
	}
};
const DEBUG = /* @__PURE__ */ new WeakMap();
function setDebugInfo(obj, file, loc, vars) {
	DEBUG.set(obj, {
		file,
		loc,
		vars,
		slots: DEBUG.get(obj)?.slots
	});
}
function setDebugSlotName(obj, accessor, name) {
	const debug = DEBUG.get(obj);
	if (debug) (debug.slots ??= {})[accessor] = name;
	else DEBUG.set(obj, {
		file: "",
		loc: 0,
		vars: void 0,
		slots: { [accessor]: name }
	});
}
function stringifyScopes(state, flushes, boundary, channel) {
	try {
		state.boundary = boundary;
		state.channel = channel;
		return writeScopesRoot(state, flushes);
	} catch (err) {
		abortRender(boundary, err);
		return "";
	} finally {
		state.flushId++;
		state.buf = [];
	}
}
function pendingReadyChannel(state) {
	const calls = state.queuedReadyCalls;
	return calls.length ? calls[0].channel : void 0;
}
function takeChannelDeps(state) {
	const deps = state.channelDeps;
	state.channelDeps = null;
	return deps;
}
function queueCall(state, value, object, method, channel) {
	(channel?.readyId ? state.queuedReadyCalls : state.queuedCalls).push({
		method,
		value,
		object,
		channel,
		valueId: null
	});
}
function dropQueuedCall(state, value, object, method, channel) {
	const queuedCalls = channel?.readyId ? state.queuedReadyCalls : state.queuedCalls;
	for (let i = 0; i < queuedCalls.length; i++) {
		const call = queuedCalls[i];
		if (call.value === value && call.object === object && call.method === method) {
			queuedCalls.splice(i, 1);
			return true;
		}
	}
	return false;
}
function register(id, val, scope, locals, access = "_._" + toAccess(toObjectKey(id))) {
	REGISTRY.set(val, {
		id,
		scope,
		locals,
		access
	});
	return val;
}
function writeScopesRoot(state, flushes) {
	const { buf } = state;
	let nextSlotId = -1;
	let scopesIndex = -1;
	for (const flush of flushes) {
		const scopeId = flush[0];
		const scope = flush[1];
		const ref = state.scopeRef(scope, scopeId);
		const openIndex = buf.push("") - 1;
		if (state.writeScopeProps(flush[2], ref)) {
			buf[openIndex] = nextSlotId === -1 ? state.scopesCursor(scopeId) + "{" : (scopeId !== nextSlotId ? "," + (scopeId - nextSlotId) : "") + ",{";
			if (scopesIndex === -1) scopesIndex = openIndex;
			nextSlotId = scopeId + 1;
			buf.push("}");
		} else buf.pop();
	}
	let extras = "";
	if (state.deferredRefs.size || hasChannelCalls(state)) extras = state.writeTrailing(scopesIndex);
	let result = extras && "(";
	for (const chunk of buf) result += chunk;
	result += extras;
	if (!result) return "";
	return state.wrapPayload(result, extras);
}
function writeDeferred(state) {
	let sep = state.buf.length ? "," : "";
	if (state.deferredRefs.size) {
		const pending = state.deferredRefs;
		state.deferredRefs = /* @__PURE__ */ new Set();
		let buf = "";
		let hasCalls = false;
		for (const ref of pending) {
			if (ref.assignments) {
				buf += sep + assignmentsToString(ref.assignments, ref.id);
				ref.assignments = null;
				sep = ",";
			}
			hasCalls ||= ref.deferredMembers !== null;
		}
		if (buf) state.buf.push(buf);
		if (hasCalls) for (const ref of pending) {
			const members = ref.deferredMembers;
			if (members) {
				writeDeferredMembers(state, ref.id, members);
				ref.deferredMembers = null;
			}
		}
	}
	const readyId = state.channel?.readyId;
	let calls = state.queuedCalls;
	if (readyId) {
		calls = [];
		const remaining = [];
		for (const call of state.queuedReadyCalls) (call.channel.readyId === readyId ? calls : remaining).push(call);
		state.queuedReadyCalls = remaining;
	} else if (calls.length) state.queuedCalls = [];
	for (const call of calls) {
		const objectStartIndex = state.buf.push(state.buf.length === 0 ? "" : ",");
		if (writeProp(state, call.object, null, "")) {
			const objectRef = state.refs.get(call.object);
			if (!objectRef.id && !isAncestorChannelRef(state, objectRef)) {
				objectRef.id = nextRefAccess(state);
				state.buf[objectStartIndex] = "(" + objectRef.id + "=" + state.buf[objectStartIndex];
				state.buf.push(")");
			} else if (objectRef.id && state.buf[objectStartIndex] !== objectRef.id) {
				state.buf[objectStartIndex] = "(" + state.buf[objectStartIndex];
				state.buf.push(")");
			}
		} else state.buf.push("void 0");
		state.buf.push("." + call.method + "(");
		if (call.value !== void 0) writeCallArg(state, call.value, call.valueId);
		state.buf.push(")");
	}
	if (state.deferredRefs.size) writeDeferred(state);
}
function writeDeferredMembers(state, id, { collection, first, rest }) {
	if (collection instanceof Map) {
		writeDeferredEntry(state, id, first);
		for (const entry of rest) writeDeferredEntry(state, id, entry);
	} else {
		writeDeferredMember(state, id, first);
		for (const member of rest) writeDeferredMember(state, id, member);
	}
}
function writeDeferredEntry(state, id, [key, value]) {
	state.buf.push("," + id + ".set(");
	if (key !== void 0 || value !== void 0) writeCallArg(state, key, null);
	if (value !== void 0) {
		state.buf.push(",");
		writeCallArg(state, value, null);
	}
	state.buf.push(")");
}
function writeDeferredMember(state, id, member) {
	state.buf.push("," + id + ".add(");
	if (member !== void 0) writeCallArg(state, member, null);
	state.buf.push(")");
}
function writeCallArg(state, val, valueId) {
	const startIndex = state.buf.length;
	if (val === void 0) {
		state.wroteUndefined = true;
		state.buf.push("$");
	} else if (writeProp(state, val, null, "")) {
		const ref = typeof val === "string" ? state.strs.get(val) : state.refs.get(val);
		if (ref && !ref.id && ref.scopeId === void 0 && !isAncestorChannelRef(state, ref)) {
			ref.id = valueId || nextRefAccess(state);
			state.buf[startIndex] = ref.id + "=" + state.buf[startIndex];
		}
	} else state.buf.push("void 0");
}
function hasChannelCalls(state) {
	return hasMatchingCalls(state, state.channel?.readyId);
}
function hasMatchingCalls(state, readyId) {
	if (!readyId) return state.queuedCalls.length > 0;
	for (const call of state.queuedReadyCalls) if (call.channel.readyId === readyId) return true;
	return false;
}
function writeProp(state, val, parent, accessor) {
	switch (typeof val) {
		case "string": return writeString(state, val, parent, accessor);
		case "number": return writeNumber(state, val);
		case "boolean": return writeBoolean(state, val);
		case "bigint": return writeBigInt(state, val);
		case "symbol": return writeSymbol(state, val, parent, accessor);
		case "function": return writeFunction(state, val, parent, accessor);
		case "object": return writeObject(state, val, parent, accessor);
		default:
			throwUnserializable(state, val, parent, accessor);
			return false;
	}
}
function writeReferenceOr(state, write, val, parent, accessor) {
	let ref = state.refs.get(val);
	if (ref) {
		if (!trackChannel(state, ref)) {
			abortUnreachableChannel(state, val);
			return false;
		}
		if (parent && isCircular(parent, ref)) {
			ensureRefAccess(state, ref);
			state.deferredRefs.add(ref);
			addAssignment(ref, accessId(state, parent) + toAccess(accessor));
			return false;
		}
		writeRef(state, ref);
		return true;
	}
	const registered = REGISTRY.get(val);
	if (registered) return writeRegistered(state, val, parent, accessor, registered);
	state.refs.set(val, ref = new Reference(parent, accessor, state.flushId, state.buf.length));
	ref.channel = state.channel;
	ref.debug = DEBUG.get(val);
	if (write(state, val, ref)) return true;
	state.refs.delete(val);
	return false;
}
function trackScope(state, val, scopeId) {
	const ref = state.refs.get(val);
	if (ref) trackChannel(state, ref);
	else newScopeReference(state, val, scopeId);
}
function newScopeReference(state, val, scopeId) {
	const ref = new Reference(null, null, state.flushId);
	ref.scopeId = scopeId;
	ref.channel = state.channel;
	state.refs.set(val, ref);
	ref.debug = DEBUG.get(val);
	return ref;
}
function quoteRegisterId(id) {
	return quote(id, 0);
}
function writeRegistered(state, val, parent, accessor, registered) {
	const { scope } = registered;
	if (scope) state.writeScopedRegistration(val, parent, accessor, registered);
	else state.buf.push(registered.access);
	return true;
}
const STRING_DEDUP_LENGTH = 12;
function writeString(state, val, parent, accessor) {
	if (val.length > STRING_DEDUP_LENGTH) {
		const ref = state.strs.get(val);
		if (ref) {
			if (trackChannel(state, ref)) {
				writeRef(state, ref);
				return true;
			}
		} else {
			const ref = new Reference(parent, accessor, state.flushId, state.buf.length);
			ref.channel = state.channel;
			state.strs.set(val, ref);
		}
	}
	state.buf.push(quote(val, 0));
	return true;
}
function writeNumber(state, val) {
	state.buf.push(val + "");
	return true;
}
function writeBoolean(state, val) {
	state.buf.push(val ? "!0" : "!1");
	return true;
}
function writeBigInt(state, val) {
	state.buf.push(val + "n");
	return true;
}
function writeFunction(state, val, parent, accessor) {
	const wellKnownFunction = KNOWN_FUNCTIONS.get(val);
	if (wellKnownFunction) {
		state.buf.push(wellKnownFunction);
		return true;
	}
	return writeReferenceOr(state, writeNever, val, parent, accessor);
}
function writeSymbol(state, val, parent, accessor) {
	const wellKnownSymbol = KNOWN_SYMBOLS.get(val);
	if (wellKnownSymbol) {
		state.buf.push(wellKnownSymbol);
		return true;
	}
	const key = Symbol.keyFor(val);
	if (key !== void 0) {
		state.buf.push("Symbol.for(" + quote(key, 0) + ")");
		return true;
	}
	return writeReferenceOr(state, writeUnknownSymbol, val, parent, accessor);
}
function writeUnknownSymbol(state) {
	state.buf.push("Symbol()");
	return true;
}
function writeNever(state, val, ref) {
	throwUnserializable(state, val, ref);
	return false;
}
function writeNull(state) {
	state.buf.push("null");
	return true;
}
function writeObject(state, val, parent, accessor) {
	if (val === null) return writeNull(state);
	const scopeId = val[K_SCOPE_ID];
	if (scopeId !== void 0) {
		trackScope(state, val, scopeId);
		state.buf.push("_(" + scopeId + ")");
		return true;
	}
	const wellKnownObject = KNOWN_OBJECTS.get(val);
	if (wellKnownObject) {
		state.buf.push(wellKnownObject);
		return true;
	}
	return writeReferenceOr(state, writeUnknownObject, val, parent, accessor);
}
function writeUnknownObject(state, val, ref) {
	const proto = Object.getPrototypeOf(val);
	if (proto === objectProto) return writePlainObject(state, val, ref);
	if (proto === arrayProto) return writeArray(state, val, ref);
	const constructor = proto?.constructor;
	switch (constructor) {
		case void 0: return writeNullObject(state, val, ref);
		case Object: return writePlainObject(state, val, ref);
		case Array: return writeArray(state, val, ref);
		case Date: return writeDate(state, val);
		case RegExp: return writeRegExp(state, val);
		case Promise: return writePromise(state, val, ref);
		case Map: return writeMap(state, val, ref);
		case Set: return writeSet(state, val, ref);
		case Generator: return writeGenerator(state, val, ref);
		case AsyncGenerator: return writeAsyncGenerator(state, val, ref);
		case Error:
		case EvalError:
		case RangeError:
		case ReferenceError:
		case SyntaxError:
		case TypeError:
		case URIError: return writeError(state, val, constructor.name, ref);
		case AggregateError: return writeAggregateError(state, val, ref);
		case ArrayBuffer: return writeArrayBuffer(state, val);
		case Int8Array:
		case Uint8Array:
		case Uint8ClampedArray:
		case Int16Array:
		case Uint16Array:
		case Int32Array:
		case Uint32Array:
		case Float32Array:
		case Float64Array:
		case BigInt64Array:
		case BigUint64Array: return writeTypedArray(state, val, constructor.name, ref);
		case DataView: return writeDataView(state, val, ref);
		case WeakSet: return writeWeakSet(state);
		case WeakMap: return writeWeakMap(state);
		case globalThis.URL: return writeURL(state, val);
		case globalThis.URLSearchParams: return writeURLSearchParams(state, val);
		case globalThis.Headers: return writeHeaders(state, val);
		case globalThis.FormData: return writeFormData(state, val, ref);
		case globalThis.ReadableStream: return writeReadableStream(state, val, ref);
		case globalThis.Request: return writeRequest(state, val, ref);
		case globalThis.Response: return writeResponse(state, val, ref);
		case globalThis.Intl?.NumberFormat: return writeIntl(state, val, "NumberFormat", ref);
		case globalThis.Intl?.DateTimeFormat: return writeIntl(state, val, "DateTimeFormat", ref);
		case globalThis.Intl?.Collator: return writeIntl(state, val, "Collator", ref);
		case globalThis.Intl?.PluralRules: return writeIntl(state, val, "PluralRules", ref);
		case globalThis.Intl?.RelativeTimeFormat: return writeIntl(state, val, "RelativeTimeFormat", ref);
		case globalThis.Intl?.ListFormat: return writeIntl(state, val, "ListFormat", ref);
		case globalThis.Intl?.DisplayNames: return writeIntl(state, val, "DisplayNames", ref);
		case globalThis.Intl?.Segmenter: return writeIntl(state, val, "Segmenter", ref);
		case globalThis.Intl?.DurationFormat: return writeIntl(state, val, "DurationFormat", ref);
		case globalThis.Intl?.Locale: return writeIntlLocale(state, val);
		case globalThis.Temporal?.Instant: return writeTemporal(state, val, "Instant");
		case globalThis.Temporal?.Duration: return writeTemporal(state, val, "Duration");
		case globalThis.Temporal?.PlainDate: return writeTemporal(state, val, "PlainDate");
		case globalThis.Temporal?.PlainDateTime: return writeTemporal(state, val, "PlainDateTime");
		case globalThis.Temporal?.PlainMonthDay: return writeTemporal(state, val, "PlainMonthDay");
		case globalThis.Temporal?.PlainTime: return writeTemporal(state, val, "PlainTime");
		case globalThis.Temporal?.PlainYearMonth: return writeTemporal(state, val, "PlainYearMonth");
		case globalThis.Temporal?.ZonedDateTime: return writeTemporal(state, val, "ZonedDateTime");
	}
	throwUnserializable(state, val, ref);
	return false;
}
function writePlainObject(state, val, ref) {
	state.buf.push("{");
	writeMaybeIterableProps(state, val, ref);
	state.buf.push("}");
	return true;
}
function writeArray(state, val, ref) {
	let sep = "[";
	for (let i = 0; i < val.length; i++) {
		const item = val[i];
		state.buf.push(sep);
		sep = ",";
		if (item === void 0) {
			state.wroteUndefined = true;
			state.buf.push("$");
		} else writeProp(state, item, ref, "" + i);
	}
	if (sep === "[") state.buf.push("[]");
	else state.buf.push("]");
	return true;
}
function writeDate(state, val) {
	state.buf.push("new Date(" + +val + ")");
	return true;
}
const unsafeRegExpSourceReg = /\\[\s\S]|[<\0\ud800-\udfff]/gu;
const unsafeRegExpSourceDetect = /[<\0\ud800-\udfff]/u;
const replaceUnsafeRegExpSourceChar = (match) => {
	const ch = match.length === 3 ? "" : match[match.length - 1];
	if (ch === "<") return "\\x3C";
	if (ch === "\0") return "\\x00";
	const code = ch.charCodeAt(0);
	return code >= 55296 && code <= 57343 ? "\\u" + code.toString(16).padStart(4, "0") : match;
};
function writeRegExp(state, val) {
	const { source } = val;
	if (source.includes("<")) state.buf.push(`RegExp(${quote(source, 0)}${val.flags ? ",\"" + val.flags + "\"" : ""})`);
	else state.buf.push("/" + (unsafeRegExpSourceDetect.test(source) ? source.replace(unsafeRegExpSourceReg, replaceUnsafeRegExpSourceChar) : source) + "/" + val.flags);
	return true;
}
function writePromise(state, val, ref) {
	const { boundary, channel } = state;
	const pId = nextRefAccess(state);
	const handle = newAsyncHandle(state, ref, pId);
	state.buf.push("(p=>p=new Promise((f,r)=>" + pId + "={f,r(e){p.catch(_=>0);r(e)}}))()");
	val.then((v) => queueAsyncCall(state, boundary, handle, "f", v, channel, pId), (v) => queueAsyncCall(state, boundary, handle, "r", v, channel, pId));
	boundary.startAsync();
	return true;
}
function newAsyncHandle(state, parent, id) {
	const handle = {};
	const handleRef = new Reference(parent, null, state.flushId, null, id);
	handleRef.channel = state.channel;
	state.refs.set(handle, handleRef);
	return handle;
}
function writeMap(state, val, ref) {
	if (!val.size) {
		state.buf.push("new Map");
		return true;
	}
	const items = [];
	let assignments;
	let needsId;
	let i = 0;
	const entries = val.entries();
	if (val.size < 25) {
		for (const entry of entries) {
			let [itemKey, itemValue] = entry;
			if (itemKey !== val && isAncestorMember(state, ref, itemKey) || itemValue !== val && isAncestorMember(state, ref, itemValue)) {
				deferMembers(state, ref, val, entry, entries);
				if (!i) {
					state.buf.push("new Map");
					return true;
				}
				break;
			}
			if (itemKey === val) {
				itemKey = void 0;
				(assignments ||= []).push("a[" + i + "][0]");
			}
			if (itemValue === val) {
				itemValue = void 0;
				(assignments ||= []).push("a[" + i + "][1]");
			}
			needsId ||= isReusableMember(itemKey) || isReusableMember(itemValue);
			i = items.push(itemValue === void 0 ? itemKey === void 0 ? [] : [itemKey] : [itemKey, itemValue]);
		}
		writeArrayArg(state, ref, items, assignments && "((m,a)=>(" + assignmentsToString(assignments, "m") + ",a.forEach(i=>m.set(i[0],i[1])),m))(new Map,", "new Map(", needsId);
	} else {
		for (const entry of entries) {
			let [itemKey, itemValue] = entry;
			if (itemKey !== val && isAncestorMember(state, ref, itemKey) || itemValue !== val && isAncestorMember(state, ref, itemValue)) {
				deferMembers(state, ref, val, entry, entries);
				if (!i) {
					state.buf.push("new Map");
					return true;
				}
				break;
			}
			if (itemKey === val) {
				itemKey = 0;
				(assignments ||= []).push("a[" + i + "]");
			}
			if (itemValue === val) {
				itemValue = 0;
				(assignments ||= []).push("a[" + (i + 1) + "]");
			}
			needsId ||= isReusableMember(itemKey) || isReusableMember(itemValue);
			i = items.push(itemKey, itemValue);
		}
		writeArrayArg(state, ref, items, assignments && "(a=>a.reduce((m,v,i)=>i%2?m:m.set(v,a[i+1])," + assignmentsToString(assignments, "new Map") + "))(", "(a=>a.reduce((m,v,i)=>i%2?m:m.set(v,a[i+1]),new Map))(", needsId);
	}
	return true;
}
function writeSet(state, val, ref) {
	if (!val.size) {
		state.buf.push("new Set");
		return true;
	}
	const items = [];
	let assignments;
	let needsId;
	let i = 0;
	const members = val.values();
	for (let item of members) {
		if (item !== val && isAncestorMember(state, ref, item)) {
			deferMembers(state, ref, val, item, members);
			if (!i) {
				state.buf.push("new Set");
				return true;
			}
			break;
		}
		if (item === val) {
			item = 0;
			(assignments ||= []).push("i[" + i + "]");
		} else needsId ||= isReusableMember(item);
		i = items.push(item);
	}
	writeArrayArg(state, ref, items, assignments && "((s,i)=>(" + assignmentsToString(assignments, "s") + ",i.forEach(i=>s.add(i)),s))(new Set,", "new Set(", needsId);
	return true;
}
function isAncestorMember(state, container, member) {
	if (member === null || typeof member !== "object" && typeof member !== "function") return false;
	const ref = state.refs.get(member);
	return ref !== void 0 && isCircular(container, ref);
}
function deferMembers(state, ref, collection, first, rest) {
	ensureRefAccess(state, ref);
	ref.deferredMembers = {
		collection,
		first,
		rest
	};
	state.deferredRefs.add(ref);
}
function writeArrayArg(state, ref, items, assignsPrefix, plainPrefix, needsId) {
	if (assignsPrefix || needsId) {
		const arrayRef = new Reference(ref, null, state.flushId, null, nextRefAccess(state));
		state.buf.push((assignsPrefix || plainPrefix) + arrayRef.id + "=");
		writeArray(state, items, arrayRef);
	} else {
		state.buf.push(plainPrefix);
		writeArray(state, items, new Reference(ref, null, state.flushId, state.buf.length));
	}
	state.buf.push(")");
}
function newArgReference(state, parent, val) {
	for (const key in val) {
		const member = val[key];
		if (isReusableMember(member) && !(typeof member === "string" ? state.strs.has(member) : state.refs.has(member))) {
			const ref = new Reference(parent, null, state.flushId, null, nextRefAccess(state));
			state.buf.push(ref.id + "=");
			return ref;
		}
	}
	return new Reference(parent, null, state.flushId, state.buf.length);
}
function isReusableMember(val) {
	switch (typeof val) {
		case "object": return val !== null && val[K_SCOPE_ID] === void 0;
		case "function":
		case "symbol": return true;
		case "string": return val.length > STRING_DEDUP_LENGTH;
		default: return false;
	}
}
function canWriteBuffer(state, buffer, ref) {
	if (Object.getPrototypeOf(buffer)?.constructor === ArrayBuffer) return true;
	throwUnserializable(state, buffer, ref, "buffer");
	return false;
}
function writeDataView(state, val, ref) {
	const { buffer } = val;
	if (!canWriteBuffer(state, buffer, ref)) return false;
	const needsLength = val.byteOffset + val.byteLength < buffer.byteLength;
	state.buf.push("new DataView(");
	writeProp(state, buffer, ref, "buffer");
	state.buf.push((val.byteOffset || needsLength ? "," + val.byteOffset + (needsLength ? "," + val.byteLength : "") : "") + ")");
	return true;
}
function writeArrayBuffer(state, val) {
	let result;
	if (val.byteLength) {
		const view = new Int8Array(val);
		result = hasOnlyZeros(view) ? "new ArrayBuffer(" + val.byteLength + ")" : "new Int8Array(" + typedArrayToInitString(view) + ").buffer";
	} else result = "new ArrayBuffer";
	state.buf.push(result);
	return true;
}
function writeTypedArray(state, val, name, ref) {
	if (val.byteOffset || val.byteLength < val.buffer.byteLength || state.refs.has(val.buffer)) {
		if (!canWriteBuffer(state, val.buffer, ref)) return false;
		const needsLength = val.byteOffset + val.byteLength < val.buffer.byteLength;
		state.buf.push("new " + name + "(");
		writeProp(state, val.buffer, ref, "buffer");
		state.buf.push((val.byteOffset || needsLength ? "," + val.byteOffset + (needsLength ? "," + val.length : "") : "") + ")");
	} else {
		state.refs.set(val.buffer, new Reference(ref, "buffer", state.flushId, null));
		state.buf.push("new " + name + (val.length === 0 ? "" : "(" + (hasOnlyZeros(val) ? val.length : typedArrayToInitString(val)) + ")"));
	}
	return true;
}
function writeWeakSet(state) {
	state.buf.push("new WeakSet");
	return true;
}
function writeWeakMap(state) {
	state.buf.push("new WeakMap");
	return true;
}
function writeError(state, val, name, ref) {
	const result = "new " + name + "(" + quote(val.message + "", 0);
	if (val.cause !== void 0) {
		const pos = state.buf.push(result + ",{cause:") - 1;
		if (writeProp(state, val.cause, ref, "cause")) state.buf.push("})");
		else state.buf[pos] = state.buf[pos].slice(0, -8) + ")";
	} else state.buf.push(result + ")");
	return true;
}
function writeAggregateError(state, val, ref) {
	state.buf.push("new AggregateError(");
	const inlined = writeProp(state, val.errors, ref, "errors");
	if (!inlined) state.buf.push("[]");
	if (val.message) state.buf.push("," + quote(val.message + "", 0) + ")");
	else state.buf.push(")");
	if (inlined) {
		const errorsRef = state.refs.get(val.errors);
		if (errorsRef?.id) {
			state.deferredRefs.add(errorsRef);
			addAssignment(errorsRef, accessId(state, ref) + toAccess("errors"));
		}
	}
	return true;
}
function writeURL(state, val) {
	state.buf.push("new URL(" + quote(val.toString(), 0) + ")");
	return true;
}
function writeURLSearchParams(state, val) {
	const str = val.toString();
	if (str) state.buf.push("new URLSearchParams(" + quote(str, 0) + ")");
	else state.buf.push("new URLSearchParams");
	return true;
}
function writeHeaders(state, val) {
	const headers = stringEntriesToHeadersInit(val);
	state.buf.push("new Headers" + (headers ? "(" + headers + ")" : ""));
	return true;
}
function writeFormData(state, val, ref) {
	let sep = "[";
	let valStr = "";
	for (const [key, value] of val) {
		if (typeof value !== "string") {
			throwUnserializable(state, value, ref, key);
			return false;
		}
		valStr += sep + quote(key, 0) + "," + quote(value, 0);
		sep = ",";
	}
	if (sep === "[") state.buf.push("new FormData");
	else state.buf.push(valStr + "].reduce((f,v,i,a)=>i%2&&f.append(a[i-1],v)||f,new FormData)");
	return true;
}
function writeRequest(state, val, ref) {
	let sep = "";
	let bodySerialized = false;
	const hasBody = val.body && !val.bodyUsed && val.duplex === "half";
	state.buf.push("new Request(" + quote(val.url, 0));
	if (hasBody) {
		state.buf.push(",{body:");
		if (writeProp(state, val.body, ref, "body")) {
			state.buf.push(",duplex:\"half\"");
			sep = ",";
			bodySerialized = true;
		} else state.buf.pop();
	}
	let options = "";
	if (val.cache !== "default") {
		options += sep + "cache:" + quote(val.cache, 0);
		sep = ",";
	}
	if (val.credentials !== "same-origin") {
		options += sep + "credentials:" + quote(val.credentials, 0);
		sep = ",";
	}
	const seenHeaders = state.refs.get(val.headers);
	if (seenHeaders) {
		options += sep + "headers:" + ensureRefAccess(state, seenHeaders);
		sep = ",";
	} else {
		state.refs.set(val.headers, new Reference(ref, "headers", state.flushId, null));
		const headers = stringEntriesToHeadersInit(val.headers);
		if (headers) {
			options += sep + "headers:" + headers;
			sep = ",";
		}
	}
	if (val.integrity) {
		options += sep + "integrity:" + quote(val.integrity, 0);
		sep = ",";
	}
	if (val.keepalive) {
		options += sep + "keepalive:true";
		sep = ",";
	}
	if (val.method !== "GET") {
		options += sep + "method:" + quote(val.method, 0);
		sep = ",";
	}
	if (val.mode !== "cors") {
		options += sep + "mode:" + quote(val.mode, 0);
		sep = ",";
	}
	if (val.redirect !== "follow") {
		options += sep + "redirect:" + quote(val.redirect, 0);
		sep = ",";
	}
	if (val.referrer !== "about:client") {
		options += sep + "referrer:" + quote(val.referrer, 0);
		sep = ",";
	}
	if (val.referrerPolicy) options += sep + "referrerPolicy:" + quote(val.referrerPolicy, 0);
	state.buf.push(bodySerialized ? options + "})" : options ? ",{" + options + "})" : ")");
	return true;
}
function writeResponse(state, val, ref) {
	let sep = "";
	let options = "";
	if (val.status !== 200) {
		options += "status:" + val.status;
		sep = ",";
	}
	if (val.statusText) {
		options += sep + "statusText:" + quote(val.statusText, 0);
		sep = ",";
	}
	const seenHeaders = state.refs.get(val.headers);
	if (seenHeaders) options += sep + "headers:" + ensureRefAccess(state, seenHeaders);
	else {
		state.refs.set(val.headers, new Reference(ref, "headers", state.flushId, null));
		const headers = stringEntriesToHeadersInit(val.headers);
		if (headers) options += sep + "headers:" + headers;
	}
	if (!val.body || val.bodyUsed) state.buf.push("new Response" + (options ? "(null,{" + options + "})" : ""));
	else {
		state.buf.push("new Response(");
		state.buf.push((writeProp(state, val.body, ref, "body") ? "" : "null") + (options ? ",{" + options + "})" : ")"));
	}
	return true;
}
function writeIntl(state, val, name, ref) {
	const { locale, ...options } = val.resolvedOptions();
	state.buf.push("new Intl." + name + "(" + quote(locale, 0) + ",");
	const optionsRef = newArgReference(state, ref, options);
	state.buf.push("{");
	writeObjectProps(state, options, optionsRef);
	state.buf.push("})");
	return true;
}
function writeIntlLocale(state, val) {
	state.buf.push("new Intl.Locale(" + quote(val.toString(), 0) + ")");
	return true;
}
function writeTemporal(state, val, name) {
	state.buf.push("Temporal." + name + ".from(" + quote(val.toString(), 0) + ")");
	return true;
}
function writeReadableStream(state, val, ref) {
	if (val.locked) {
		throwUnserializable(state, val, ref, "", "The ReadableStream is locked by a reader on the server; to also send it to the browser, `tee()` it (or `clone()` its `Request`/`Response`) before reading.");
		return false;
	}
	const { boundary, channel } = state;
	const reader = val.getReader();
	const iterId = nextRefAccess(state);
	const handle = newAsyncHandle(state, ref, iterId);
	const onFulfilled = ({ value, done }) => {
		if (done) queueAsyncCall(state, boundary, handle, "r", value, channel);
		else if (!boundary.aborted) {
			reader.read().then(onFulfilled, onRejected);
			boundary.startAsync();
			queueAsyncCall(state, boundary, handle, "f", value, channel);
		}
	};
	const onRejected = (reason) => {
		queueAsyncCall(state, boundary, handle, "j", reason, channel);
	};
	state.buf.push("new ReadableStream({start(c){(async(_,f,v,l,i,p=a=>l=new Promise((r,j)=>{f=_.r=r;_.j=j}),a=((_.f=v=>{f(v);a.push(p())}),[p()]))=>{for(i of a)v=await i,i==l?c.close():c.enqueue(v)})(" + iterId + "={}).catch(e=>c.error(e))}})");
	reader.read().then(onFulfilled, onRejected);
	boundary.startAsync();
	return true;
}
function writeGenerator(state, iter, ref) {
	if (iter[kTouchedIterator]) {
		state.buf.push("(function*(){}())");
		return true;
	}
	const yields = [];
	let returnValue;
	let needsId;
	while (true) {
		const { value, done } = iter.next();
		if (done) {
			returnValue = value;
			break;
		}
		needsId ||= isReusableMember(value);
		yields.push(value);
	}
	if (returnValue === void 0 && !yields.length) {
		state.buf.push("(function*(){})()");
		return true;
	}
	const heldReturn = returnValue !== void 0 && isAncestorMember(state, ref, returnValue);
	state.buf.push(returnValue === void 0 ? "(function*(a){yield*a})(" : heldReturn ? "(function*(a,r){yield*a;return r.v})(" : "(function*(a,r){yield*a;return r})(");
	if (needsId) {
		const arrayRef = new Reference(ref, null, state.flushId, null, nextRefAccess(state));
		state.buf.push(arrayRef.id + "=");
		writeArray(state, yields, arrayRef);
	} else writeArray(state, yields, new Reference(ref, null, state.flushId, state.buf.length));
	if (heldReturn) {
		const holder = new Reference(ref, null, state.flushId, null, nextRefAccess(state));
		state.buf.push("," + holder.id + "={}");
		writeProp(state, returnValue, holder, "v");
	} else if (returnValue !== void 0) {
		state.buf.push(",");
		if (writeProp(state, returnValue, ref, "") && isReusableMember(returnValue)) {
			const retRef = typeof returnValue === "string" ? state.strs.get(returnValue) : state.refs.get(returnValue);
			if (retRef) ensureRefAccess(state, retRef);
		}
	}
	state.buf.push(")");
	return true;
}
function writeAsyncGenerator(state, iter, ref) {
	if (iter[kTouchedIterator]) {
		state.buf.push("(async function*(){}())");
		return true;
	}
	const { boundary, channel } = state;
	const iterId = nextRefAccess(state);
	const handle = newAsyncHandle(state, ref, iterId);
	const onFulfilled = ({ value, done }) => {
		if (done) queueAsyncCall(state, boundary, handle, "r", value, channel);
		else if (!boundary.aborted) {
			iter.next().then(onFulfilled, onRejected);
			boundary.startAsync();
			queueAsyncCall(state, boundary, handle, "f", value, channel);
		}
	};
	const onRejected = (reason) => {
		queueAsyncCall(state, boundary, handle, "j", reason, channel);
	};
	state.buf.push("(async function*(_,f,v,l,i,p=a=>l=new Promise((r,j)=>{f=_.r=r;_.j=j}),a=((_.f=v=>{f(v);a.push(p())}),[p()])){for(i of a)v=await i,i!=l&&(yield v);return v})(" + iterId + "={})");
	iter.next().then(onFulfilled, onRejected);
	boundary.startAsync();
	return true;
}
function writeNullObject(state, val, ref) {
	state.buf.push("{");
	state.buf.push(writeMaybeIterableProps(state, val, ref) + "__proto__:null}");
	return true;
}
function writeObjectProps(state, val, ref) {
	let sep = "";
	for (const key in val) if (hasOwnProperty.call(val, key)) {
		const escapedKey = toObjectKey(key);
		state.buf.push(sep + escapedKey + ":");
		if (writeProp(state, val[key], ref, escapedKey)) sep = ",";
		else state.buf.pop();
	}
	return sep;
}
function writeMaybeIterableProps(state, val, ref) {
	let sep = writeObjectProps(state, val, ref);
	if (hasSymbolIterator(val)) {
		let yieldSelf = "";
		const iterArr = [];
		for (const item of val) if (item === val && !(yieldSelf || iterArr.length)) yieldSelf = "yield this;";
		else iterArr.push(item);
		if (iterArr.length) {
			const iterRef = new Reference(ref, null, state.flushId, null, nextRefAccess(state));
			state.buf.push(sep + "*[(" + iterRef.id + "=");
			writeArray(state, iterArr, iterRef);
			state.buf.push(",Symbol.iterator)](){" + yieldSelf + "yield*" + iterRef.id + "}");
		} else state.buf.push(sep + "*[Symbol.iterator](){" + yieldSelf.slice(0, -1) + "}");
		sep = ",";
	}
	return sep;
}
function queueAsyncCall(state, boundary, handle, method, value, channel, valueId = null) {
	if (boundary.aborted) return;
	(channel?.readyId ? state.queuedReadyCalls : state.queuedCalls).push({
		method,
		value,
		object: handle,
		channel,
		valueId
	});
	boundary.endAsync();
}
function throwUnserializable(state, cause, ref = null, accessor = "", hint = "Values referenced in the browser must be serializable.") {
	if (cause !== void 0) {
		let message = "Unable to serialize";
		let access = "";
		while (ref) {
			const { accessor } = ref;
			const debug = ref.parent?.debug;
			if (accessor && debug) {
				const rawAccessor = fromObjectKey(accessor);
				const varLoc = debug.vars?.[rawAccessor];
				const slotName = debug.slots?.[rawAccessor];
				let debugAccess = varLoc ? rawAccessor : void 0;
				let debugLoc = debug.loc;
				if (varLoc) {
					if (Array.isArray(varLoc)) {
						debugAccess = varLoc[0];
						if (varLoc[1]) debugLoc = varLoc[1];
					} else debugLoc = varLoc;
				}
				let display;
				if (debugAccess !== void 0) display = slotName && debugAccess.startsWith("...") ? `\`${slotName}\` from \`${debugAccess}\`` : JSON.stringify(debugAccess);
				else display = describeAccessor(rawAccessor, slotName) ?? JSON.stringify(rawAccessor);
				message += ` ${display} in ${debug.file}`;
				if (debugLoc) message += `:${debugLoc}`;
				break;
			}
			if (accessor) access = toAccess(accessor) + access;
			ref = ref.parent;
		}
		if (accessor) access = toAccess(accessor) + access;
		if (access[0] === ".") access = access.slice(1);
		if (access) message += ` (reading ${access})`;
		message += ". " + hint;
		const err = new TypeError(message, { cause });
		err.stack = void 0;
		abortRender(state.boundary, err);
	}
}
const accessorPrefixDescriptions = {
	BranchScopes: "the branch scopes",
	ClosureScopes: "the closure scopes",
	ClosureSignalIndex: "the closure signal index",
	ConditionalRenderer: "the conditional renderer",
	ControlledObserver: "the controlled observer",
	ControlledHandler: "the change handler",
	ControlledType: "the controlled type",
	ControlledValue: "the controlled value",
	DynamicHTMLLastChild: "the dynamic html",
	DynamicHTMLValue: "the dynamic html value",
	EventAttributes: "the event handlers",
	IdFallback: "the generated id",
	KeyedScopes: "the keyed scopes",
	Lifecycle: "the lifecycle handlers",
	Promise: "the pending promise",
	TagVariableChange: "the tag variable change handler",
	TryBranch: "the try branch"
};
function describeAccessor(accessor, slotName) {
	const sep = accessor.indexOf(":");
	if (~sep) {
		const description = slotName === void 0 ? accessorPrefixDescriptions[accessor.slice(0, sep)] : `the \`${slotName}\` handler`;
		if (description) {
			const node = /^#([a-z-]+)\//i.exec(accessor.slice(sep + 1));
			return node ? `${description} of \`<${node[1]}>\`` : description;
		}
	}
}
function fromObjectKey(key) {
	try {
		if (key[0] === "\"") return JSON.parse(key.replace(/\\x/g, "\\u00"));
		if (key[0] === "[") return JSON.parse(key.slice(1, -1));
	} catch {}
	return key;
}
function trackChannel(state, ref) {
	const refReadyId = ref.channel?.readyId;
	if (!refReadyId || refReadyId === state.channel?.readyId) return true;
	let cur = state.channel?.parent;
	while (cur) {
		if (cur.readyId === refReadyId) {
			(state.channelDeps ||= /* @__PURE__ */ new Set()).add(refReadyId);
			return true;
		}
		cur = cur.parent;
	}
	return false;
}
function isAncestorChannelRef(state, ref) {
	return ref.channel?.readyId !== state.channel?.readyId;
}
function abortUnreachableChannel(state, val) {
	const err = new TypeError("Unable to serialize a value shared between independently lazy loaded content. Values shared this way must also be serialized by content that is not lazily loaded, or by a common parent.", { cause: val });
	err.stack = void 0;
	abortRender(state.boundary, err);
}
function abortRender(boundary, err) {
	while (boundary.parent) boundary = boundary.parent;
	boundary.abort(err);
}
function isCircular(parent, ref) {
	let cur = parent;
	while (cur) {
		if (cur === ref) return true;
		cur = cur.parent;
	}
	return false;
}
function toObjectKey(name) {
	if (name === "") return "\"\"";
	if (name === "__proto__") return "[\"__proto__\"]";
	const len = name.length;
	const c0 = name.charCodeAt(0);
	if (c0 >= 48 && c0 <= 57) {
		if (c0 === 48) {
			if (len !== 1) return quote(name, 1);
		} else {
			for (let i = 1; i < len; i++) {
				const c = name.charCodeAt(i);
				if (c < 48 || c > 57) return quote(name, i);
			}
			if (len > 15 && "" + +name !== name) return quote(name, 0);
		}
	} else if (c0 >= 97 && c0 <= 122 || c0 >= 65 && c0 <= 90 || c0 === 95 || c0 === 36) for (let i = 1; i < len; i++) {
		const c = name.charCodeAt(i);
		if (!(c >= 97 && c <= 122 || c >= 65 && c <= 90 || c >= 48 && c <= 57 || c === 95 || c === 36)) return quote(name, i);
	}
	else return quote(name, 0);
	return name;
}
function toAccess(accessor) {
	const start = accessor[0];
	return start === "[" ? accessor : start === "\"" || start >= "0" && start <= "9" ? "[" + accessor + "]" : "." + accessor;
}
const unsafeQuoteReg = /["\\<\n\r\u2028\u2029\0\ud800-\udfff]/u;
function quote(str, startPos) {
	if (!unsafeQuoteReg.test(str)) return "\"" + str + "\"";
	let result = "";
	let lastPos = 0;
	for (let i = startPos; i < str.length; i++) {
		let replacement;
		const code = str.charCodeAt(i);
		switch (code) {
			case 34:
				replacement = "\\\"";
				break;
			case 92:
				replacement = "\\\\";
				break;
			case 60:
				replacement = "\\x3C";
				break;
			case 10:
				replacement = "\\n";
				break;
			case 13:
				replacement = "\\r";
				break;
			case 8232:
				replacement = "\\u2028";
				break;
			case 8233:
				replacement = "\\u2029";
				break;
			case 0:
				replacement = "\\x00";
				break;
			default:
				if (code < 55296 || code > 57343) continue;
				if (code < 56320) {
					const next = str.charCodeAt(i + 1);
					if (next >= 56320 && next <= 57343) {
						i++;
						continue;
					}
				}
				replacement = "\\u" + code.toString(16);
		}
		result += str.slice(lastPos, i) + replacement;
		lastPos = i + 1;
	}
	return "\"" + (lastPos === startPos ? str : result + str.slice(lastPos)) + "\"";
}
function writeRef(state, ref) {
	if (ref.id === null && ref.scopeId === void 0 && ref.path === null && (ref.pos === null || ref.flushId !== state.flushId) && !isAncestorChannelRef(state, ref)) {
		ref.path = accessPath(state, ref);
		ref.pos = state.buf.length;
		ref.flushId = state.flushId;
		state.buf.push(ref.path);
	} else state.buf.push(ensureRefAccess(state, ref));
}
function ensureRefAccess(state, ref) {
	if (ref.scopeId !== void 0) {
		trackChannel(state, ref);
		return "_(" + ref.scopeId + ")";
	}
	if (ref.id) {
		trackChannel(state, ref);
		return ref.id;
	}
	return claimRefAccess(state, ref);
}
function accessId(state, ref) {
	const id = ensureRefAccess(state, ref);
	return id === ref.id || ref.scopeId !== void 0 ? id : "(" + id + ")";
}
function claimRefAccess(state, ref) {
	const { pos } = ref;
	if (pos !== null && ref.flushId === state.flushId) {
		ref.id = nextRefAccess(state);
		if (pos === 0) state.buf[0] = ref.id + "=" + state.buf[0];
		else state.buf[pos - 1] += ref.id + "=";
		return ref.id;
	}
	if (isAncestorChannelRef(state, ref)) return ref.path || accessPath(state, ref);
	ref.id = nextRefAccess(state);
	return ref.id + "=" + (ref.path || accessPath(state, ref));
}
function accessPath(state, ref) {
	let cur = ref;
	let accessPrevValue = "";
	do {
		if (cur.accessor === null) throw new Error("Unable to serialize a reused value: no access path reaches where it was first written, and it has no id.");
		accessPrevValue = toAccess(cur.accessor) + accessPrevValue;
		const parent = cur.parent;
		if (parent.id) {
			trackChannel(state, parent);
			return parent.id + accessPrevValue;
		}
		if (parent.flushId === state.flushId || parent.scopeId !== void 0) return accessId(state, parent) + accessPrevValue;
		cur = parent;
	} while (cur);
	return accessPrevValue;
}
function assignmentsToString(assignments, value) {
	if (assignments.length > 100) return "($=>(" + assignments.join("=$,") + "=$))(" + value + ")";
	return assignments.join("=") + "=" + value;
}
function addAssignment(ref, assign) {
	if (ref.assignments) ref.assignments.push(assign);
	else ref.assignments = [assign];
}
function nextRefAccess(state) {
	return "_." + nextId(state);
}
function nextId(state) {
	const c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
	let n = state.ids++;
	let r = c[n % 53];
	for (n = n / 53 | 0; n; n >>>= 6) r += c[n & 63];
	return r === "name" ? nextId(state) : r;
}
function hasSymbolIterator(value) {
	return Symbol.iterator in value;
}
function stringEntriesToHeadersInit(entries) {
	const list = [...entries];
	if (!list.length) return "";
	let duplicate = false;
	const seen = /* @__PURE__ */ new Set();
	for (const [key] of list) {
		if (seen.has(key)) {
			duplicate = true;
			break;
		}
		seen.add(key);
	}
	let result = "";
	let sep = "";
	for (const [key, value] of list) {
		result += duplicate ? sep + "[" + quote(key, 0) + "," + quote(value, 0) + "]" : sep + toObjectKey(key) + ":" + quote(value, 0);
		sep = ",";
	}
	return duplicate ? "[" + result + "]" : "{" + result + "}";
}
function typedArrayToInitString(view) {
	const suffix = typeof view[0] === "bigint" ? "n" : "";
	let result = "[";
	let sep = "";
	for (let i = 0; i < view.length; i++) {
		result += sep + view[i] + suffix;
		sep = ",";
	}
	result += "]";
	return result;
}
function hasOnlyZeros(typedArray) {
	const zero = typeof typedArray[0] === "bigint" ? 0n : 0;
	for (let i = 0; i < typedArray.length; i++) if (typedArray[i] !== zero) return false;
	return true;
}
function patchIteratorNext(proto) {
	if (proto.next[kTouchedIterator]) return;
	const { next } = proto;
	proto.next = function(value) {
		this[kTouchedIterator] = 1;
		return next.call(this, value);
	};
	proto.next[kTouchedIterator] = true;
}
//#endregion
//#region src/html/attrs.ts
function _attr_class(value) {
	return stringAttr("class", toDelimitedString(value, " ", stringifyClassEntry));
}
function _attr_style(value) {
	return stringAttr("style", toDelimitedString(value, ";", stringifyStyleEntry));
}
function _attr_option_value(value) {
	const valueAttr = _attr("value", value);
	const selectedValue = getContext(kSelectedValue);
	if (selectedValue !== void 0 && normalizedValueMatches(selectedValue, value)) {
		getContext(kSelectedValueMatched)?.add(normalizeStrAttrValue(value));
		return valueAttr + " selected";
	}
	return valueAttr;
}
const kSelectedValue = Symbol("selectedValue");
const kSelectedValueMatched = Symbol("selectedValueMatched");
function _attr_select_value(scopeId, nodeAccessor, value, valueChange, content, serializeType) {
	if (valueChange) writeControlledScope(3, scopeId, nodeAccessor, void 0, valueChange, serializeType);
	if (content) {
		const selectedValue = value ?? "";
		if (valueChange) {
			const matched = /* @__PURE__ */ new Set();
			withContext(kSelectedValue, selectedValue, () => withContext(kSelectedValueMatched, matched, content));
			if ((Array.isArray(value) ? value : [value]).some((v) => {
				const str = normalizeStrAttrValue(v);
				return str !== "" && !matched.has(str);
			})) console.error("A controlled `<select>`'s `value` has no matching `<option>`:", value);
		} else withContext(kSelectedValue, selectedValue, content);
	}
}
function _attrs_select_value(scopeId, nodeAccessor, data, content) {
	if (data && ("value" in data || data.valueChange)) _attr_select_value(scopeId, nodeAccessor, data.value, data.valueChange, content, 1);
	else content();
}
function _attr_textarea_value(scopeId, nodeAccessor, value, valueChange, serializeType) {
	if (valueChange) writeControlledScope(2, scopeId, nodeAccessor, void 0, valueChange, serializeType);
	return _textarea_value(value);
}
function _attrs_textarea_value(scopeId, nodeAccessor, data) {
	return _attr_textarea_value(scopeId, nodeAccessor, data?.value, data?.valueChange, 1);
}
function _textarea_value(value) {
	const escaped = _escape(normalizeStrAttrValue(value));
	return escaped[0] === "\n" ? "\n" + escaped : escaped;
}
function _attr_input_value(scopeId, nodeAccessor, value, valueChange, serializeType) {
	if (valueChange) writeControlledScope(2, scopeId, nodeAccessor, void 0, valueChange, serializeType);
	return _attr("value", value);
}
function _attr_input_checked(scopeId, nodeAccessor, checked, checkedChange, serializeType) {
	if (checkedChange) writeControlledScope(0, scopeId, nodeAccessor, void 0, checkedChange, serializeType);
	return isNotNullishOrFalse(checked) ? " checked" : "";
}
function _attr_input_checkedValue(scopeId, nodeAccessor, checkedValue, checkedValueChange, value, serializeType) {
	const valueAttr = _attr("value", value);
	if (checkedValueChange) writeControlledScope(1, scopeId, nodeAccessor, getCheckedValueRef(checkedValue), checkedValueChange, serializeType);
	return normalizedValueMatches(checkedValue, value) ? valueAttr + " checked" : valueAttr;
}
const checkedValuesRefs = /* @__PURE__ */ new WeakMap();
function getCheckedValueRef(checkedValue) {
	if (Array.isArray(checkedValue)) {
		let ref = checkedValuesRefs.get(checkedValue);
		if (!ref) {
			ref = [];
			checkedValuesRefs.set(checkedValue, ref);
		}
		return ref;
	}
}
function _attr_details_or_dialog_open(scopeId, nodeAccessor, open, openChange, serializeType) {
	const normalizedOpen = isNotNullishOrFalse(open);
	if (openChange) writeControlledScope(4, scopeId, nodeAccessor, normalizedOpen || void 0, openChange, serializeType);
	return normalizedOpen ? " open" : "";
}
function _attr_nonce() {
	return getChunk().boundary.state.nonceAttr;
}
function _style_html(decls) {
	const id = _id();
	return `<style${_attr_nonce()} class=${id}>.${id}~*{${decls}}</style>`;
}
function _attr(name, value) {
	return isNullishOrFalse(value) ? "" : stringifyAttr(name, value);
}
function _attr_and(name, value, attr) {
	return value ? attr : _attr(name, value);
}
function _attr_or(name, value, attr) {
	return value ? _attr(name, value) : attr;
}
function _attr_nullish(name, value, attr) {
	return value == null ? attr : _attr(name, value);
}
function _attrs(data, nodeAccessor, scopeId, tagName) {
	let result = "";
	let skip = /[\s/>"'=]/;
	let events;
	switch (data && tagName) {
		case "input":
			assertExclusiveAttrs(data);
			if (data.checkedChange) {
				result += _attr_input_checked(scopeId, nodeAccessor, data.checked, data.checkedChange, 1);
				skip = /^checked(?:Value)?(?:Change)?$|[\s/>"'=]/;
			} else if ("checkedValue" in data || data.checkedValueChange) {
				result += _attr_input_checkedValue(scopeId, nodeAccessor, data.checkedValue, data.checkedValueChange, data.value, 1);
				skip = /^(?:value|checked(?:Value)?)(?:Change)?$|[\s/>"'=]/;
			} else if (data.valueChange) {
				assertNoValueBindingOnCheckable(data.type, data.valueChange);
				result += _attr_input_value(scopeId, nodeAccessor, data.value, data.valueChange, 1);
				skip = /^value(?:Change)?$|[\s/>"'=]/;
			}
			break;
		case "select":
		case "textarea":
			if ("value" in data || data.valueChange) skip = /^value(?:Change)?$|[\s/>"'=]/;
			break;
		case "option":
			if ("value" in data) {
				result += _attr_option_value(data.value);
				skip = /^value$|[\s/>"'=]/;
			}
			break;
		case "details":
		case "dialog": if (data.openChange) {
			result += _attr_details_or_dialog_open(scopeId, nodeAccessor, data.open, data.openChange, 1);
			skip = /^open(?:Change)?$|[\s/>"'=]/;
		}
	}
	for (const name in data) {
		const value = data[name];
		switch (name) {
			case "class":
				result += _attr_class(value);
				break;
			case "style":
				result += _attr_style(value);
				break;
			default:
				if (name) assertValidAttrName(name);
				if (name && !(isNullishOrFalse(value) || skip.test(name) || name === "content" && tagName !== "meta")) {
					if (isEventHandler(name)) {
						if (!events) {
							events = {};
							writeScope(scopeId, { [EventAttributes + nodeAccessor]: events });
						}
						events[getEventType(name)] = value;
					} else result += stringifyAttr(name, value);
				}
		}
	}
	return result;
}
function _attrs_content(data, nodeAccessor, scopeId, tagName, markerGuard) {
	_html(`${_attrs(data, nodeAccessor, scopeId, tagName)}>`);
	_attr_content(nodeAccessor, scopeId, data?.content, markerGuard);
}
function _attrs_partial(data, skip, nodeAccessor, scopeId, tagName) {
	const partial = {};
	for (const name in data) {
		const key = isEventHandler(name) ? `on-${getEventType(name)}` : name;
		if (!skip[key]) partial[key] = data[name];
	}
	assertExclusiveAttrs({
		...data,
		...skip
	});
	return _attrs(partial, nodeAccessor, scopeId, tagName);
}
function _attrs_partial_content(data, skip, nodeAccessor, scopeId, tagName, markerGuard) {
	_html(`${_attrs_partial(data, skip, nodeAccessor, scopeId, tagName)}>`);
	_attr_content(nodeAccessor, scopeId, data?.content, markerGuard);
}
function writeControlledScope(type, scopeId, nodeAccessor, value, valueChange, serializeType) {
	var handlerName = [
		"checkedChange",
		"checkedValueChange",
		"valueChange",
		"valueChange",
		"openChange"
	][type];
	assertHandlerIsFunction(handlerName, valueChange);
	setDebugSlotName(writeScope(scopeId, serializeType ? {
		[ControlledType + nodeAccessor]: type,
		[ControlledValue + nodeAccessor]: value,
		[ControlledHandler + nodeAccessor]: valueChange
	} : {
		[ControlledValue + nodeAccessor]: value,
		[ControlledHandler + nodeAccessor]: valueChange
	}), ControlledHandler + nodeAccessor, handlerName);
}
function stringAttr(name, value) {
	return value && " " + name + attrAssignment(value);
}
function stringifyAttr(name, value) {
	assertValidAttrValue(name, value);
	switch (typeof value) {
		case "string": return " " + name + attrAssignment(value);
		case "boolean": return " " + name;
		case "number": return " " + name + "=" + value;
	}
	return " " + name + attrAssignment(value + "");
}
const singleQuoteAttrReplacements = /['\r]|&(?=[#a-zA-Z])/g;
const doubleQuoteAttrReplacements = /["\r]|&(?=[#a-zA-Z])/g;
const needsQuotedAttr = /["'>\s]|&[#a-zA-Z]|\/$/g;
function attrAssignment(value) {
	return value ? needsQuotedAttr.test(value) ? value[needsQuotedAttr.lastIndex - 1] === (needsQuotedAttr.lastIndex = 0, "\"") ? "='" + escapeSingleQuotedAttrValue(value) + "'" : "=\"" + escapeDoubleQuotedAttrValue(value) + "\"" : "=" + value : "";
}
function escapeSingleQuotedAttrValue(value) {
	return singleQuoteAttrReplacements.test(value) ? value.replace(singleQuoteAttrReplacements, replaceUnsafeSingleQuoteAttrChar) : value;
}
function replaceUnsafeSingleQuoteAttrChar(match) {
	return match === "'" ? "&#39;" : match === "\r" ? "&#13;" : "&amp;";
}
function escapeDoubleQuotedAttrValue(value) {
	return doubleQuoteAttrReplacements.test(value) ? value.replace(doubleQuoteAttrReplacements, replaceUnsafeDoubleQuoteAttrChar) : value;
}
function replaceUnsafeDoubleQuoteAttrChar(match) {
	return match === "\"" ? "&#34;" : match === "\r" ? "&#13;" : "&amp;";
}
function normalizedValueMatches(a, b) {
	const value = normalizeStrAttrValue(b);
	if (Array.isArray(a)) {
		for (const item of a) if (normalizeStrAttrValue(item) === value) return true;
	} else if (normalizeStrAttrValue(a) === value) return true;
	return false;
}
function normalizeStrAttrValue(value) {
	return isNotNullishOrFalse(value) && value !== true ? value + "" : "";
}
//#endregion
//#region src/html/inlined-runtimes.debug.ts
const WALKER_RUNTIME_CODE = `((runtimeId) => (self[runtimeId] ||= (
  renderId,
  prefix = runtimeId + renderId,
  prefixLen = prefix.length,
  lookup = {},
  visits = [],
  doc = document,
  walker = doc.createTreeWalker(
    doc,
    129 /* NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_ELEMENT */,
  ),
) =>
  doc = (self[runtimeId][renderId] = {
    i: prefix,
    d: doc,
    l: lookup,
    v: visits,
    x() {},
    w(node, op, id) {
      while ((node = walker.nextNode())) {
        // Only reorder markers ("#", "!") are ever looked up, so only they are
        // kept: the lookup lives as long as the page, and every node marker
        // would otherwise stay referenced in it after resume consumed it.
        doc.x(
          (op =
            (op = node.data) &&
            !op.indexOf(prefix) &&
            ((id = op.slice(prefixLen + 1)),
            (op = op[prefixLen]) > "#" || (lookup[id] = node),
            op)),
          id,
          node,
        );

        if (op > "#") {
          visits.push(node);
        }
      }
    },
  })
, self[runtimeId]))`;
const REORDER_RUNTIME_CODE = `((runtime) => {
  if (runtime.j) return;
  let onNextSibling,
    placeholder,
    nextSibling,
    placeholders = runtime.p = {},
    replace = (id, container) => runtime.l[id].replaceWith(...container.childNodes);
  runtime.j = {};
  runtime.x = (op, id, node, placeholderRoot, placeholderCb) => {
    if (node == nextSibling) {
      onNextSibling();
    }

    if (op == "#") {
      (placeholders[id] = placeholder).i++;
    } else if (node.tagName == "T" && (id = node.getAttribute(runtime.i))) {
      nextSibling = node.nextSibling;
      onNextSibling = () => {
        node.remove();
        placeholderRoot || replace(id, node);
        placeholder.c();
      };
      placeholder =
        placeholders[id] ||
        (placeholderRoot = placeholders[id] =
          {
            // The writer streams a reorder only after its markers.
            i: 1,
            r: id,
            // Resume may still walk markers inside the dropped placeholder, so
            // park it in any detached parent (a bare <t> clone is the cheapest).
            c(start = runtime.l["^" + id], removed = node.cloneNode()) {
              if (--placeholderRoot.i) return 1;
              for (
                ;
                removed.prepend(
                  (nextSibling = runtime.l[id].previousSibling || start),
                ),
                  start != nextSibling;

              );
              replace(id, node);
            },
          });
      // Opens the chunk's visits for resume to parent to the root's branch; the
      // walk that this chunk's own script triggers closes it.
      runtime.v.push({ data: runtime.i + "*" + placeholder.r });
      // repurpose "op" for callbacks ...carefully
      if ((op = runtime.j[id])) {
        placeholderCb = placeholder.c;
        placeholder.c = () => placeholderCb() || op(runtime.r);
      }
    }
  };
})`;
//#endregion
//#region src/html/writer.ts
let $chunk;
function getChunk() {
	return $chunk;
}
function withChunk(chunk, cb) {
	const prev = $chunk;
	$chunk = chunk;
	try {
		return cb();
	} finally {
		$chunk = prev;
	}
}
function getContext(key) {
	return $chunk.context?.[key];
}
function getState() {
	return $chunk.boundary.state;
}
function rendererKey(renderer) {
	return renderer?.["owner"] === void 0 ? renderer?.["id"] || renderer : renderer["id"] + " " + renderer[Owner];
}
function getScopeId(scope) {
	return scope[K_SCOPE_ID];
}
function getScopeById(scopeId) {
	if (scopeId !== void 0) return $chunk.boundary.state.scopes.get(scopeId);
}
function $global() {
	return $chunk.boundary.state.$global;
}
function _id() {
	const state = $chunk.boundary.state;
	const { $global } = state;
	return "s" + $global.runtimeId + $global.renderId + (state.tagId++).toString(36);
}
function _scope_id() {
	return $chunk.boundary.state.scopeId++;
}
function _peek_scope_id() {
	return $chunk.boundary.state.scopeId;
}
const kPendingContexts = Symbol("Pending Contexts");
function withContext(key, value, cb, cbValue, cbValue2) {
	const ctx = $chunk.context ||= { [kPendingContexts]: 0 };
	const prev = ctx[key];
	ctx[kPendingContexts]++;
	ctx[key] = value;
	try {
		return cb(cbValue, cbValue2);
	} finally {
		ctx[kPendingContexts]--;
		ctx[key] = prev;
	}
}
function captureContext(chunk) {
	if (chunk.context?.[kPendingContexts]) chunk.context = {
		...chunk.context,
		[kPendingContexts]: 0
	};
}
const kBranchId = Symbol("Branch Id");
const kAsyncContent = Symbol("Async Content");
function isInResumedBranch() {
	return $chunk?.context?.[kBranchId] !== void 0;
}
function withBranchId(branchId, cb, cbValue, cbValue2) {
	return withContext(kBranchId, branchId, cb, cbValue, cbValue2);
}
function withAsyncContent(async, cb, value) {
	return withContext(kAsyncContent, async, cb, value);
}
function _html(html) {
	$chunk.writeHTML(html);
}
function writeScript(script) {
	$chunk.writeScript(script);
}
function catchableBoundary() {
	const { boundary } = $chunk;
	return boundary.withinCatch ? boundary : null;
}
function mayDrop(written) {
	const { boundary } = $chunk;
	for (let cur = written; cur && !isWithin(boundary, cur); cur = cur.parent) if (cur.aborted || cur.count) return true;
	return false;
}
function _script(scopeId, registryId, markerGuard) {
	if (markerGuard === 0 && ($chunk.channel.readyId || $chunk.context?.[kAsyncContent])) _resume_branch(scopeId);
	$chunk.boundary.state.queueEffect(scopeId, registryId);
}
function _trailers(html) {
	$chunk.boundary.state.trailerHTML += html;
}
function _resume(val, id, scopeId, locals) {
	return register(id, val, scopeId === void 0 ? void 0 : _scope_with_id(scopeId), locals);
}
function _resume_locals(val, id, locals, ownerScopeId) {
	if (ownerScopeId !== void 0) locals["_"] = _scope_with_id(ownerScopeId);
	return register(id, val, writeScope(_scope_id(), locals));
}
function _el(scopeId, id) {
	return _resume(() => _el_read_error(), id, scopeId);
}
function _hoist(scopeId, id) {
	const getter = () => _hoist_read_error();
	getter[Symbol.iterator] = _hoist_read_error;
	return _resume(getter, id, scopeId);
}
function _el_resume(scopeId, accessor, markerGuard) {
	if (markerGuard === 0) return "";
	const { state } = $chunk.boundary;
	state.needsWalkerRuntime = true;
	return state.mark("$", scopeId + " " + accessor);
}
function _text_resume(scopeId, accessor, val, markerGuard) {
	return markText(scopeId, accessor, _escape(val), markerGuard);
}
function _html_resume(scopeId, accessor, val, markerGuard) {
	const html = _unescaped(val);
	if (markerGuard === 0 || !~html.indexOf("<")) return markText(scopeId, accessor, html, markerGuard);
	const { state } = $chunk.boundary;
	state.needsWalkerRuntime = true;
	return state.mark("&", "") + html + state.mark("'", scopeId + " " + accessor);
}
function markText(scopeId, accessor, text, markerGuard) {
	if (markerGuard === 0) return text;
	const { state } = $chunk.boundary;
	state.needsWalkerRuntime = true;
	return text ? (markerGuard === 2 ? "<!>" : "") + text + state.mark("$", scopeId + " " + accessor) : state.mark("%", scopeId + " " + accessor);
}
function _resume_branch(scopeId) {
	const branchId = $chunk.context?.[kBranchId];
	if (branchId !== void 0 && branchId !== scopeId) writeScope(scopeId, { [ClosestBranchId]: branchId });
}
function _attr_content(nodeAccessor, scopeId, content, markerGuard) {
	const shouldResume = markerGuard !== 0;
	const render = normalizeServerRender(content);
	const branchId = _peek_scope_id();
	if (render) try {
		_set_scope_reason(shouldResume ? ALL_GROUPS : 0);
		if (shouldResume) withBranchId(branchId, render);
		else render();
	} finally {
		_set_scope_reason(void 0);
	}
	if (_peek_scope_id() !== branchId) {
		if (shouldResume) writeScope(scopeId, {
			[BranchScopes + nodeAccessor]: writeScope(branchId, {}),
			[ConditionalRenderer + nodeAccessor]: rendererKey(render)
		});
	} else _scope_id();
}
function normalizeServerRender(value) {
	const renderer = normalizeDynamicRenderer(value);
	if (renderer) {
		if (typeof renderer === "function") return renderer;
		else throw new Error(`Invalid \`content\` attribute. Received ${typeof value}`);
	}
}
function _var(parentScopeId, scopeOffsetAccessor, childScopeId, registryId, nodeAccessor) {
	writeScopePassive(parentScopeId, { [scopeOffsetAccessor]: _scope_id() });
	const childScope = writeScopePassive(childScopeId, { [TagVariable]: _resume({}, registryId, parentScopeId) });
	if (nodeAccessor !== void 0) writeScope(parentScopeId, { [BranchScopes + nodeAccessor]: childScope });
}
function writeScopePassive(scopeId, partialScope) {
	const target = $chunk.channel;
	const scope = _scope_with_id(scopeId);
	Object.assign(scope, partialScope);
	$chunk.boundary.state.queuePassiveScope(target, scopeId, partialScope);
	return scope;
}
let writeScope = (scopeId, partialScope) => {
	const { state } = $chunk.boundary;
	const target = $chunk.channel;
	const scope = scopeWithId(state, scopeId);
	state.needsWalkerRuntime = true;
	countResumeWrite($chunk);
	writeAsyncVisits($chunk);
	Object.assign(scope, partialScope);
	state.queueScope(target, scopeId, partialScope);
	return scope;
};
writeScope = ((writeScope) => (scopeId, partialScope, file, loc, vars) => {
	const scope = writeScope(scopeId, partialScope);
	if (file && loc !== void 0) setDebugInfo(scope, file, loc, vars);
	return scope;
})(writeScope);
function _existing_scope(scopeId) {
	return writeScope(scopeId, {});
}
function _scope_with_id(scopeId) {
	return scopeWithId($chunk.boundary.state, scopeId);
}
function scopeWithId(state, scopeId) {
	const { scopes } = state;
	let scope = scopes.get(scopeId);
	if (!scope) scopes.set(scopeId, scope = { [K_SCOPE_ID]: scopeId });
	return scope;
}
function _subscribe(subscribers, scope, resumeId, markerGuard) {
	if (subscribers) {
		const { boundary, channel } = $chunk;
		const { serializer } = boundary.state;
		if (!channel.readyId && !serializer.refs.has(subscribers)) subscribers.add(scope);
		else if (resumeId) _script(scope[K_SCOPE_ID], resumeId, markerGuard);
		else queueCall(serializer, scope, subscribers, "add", channel);
		if (boundary.withinCatch) (boundary.subscribed ||= []).push(subscribers, scope, channel);
	}
	return scope;
}
const ALL_GROUPS = 715827883;
function getGroupReason(reason, group) {
	return reason === 715827883 ? 1 : typeof reason === "number" ? group < 15 ? reason >>> 1 + 2 * group & 3 : 0 : reason[group] ?? 0;
}
function _set_scope_reason(reason) {
	$chunk.boundary.state.scopeReason = reason;
}
function _scope_reason() {
	const reason = $chunk.boundary.state.scopeReason;
	$chunk.boundary.state.scopeReason = void 0;
	return reason;
}
function _write_if(reason, group) {
	return reason && getGroupReason(reason, group) ? 1 : void 0;
}
function _write_guard(reason, group) {
	return _write_if(reason, group) || 0;
}
function writeWaitReady(readyId, renderer, input) {
	const chunk = $chunk;
	const { boundary } = chunk;
	const body = new Chunk(boundary, null, chunk.context, {
		readyId,
		parent: chunk.channel,
		resumes: "",
		writeScopes: {},
		flushScopes: false
	});
	const bodyEnd = body.render(renderer, input);
	if (boundary.aborted) throw boundary.reason;
	if (body === bodyEnd) {
		chunk.writeHTML(body.html);
		body.deferOwnReady();
		chunk.deferredReady = push(chunk.deferredReady, body);
	} else {
		bodyEnd.next = chunk.forkRest(boundary);
		chunk.next = body;
	}
}
function deferBranchStart(chunk) {
	const beforeBranch = chunk.html;
	chunk.html = "";
	return beforeBranch;
}
function applyBranchStart(chunk, beforeBranch, rendered) {
	chunk.html = beforeBranch + (rendered ? chunk.boundary.state.mark("[", "") : "") + chunk.html;
}
function unsubscribe(subscribed, serializer) {
	for (let i = 0; i < subscribed.length; i += 3) {
		const subscribers = subscribed[i];
		const scope = subscribed[i + 1];
		if (!serializer.refs.has(subscribers)) subscribers.delete(scope);
		else {
			const channel = subscribed[i + 2];
			if (!dropQueuedCall(serializer, scope, subscribers, "add", channel)) queueCall(serializer, scope, subscribers, "delete", channel);
		}
	}
}
const NOOP$2 = () => {};
function countResumeWrite(chunk) {
	for (let boundary = chunk.boundary; boundary; boundary = boundary.parent) boundary.resumeWrites++;
}
function writeAsyncVisits(chunk) {
	for (let async = getAsyncContent(chunk); async && !async.resumed; async = async.parent) {
		async.resumed = true;
		async.end?.writeHTML(async.visit);
	}
}
function getAsyncContent(chunk) {
	return chunk.context?.[kAsyncContent];
}
var State = class {
	tagId = 1;
	scopeId = 1;
	reorderId = 1;
	readyGate = 1;
	hasWrittenGlobals = false;
	needsWalkerRuntime = false;
	hasWalkerRuntime = false;
	hasWrittenReady = false;
	hasReorderRuntime = false;
	hasWrittenResume = false;
	walkOnNextFlush = false;
	trailerHTML = "";
	resumes = "";
	nonceAttr = "";
	serializer = new State$1();
	writeReorders = null;
	scopes = /* @__PURE__ */ new Map();
	scope = (scopeId) => scopeWithId(this, scopeId);
	flushScopes = false;
	writeScopes = {};
	readyIds = null;
	scopeReason;
	$global;
	constructor($global) {
		this.$global = $global;
		if ($global.cspNonce) this.nonceAttr = " nonce" + attrAssignment($global.cspNonce);
	}
	joinFlush(html, scripts, pending) {
		const { $global, nonceAttr } = this;
		const { __flush__ } = $global;
		if (scripts) html += "<script" + nonceAttr + ">" + scripts + "<\/script>";
		if (__flush__) {
			$global.__flush__ = void 0;
			html = __flush__($global, html);
		}
		return pending ? html : html + this.trailerHTML;
	}
	walkScript() {
		return this.runtimePrefix + ".w()";
	}
	addResumes(channel, resumes) {
		channel.resumes = concatSequence(channel.resumes, resumes);
	}
	queueScope(target, scopeId, partialScope) {
		const pending = target.writeScopes[scopeId];
		if (pending && pending !== partialScope) Object.assign(pending, partialScope);
		else target.writeScopes[scopeId] = partialScope;
		target.flushScopes = true;
	}
	queuePassiveScope(target, scopeId, partialScope) {
		const passive = target.passiveScopes ||= {};
		passive[scopeId] = Object.assign(passive[scopeId] || {}, partialScope);
	}
	queueEffect(scopeId, registryId) {
		this.needsWalkerRuntime = true;
		$chunk.writeEffect(scopeId, registryId);
	}
	serializeFlush(boundary) {
		flushSerializer(boundary, this);
	}
	runtimeScript() {
		return WALKER_RUNTIME_CODE + "(\"" + this.$global.runtimeId + "\")(\"" + this.$global.renderId + "\")";
	}
	keepsTryMarks(chunk, resumeWrites) {
		return chunk !== $chunk || chunk.boundary.resumeWrites !== resumeWrites;
	}
	resumeScript(resumes) {
		if (this.hasWrittenResume) return this.runtimePrefix + ".r.push(" + resumes + ")";
		this.hasWrittenResume = true;
		return this.runtimePrefix + ".r=[" + resumes + "]";
	}
	get runtimePrefix() {
		const { $global } = this;
		return $global.runtimeId + "." + $global.renderId;
	}
	get commentPrefix() {
		const { $global } = this;
		return $global.runtimeId + $global.renderId;
	}
	reorder(chunk) {
		if (this.writeReorders) this.writeReorders.push(chunk);
		else {
			this.needsWalkerRuntime = true;
			this.writeReorders = [chunk];
		}
	}
	readyScript(id, resumes) {
		const readyKey = toObjectKey(id);
		if (this.readyIds?.has(id)) return this.readyAccess(readyKey) + ".push(" + resumes + ")";
		(this.readyIds ||= /* @__PURE__ */ new Set()).add(id);
		if (this.hasWrittenReady) return this.readyAccess(readyKey) + "=[" + resumes + "]";
		this.hasWrittenReady = true;
		return this.runtimePrefix + ".b={" + readyKey + ":[" + resumes + "]}";
	}
	readyAccess(readyKey) {
		return this.runtimePrefix + ".b" + toAccess(readyKey);
	}
	nextReorderId() {
		const c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
		let n = this.reorderId++;
		let r = c[n % 54];
		for (n = n / 54 | 0; n; n >>>= 6) r += c[n & 63];
		return r;
	}
	mark(code, str) {
		return "<!--" + this.commentPrefix + code + str + "-->";
	}
};
var Boundary = class {
	onNext = NOOP$2;
	count = 0;
	resumeWrites = 0;
	state;
	parent;
	aborted = false;
	reason;
	subscribed;
	pendingReorders;
	children;
	withinCatch = false;
	constructor(state, signal, parent) {
		this.state = state;
		this.parent = parent;
		if (parent) {
			this.withinCatch = parent.withinCatch;
			if (parent.aborted) this.abort(parent.reason);
			else (parent.children ||= []).push(this);
		} else if (signal) {
			if (signal.aborted) this.abort(signal.reason);
			else signal.addEventListener("abort", this);
		}
	}
	abort(reason) {
		if (this.aborted) return;
		const { state } = this;
		this.aborted = true;
		this.reason = reason;
		if (this.subscribed) unsubscribe(this.subscribed, state.serializer);
		if (this.pendingReorders) {
			for (const reorder of this.pendingReorders) state.reorder(reorder);
			this.pendingReorders = void 0;
		}
		this.count = 0;
		this.state = new State(state.$global);
		if (this.children) for (const child of this.children) child.abort(reason);
		this.onNext();
	}
	handleEvent(event) {
		this.abort(event.target.reason);
	}
	flush() {
		if (!this.aborted) this.state.serializeFlush(this);
		return this.count ? 1 : this.aborted ? 2 : 0;
	}
	startAsync() {
		if (!this.aborted) this.count++;
	}
	endAsync() {
		if (!this.aborted) {
			if (!this.count) throw new Error("A boundary ended more async work than it started.");
			this.count--;
			this.onNext();
		}
	}
};
var Chunk = class Chunk {
	html = "";
	scripts = "";
	effects = "";
	lastEffect = "";
	async = false;
	consumed = false;
	reorderId = null;
	reorderBranch = 0;
	deferredReady = null;
	heldEffects = null;
	deferredReorder = null;
	catchRange = null;
	placeholder = null;
	boundary;
	next;
	context;
	channel;
	constructor(boundary, next, context, channel) {
		this.boundary = boundary;
		this.next = next;
		this.context = context;
		this.channel = channel;
	}
	fork(boundary, next) {
		return new Chunk(boundary, next, this.context, this.channel);
	}
	forkRest(boundary) {
		return $chunk = this.fork(boundary, this.next);
	}
	writeHTML(html) {
		this.html += html;
	}
	writeEffect(scopeId, registryId) {
		countResumeWrite(this);
		writeAsyncVisits(this);
		if (this.lastEffect === registryId) this.effects = concatEffects(this.effects, scopeId + "");
		else {
			this.lastEffect = registryId;
			this.effects = concatEffects(this.effects, registryId + " " + scopeId);
		}
	}
	writeScript(script) {
		this.scripts = concatScripts(this.scripts, script);
	}
	append(chunk) {
		this.html += chunk.html;
		this.effects = concatEffects(this.effects, chunk.effects);
		this.scripts = concatScripts(this.scripts, chunk.scripts);
		this.lastEffect = chunk.lastEffect || this.lastEffect;
		this.deferredReady = concat(this.deferredReady, chunk.takeDeferredReady());
	}
	takeHeldEffects() {
		const { heldEffects } = this;
		this.heldEffects = null;
		return heldEffects;
	}
	takeDeferredReady() {
		const { deferredReady } = this;
		this.deferredReady = null;
		return deferredReady;
	}
	deferOwnReady() {
		if (this.channel.readyId && (this.effects || this.scripts || this.channel.flushScopes)) {
			const deferred = this.fork(this.boundary, null);
			deferred.effects = this.effects;
			deferred.scripts = this.scripts;
			this.effects = this.scripts = this.lastEffect = "";
			this.deferredReady = concat(deferred, this.deferredReady);
		}
	}
	renderPlaceholders(boundary) {
		const { state } = boundary;
		restart: for (;;) {
			let reorders = null;
			for (let cur = this; cur.next && !cur.async; cur = cur.next) {
				if (cur.renderPlaceholder(state)) {
					if (boundary.aborted) return;
					continue restart;
				}
				if (cur.deferredReorder) (reorders ||= []).push(cur.deferredReorder);
			}
			if (state.writeReorders) {
				for (const reorder of state.writeReorders) if ((reorders = renderReorderPlaceholders(reorder, reorders)) === false) {
					if (boundary.aborted) return;
					continue restart;
				}
			}
			for (let i = 0; reorders && i < reorders.length; i++) if ((reorders = renderReorderPlaceholders(reorders[i], reorders)) === false) {
				if (boundary.aborted) return;
				continue restart;
			}
			return;
		}
	}
	renderPlaceholder(state) {
		const { placeholder } = this;
		if (!placeholder) return false;
		this.placeholder = null;
		if (this.boundary.aborted) return false;
		const { body } = placeholder;
		let end = body;
		while (end.next && !end.async) end = end.next;
		if (!end.async) {
			end.next = this.next;
			this.next = body;
			return false;
		}
		const { branchId, scopeId, placeholderBranchId } = placeholder;
		const reorderId = body.reorderId = branchId + "";
		this.writeHTML(state.mark("!^", reorderId));
		const { effects } = this;
		const beforeBranch = deferBranchStart(this);
		if (this.render(withBranchId, placeholderBranchId, placeholder.render) !== this) this.boundary.abort(/* @__PURE__ */ new Error("An @placeholder cannot contain async content."));
		if (this.boundary.aborted) return true;
		const stateful = this.effects !== effects;
		applyBranchStart(this, beforeBranch, stateful);
		if (stateful) {
			this.render(writeScope, branchId, { [PlaceholderBranch]: scopeWithId(state, placeholderBranchId) });
			this.writeHTML(state.mark("]", scopeId + " " + (PlaceholderBranch + branchId) + " " + placeholderBranchId));
			dismissChunk(end, body).writeEffect(branchId, PLACEHOLDER_DISMISS_REGISTER_ID);
		}
		this.writeHTML(state.mark("!", reorderId));
		this.deferredReorder = body;
		return false;
	}
	markCatchRange() {
		const { catchRange } = this;
		if (catchRange) {
			const { state } = this.boundary;
			this.catchRange = null;
			this.writeHTML(state.mark("!^", catchRange.id));
			catchRange.end.writeHTML(state.mark("!", catchRange.id));
		}
	}
	queueDeferredReorder() {
		const { deferredReorder } = this;
		if (deferredReorder) {
			this.deferredReorder = null;
			deferredReorder.boundary.state.reorder(deferredReorder);
		}
	}
	consume(boundary) {
		this.renderPlaceholders(boundary);
		let cur = this;
		let html = "";
		let effects = "";
		let scripts = "";
		let effectsEnd;
		let heldEffects = this.heldEffects;
		let deferredReady;
		this.heldEffects = null;
		if (this.channel.readyId && this.effects) followHeldEffects(this);
		while (cur.next && !cur.async) {
			cur.markCatchRange();
			cur.queueDeferredReorder();
			html += cur.html;
			if (cur.channel.readyId) deferredReady = push(deferredReady, cur);
			else {
				if (cur.effects) {
					if (effectsEnd && effectsEnd.boundary !== cur.boundary) {
						heldEffects = holdEffectsOn(heldEffects, effectsEnd, effects);
						effects = "";
					}
					effectsEnd = cur;
					effects = concatEffects(effects, cur.effects);
				}
				scripts = concatScripts(scripts, cur.scripts);
			}
			deferredReady = concat(deferredReady, cur.takeDeferredReady());
			cur.consumed = true;
			cur = cur.next;
		}
		cur.deferOwnReady();
		if (effects) {
			if (cur.channel.readyId) heldEffects = holdEffectsOn(heldEffects, effectsEnd, effects);
			else if (effectsEnd.boundary !== cur.boundary) {
				heldEffects = holdEffectsOn(heldEffects, effectsEnd, effects);
				if (isWithin(cur.boundary, effectsEnd.boundary)) cur.lastEffect ||= effectsEnd.lastEffect;
			} else {
				cur.effects = concatEffects(effects, cur.effects);
				cur.lastEffect ||= effectsEnd.lastEffect;
			}
		}
		cur.heldEffects = heldEffects;
		cur.deferredReady = concat(deferredReady, cur.deferredReady);
		cur.html = html + cur.html;
		cur.scripts = concatScripts(scripts, cur.scripts);
		return cur;
	}
	render(content, val, val2) {
		const prev = $chunk;
		$chunk = this;
		try {
			content(val, val2);
			return $chunk;
		} catch (err) {
			this.boundary.abort(err);
			return this;
		} finally {
			$chunk = prev;
		}
	}
	flushReadyScripts(boundary, reservations, holdEffects) {
		const { channel } = this;
		const { readyId } = channel;
		let scripts = "";
		const held = this.takeDeferredReady();
		if (held) for (const chunk of Array.isArray(held) ? held : [held]) {
			if (chunk.boundary.aborted) continue;
			scripts = concatScripts(scripts, chunk.flushReadyScripts(boundary, reservations, holdEffects));
			if (chunk.effects || chunk.deferredReady) this.deferredReady = push(this.deferredReady, chunk);
		}
		if (readyId && !this.async) {
			const { state } = boundary;
			flushSerializer(boundary, channel);
			const deps = takeChannelDeps(state.serializer);
			const effects = holdEffects ? "" : this.effects;
			const { resumes } = channel;
			const chunkScripts = this.scripts;
			channel.resumes = this.scripts = "";
			if (effects) this.effects = this.lastEffect = "";
			if (resumes || effects) {
				state.needsWalkerRuntime = true;
				const batch = concatSequence(depsMarker(deps), concatSequence(resumes, effects && `"${effects}"`));
				if (reservations) {
					const gate = state.readyGate++;
					reservations.push(state.readyScript(readyId, gate + ""));
					scripts = concatScripts(scripts, "(b=>b.splice(b.indexOf(" + gate + "),1," + batch + "))(" + state.readyAccess(toObjectKey(readyId)) + ")");
				} else scripts = concatScripts(scripts, state.readyScript(readyId, batch));
			}
			scripts = concatScripts(scripts, chunkScripts);
		}
		return scripts;
	}
	flush(boundary) {
		const { state } = boundary;
		const { runtimePrefix } = state;
		let needsWalk = state.walkOnNextFlush;
		if (needsWalk) state.walkOnNextFlush = false;
		flushSerializer(boundary, state);
		let readyResumeScripts = this.flushReadyScripts(boundary, void 0, this.async);
		for (let channel; !boundary.aborted && (channel = pendingReadyChannel(state.serializer));) {
			const resumes = stringifyScopes(state.serializer, [], boundary, channel);
			const deps = takeChannelDeps(state.serializer);
			state.needsWalkerRuntime = true;
			readyResumeScripts = concatScripts(readyResumeScripts, state.readyScript(channel.readyId, concatSequence(depsMarker(deps), resumes)));
		}
		if (readyResumeScripts) needsWalk = true;
		const effects = this.async ? "" : joinHeldEffects(this.takeHeldEffects(), this.effects);
		let { html, scripts } = this;
		if (html && state.hasReorderRuntime) html = state.mark("*", "") + html;
		if (state.needsWalkerRuntime && !state.hasWalkerRuntime) {
			state.hasWalkerRuntime = true;
			scripts = concatScripts(scripts, state.runtimeScript());
		}
		scripts = concatScripts(scripts, readyResumeScripts);
		if (effects) {
			needsWalk = true;
			state.resumes = state.resumes ? state.resumes + ",\"" + effects + "\"" : "\"" + effects + "\"";
		}
		let reordered = "";
		let needsResumeArray = false;
		if (state.writeReorders) {
			for (const reorderedChunk of state.writeReorders) {
				needsWalk = true;
				if (!state.hasReorderRuntime) {
					state.hasReorderRuntime = true;
					scripts = concatScripts(scripts, REORDER_RUNTIME_CODE + "(" + runtimePrefix + ")");
				}
				const { reorderId, reorderBranch } = reorderedChunk;
				const rootBranch = reorderBranch || +reorderId;
				const readyReservations = [];
				let reorderHTML = "";
				let reorderEffects = "";
				let effectsBoundary = reorderedChunk.boundary;
				let reorderScripts = "";
				let cur = reorderedChunk.boundary.aborted ? null : reorderedChunk;
				reorderedChunk.reorderId = null;
				while (cur) {
					cur.markCatchRange();
					cur.queueDeferredReorder();
					cur.deferOwnReady();
					const { next } = cur;
					const readyResumeScripts = cur.flushReadyScripts(boundary, readyReservations, this.async);
					this.deferredReady = concat(this.deferredReady, cur.takeDeferredReady());
					cur.consumed = true;
					reorderHTML += cur.html;
					if (this.async && cur.effects && cur.boundary !== effectsBoundary) {
						if (reorderEffects) {
							holdReorderEffects(this, effectsBoundary, reorderEffects);
							reorderEffects = "";
						}
						effectsBoundary = cur.boundary;
					}
					reorderEffects = concatEffects(reorderEffects, cur.effects);
					reorderScripts = concatScripts(reorderScripts, concatScripts(readyResumeScripts, cur.scripts));
					if (cur.async) {
						reorderHTML += state.mark("#", cur.reorderId = state.nextReorderId());
						const holeBranch = cur.context?.[kBranchId];
						cur.reorderBranch = holeBranch > rootBranch ? holeBranch : reorderBranch;
						(cur.boundary.pendingReorders ||= /* @__PURE__ */ new Set()).add(cur);
						cur.html = cur.effects = cur.scripts = cur.lastEffect = "";
						cur.next = null;
					}
					cur = next;
				}
				if (reorderEffects) {
					if (this.async) holdReorderEffects(this, effectsBoundary, reorderEffects);
					else {
						needsResumeArray = true;
						reorderScripts = concatScripts(reorderScripts, "_.push(\"" + reorderEffects + "\")");
					}
				}
				for (const reservation of readyReservations) reordered = concatScripts(reordered, reservation);
				reordered = concatScripts(reordered, reorderScripts && runtimePrefix + ".j" + toAccess(reorderId) + "=_=>{" + reorderScripts + "}");
				html += "<t hidden " + state.commentPrefix + "=" + reorderId + ">" + (reorderBranch ? state.mark("*", reorderBranch + "") : "") + reorderHTML + "</t>";
			}
			state.writeReorders = null;
		}
		if (state.resumes || needsResumeArray && !state.hasWrittenResume) scripts = concatScripts(scripts, state.resumeScript(state.resumes));
		scripts = concatScripts(scripts, reordered);
		if (needsWalk) scripts = concatScripts(scripts, state.walkScript());
		this.html = html;
		this.scripts = scripts;
		if (!this.async) this.effects = this.lastEffect = "";
		state.resumes = "";
		return this;
	}
	flushHTML(boundary) {
		const { state } = boundary;
		this.flush(boundary);
		const { html, scripts } = this;
		this.html = this.scripts = "";
		return state.joinFlush(html, scripts, boundary.count);
	}
};
function renderReorderPlaceholders(reorder, reorders) {
	if (!reorder.boundary.aborted) for (let cur = reorder; cur; cur = cur.next) {
		if (cur.renderPlaceholder(reorder.boundary.state)) return false;
		if (cur.deferredReorder) (reorders ||= []).push(cur.deferredReorder);
	}
	return reorders;
}
function dismissChunk(end, body) {
	if (end.boundary !== body.boundary) while (end.next) end = end.next;
	return end;
}
function followHeldEffects(chunk) {
	const held = reduce(chunk.deferredReady, lastHeldOf, chunk);
	if (held !== chunk) {
		held.effects = concatEffects(held.effects, chunk.effects);
		chunk.effects = "";
	}
}
function lastHeldOf(held, cur) {
	return cur.channel === held.channel && cur.boundary === held.boundary ? cur : held;
}
function holdEffectsOn(heldEffects, chunk, effects) {
	chunk.effects = effects;
	return push(heldEffects, chunk);
}
function isWithin(boundary, outer) {
	while (boundary && boundary !== outer) boundary = boundary.parent;
	return !!boundary;
}
function holdReorderEffects(head, boundary, effects) {
	if (!head.channel.readyId) {
		if (head.effects) head.heldEffects = holdEffectsOn(head.heldEffects, head.fork(head.boundary, null), head.effects);
		head.effects = head.lastEffect = "";
	}
	head.heldEffects = holdEffectsOn(head.heldEffects, head.fork(boundary, null), effects);
}
function joinHeldEffects(heldEffects, effects) {
	return concatEffects(reduce(heldEffects, joinUncaught, ""), effects);
}
function joinUncaught(joined, held) {
	return held.boundary.aborted ? joined : concatEffects(joined, held.effects);
}
function flushSerializer(boundary, channel) {
	const { state } = boundary;
	const { serializer } = state;
	const pending = hasMatchingCalls(serializer, channel.readyId);
	if (channel.flushScopes || pending) {
		const { writeScopes, passiveScopes } = channel;
		const flushes = [];
		if (passiveScopes) for (const key in passiveScopes) {
			const props = writeScopes[key];
			if (props) {
				writeScopes[key] = Object.assign(passiveScopes[key], props);
				delete passiveScopes[key];
			}
		}
		if (!channel.readyId && !state.hasWrittenGlobals) {
			state.hasWrittenGlobals = true;
			const globals = getFilteredGlobals(state.$global);
			if (globals) flushes.push([
				0,
				globals,
				globals
			]);
		}
		for (const key in writeScopes) {
			const scopeId = +key;
			const props = writeScopes[scopeId];
			if (hasKeys(props)) flushes.push([
				scopeId,
				state.scopes.get(scopeId),
				props
			]);
		}
		if (flushes.length || pending) {
			if (channel.readyId && !state.hasWrittenGlobals) flushSerializerGlobals(boundary);
			state.addResumes(channel, stringifyScopes(serializer, flushes, boundary, channel));
		}
		channel.writeScopes = {};
		channel.flushScopes = false;
		if (pending) state.walkOnNextFlush = true;
	}
}
function flushSerializerGlobals(boundary) {
	const { state } = boundary;
	const globals = getFilteredGlobals(state.$global);
	if (globals) {
		state.hasWrittenGlobals = true;
		state.needsWalkerRuntime = true;
		state.resumes = concatSequence(state.resumes, stringifyScopes(state.serializer, [[
			0,
			globals,
			globals
		]], boundary));
	}
}
function depsMarker(deps) {
	let marker = "";
	if (deps) {
		for (const dep of deps) marker += (marker ? "," : "[") + quote(dep, 0);
		marker += "]";
	}
	return marker;
}
function getFilteredGlobals($global) {
	if (!$global) return 0;
	const serializedGlobals = $global.serializedGlobals;
	if (!serializedGlobals) return 0;
	let filtered = 0;
	if (Array.isArray(serializedGlobals)) for (const key of serializedGlobals) {
		const value = $global[key];
		if (value !== void 0) {
			if (filtered) filtered[key] = value;
			else filtered = { [key]: value };
		}
	}
	else for (const key in serializedGlobals) if (serializedGlobals[key]) {
		const value = $global[key];
		if (value !== void 0) {
			if (filtered) filtered[key] = value;
			else filtered = { [key]: value };
		}
	}
	return filtered;
}
function concatEffects(a, b) {
	return a ? b ? a + " " + b : a : b;
}
function concatSequence(a, b) {
	return a ? b ? a + "," + b : a : b;
}
function concatScripts(a, b) {
	return a ? b ? a + ";" + b : a : b;
}
const tick = globalThis.setImmediate || globalThis.setTimeout || globalThis.queueMicrotask || ((cb) => Promise.resolve().then(cb));
let tickQueue;
function queueTick(cb) {
	if (tickQueue) tickQueue.add(cb);
	else {
		tickQueue = /* @__PURE__ */ new Set([cb]);
		tick(flushTickQueue);
	}
}
function offTick(cb) {
	tickQueue?.delete(cb);
}
function flushTickQueue() {
	const queue = tickQueue;
	tickQueue = void 0;
	for (const cb of queue) try {
		cb(true);
	} catch (err) {
		tick(() => {
			throw err;
		});
	}
}
//#endregion
//#region src/html/content.ts
function _to_text(val) {
	assertValidTextValue(val);
	return val || val === 0 ? val + "" : "";
}
function _unescaped(val) {
	assertValidTextValue(val);
	return val ? val + "" : val === 0 ? "0" : "";
}
const unsafeXMLReg = /[<&\r]/g;
const replaceUnsafeXML = (c) => c === "&" ? "&amp;" : c === "<" ? "&lt;" : "&#13;";
const escapeXMLStr = (str) => unsafeXMLReg.test(str) ? str.replace(unsafeXMLReg, replaceUnsafeXML) : str;
function _escape(val) {
	assertValidTextValue(val);
	return val ? escapeXMLStr(val + "") : val === 0 ? "0" : "";
}
const unsafeScriptReg = /<(\/?script|!--)/gi;
const escapeScriptStr = (str) => unsafeScriptReg.test(str) ? str.replace(unsafeScriptReg, "\\u003C$1") : str;
function _escape_script(val) {
	assertValidTextValue(val);
	return val ? escapeScriptStr(val + "") : val === 0 ? "0" : "";
}
const unsafeScriptTemplateLiteralReg = /[`\\\r]|\$\{|<(?=\/?script|!--)/gi;
const replaceUnsafeScriptTemplateLiteral = (c) => c === "<" ? "\\x3C" : c === "\r" ? "\\r" : "\\" + c;
const quoteScriptTemplateLiteral = (str) => "`" + (unsafeScriptTemplateLiteralReg.test(str) ? str.replace(unsafeScriptTemplateLiteralReg, replaceUnsafeScriptTemplateLiteral) : str) + "`";
const unsafeStyleReg = /<(\/style)/gi;
const escapeStyleStr = (str) => unsafeStyleReg.test(str) ? str.replace(unsafeStyleReg, "\\3C$1") : str;
function _escape_style(val) {
	assertValidTextValue(val);
	return val ? escapeStyleStr(val + "") : val === 0 ? "0" : "";
}
function _escape_style_value(val) {
	assertValidTextValue(val);
	return val || val === 0 ? escapeStyleValue(val + "") : "";
}
const unsafeCommentReg = />/g;
function escapeCommentStr(str) {
	if (unsafeCommentReg.test(str)) str = str.replace(unsafeCommentReg, "&gt;");
	return str.startsWith(getState().commentPrefix) ? "&#" + str.charCodeAt(0) + ";" + str.slice(1) : str;
}
function _escape_comment(val) {
	assertValidTextValue(val);
	return val ? escapeCommentStr(val + "") : val === 0 ? "0" : "";
}
//#endregion
//#region src/html/dynamic-tag.ts
const voidElementsReg = /^(?:area|b(?:ase|r)|col|embed|hr|i(?:mg|nput)|link|meta|param|source|track|wbr)$/;
let _dynamic_tag = (scopeId, accessor, tag, inputOrArgs, content, inputIsArgs, markerGuard, tagVar) => {
	const shouldResume = markerGuard !== 0;
	const renderer = normalizeDynamicRenderer(tag);
	const state = getState();
	const branchId = _peek_scope_id();
	let rendered;
	let result;
	if (typeof renderer === "string") {
		assertValidTagName(renderer);
		const input = (inputIsArgs ? inputOrArgs[0] : inputOrArgs) || {};
		rendered = true;
		const renderNative = () => {
			_scope_id();
			_html(`<${renderer}${_attrs(input, `#${renderer.toLowerCase()}/0`, branchId, renderer)}>`);
			if (!voidElementsReg.test(renderer)) {
				const renderContent = content || normalizeDynamicRenderer(input.content);
				if (renderer === "textarea") {
					if (renderContent) throw new Error("A dynamic tag rendering a `<textarea>` cannot have `content` and must use the `value` attribute instead.");
					_html(_attrs_textarea_value(branchId, `#${renderer.toLowerCase()}/0`, input));
				} else {
					if (renderContent && typeof renderContent !== "function") throw new Error(`Body content is not supported for the \`<${renderer}>\` tag.`);
					if (renderer === "select" && ("value" in input || "valueChange" in input)) _attr_select_value(branchId, `#${renderer.toLowerCase()}/0`, input.value, input.valueChange, renderContent ? () => _dynamic_tag(branchId, `#${renderer.toLowerCase()}/0`, renderContent, void 0, 0, void 0, markerGuard) : void 0, 1);
					else if (renderContent) _dynamic_tag(branchId, `#${renderer.toLowerCase()}/0`, renderContent, void 0, 0, void 0, markerGuard);
				}
				_html(`</${renderer}>`);
			} else if (content) throw new Error(`Body content is not supported for the \`<${renderer}>\` tag.`);
			const childScope = getScopeById(branchId);
			const needsScript = childScope && (childScope[`EventAttributes:#${renderer.toLowerCase()}/0`] || childScope[`ControlledHandler:#${renderer.toLowerCase()}/0`]);
			if (needsScript) {
				writeScope(branchId, { [Renderer]: renderer });
				_script(branchId, DYNAMIC_TAG_SCRIPT_REGISTER_ID);
			}
			if (shouldResume || needsScript) _html(state.mark("(", scopeId + " " + accessor + " " + branchId));
		};
		renderNative();
		result = _el(scopeId, DYNAMIC_TAG_VAR_REGISTER_ID + accessor);
	} else {
		if (tagVar && renderer?.["lazy"]) throw new Error(`A dynamic tag with a [tag variable](https://markojs.com/docs/reference/language#tag-variables) rendered \`${renderer["id"]}\`, which is lazily loaded, so it does not support one. Import it without \`load\`, or remove the variable.`);
		const chunk = getChunk();
		const beforeBranch = shouldResume ? deferBranchStart(chunk) : void 0;
		const render = () => {
			if (renderer) try {
				_set_scope_reason(shouldResume ? ALL_GROUPS : 0);
				return inputIsArgs ? renderer(...inputOrArgs) : renderer(content ? {
					...inputOrArgs,
					content
				} : inputOrArgs);
			} finally {
				_set_scope_reason(void 0);
			}
			else if (content) content();
		};
		result = shouldResume ? withBranchId(branchId, render) : render();
		rendered = _peek_scope_id() !== branchId;
		if (beforeBranch !== void 0) {
			applyBranchStart(chunk, beforeBranch, rendered);
			_html(state.mark("]", scopeId + " " + accessor + (rendered ? " " + branchId : "")));
			if (renderer) _existing_scope(branchId);
		}
	}
	if (rendered) {
		if (shouldResume) writeScope(scopeId, { [ConditionalRenderer + accessor]: rendererKey(renderer) });
	} else _scope_id();
	return result;
};
function _content(id, fn, scopeId) {
	fn["id"] = id;
	fn[Owner] = scopeId;
	return fn;
}
function _content_resume(id, fn, scopeId, locals) {
	return _resume(_content(id, fn, scopeId), id, scopeId, locals);
}
const patchDynamicTag = /* @__PURE__ */ ((originalDynamicTag) => (patch) => {
	_dynamic_tag = (scopeId, accessor, tag, input, content, inputIsArgs, markerGuard, tagVar) => {
		const patched = patch(tag, scopeId, accessor);
		if (patched !== tag) patched["id"] = tag;
		return originalDynamicTag(scopeId, accessor, patched, input, content, inputIsArgs, markerGuard, tagVar);
	};
})(_dynamic_tag);
//#endregion
//#region src/html/template.ts
const CONSUMED_RESULT_MESSAGE = "Cannot read from a consumed render result";
const _template = (templateId, renderer, page) => {
	renderer.render = render;
	renderer[Embed] = !page;
	renderer._ = renderer;
	renderer.mount = () => {
		throw new Error(`mount() is not implemented for the HTML compilation of a Marko template`);
	};
	return _content_resume(templateId, renderer);
};
function render(input = {}) {
	return startRender(this, input, State);
}
function startRender(template, input, StateClass) {
	let { $global } = input;
	if ($global) {
		({$global, ...input} = input);
		$global = {
			runtimeId: "M",
			renderId: getDefaultRenderId(template),
			...$global
		};
		if (!String($global.runtimeId).match(/^[_a-z][_a-z0-9]*$/i)) throw new Error(`Invalid runtimeId: "${$global.runtimeId}". The runtimeId must start with a letter or underscore and only contain letters, numbers, and underscores.`);
		if (!String($global.renderId).match(/^[_a-z][_a-z0-9]*$/i)) throw new Error(`Invalid renderId: "${$global.renderId}". The renderId must start with a letter or underscore and only contain letters, numbers, and underscores.`);
	} else $global = {
		runtimeId: "M",
		renderId: getDefaultRenderId(template)
	};
	const state = new StateClass($global);
	const head = new Chunk(new Boundary(state, $global.signal), null, null, state);
	if (template["embed"]) head.render(() => writeWaitReady(template["id"], template, input));
	else head.render(template, input);
	return new ServerRendered(head);
}
function getDefaultRenderId(template) {
	if (template["embed"]) {
		const ENCODE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789";
		let n = Math.random() * 4294967296 >>> 0;
		let r = ENCODE_CHARS[n % 52];
		for (n = n / 52 | 0; n; n = n / 63 | 0) r += ENCODE_CHARS[n % 63];
		return r;
	}
	return "_";
}
var ServerRendered = class {
	#head;
	#cachedPromise = null;
	constructor(head) {
		this.#head = head;
	}
	[Symbol.asyncIterator]() {
		let resolve;
		let reject;
		let value = "";
		let done = false;
		let aborted = false;
		let reason;
		const boundary = this.#read((html) => {
			value += html;
			if (resolve) {
				const settle = resolve;
				resolve = reject = void 0;
				settle({
					value,
					done
				});
				value = "";
			}
		}, (err) => {
			aborted = true;
			reason = err;
			if (reject) {
				const settle = reject;
				resolve = reject = void 0;
				settle(err);
			}
		}, () => {
			done = true;
			if (resolve) {
				const settle = resolve;
				resolve = reject = void 0;
				settle({
					value,
					done: !value
				});
				value = "";
			}
		});
		return {
			next() {
				if (aborted) return Promise.reject(reason);
				else if (value) {
					const result = {
						value,
						done: false
					};
					value = "";
					return Promise.resolve(result);
				} else if (done) return Promise.resolve({
					value: "",
					done
				});
				else return new Promise(exec);
			},
			throw(error) {
				if (!(done || aborted)) boundary?.abort(error);
				return Promise.resolve({
					value: "",
					done: true
				});
			},
			return(value) {
				if (!(done || aborted)) boundary?.abort(/* @__PURE__ */ new Error("Iterator returned before consumed."));
				return Promise.resolve({
					value,
					done: true
				});
			}
		};
		function exec(_resolve, _reject) {
			resolve = _resolve;
			reject = _reject;
		}
	}
	pipe(stream) {
		this.#read((html) => {
			stream.write(html);
			stream.flush?.();
		}, (err) => {
			const socket = "socket" in stream && stream.socket;
			if (socket && typeof socket.destroySoon === "function") socket.destroySoon();
			else if (stream.destroy) stream.destroy();
			else stream.end();
			if (!stream.emit?.("error", err)) throw err;
		}, () => {
			stream.end();
		});
	}
	toReadable() {
		let cancelled = false;
		let started = false;
		let boundary;
		const encoder = new TextEncoder();
		return new ReadableStream({
			pull: (ctrl) => {
				if (started) return;
				started = true;
				boundary = this.#read((html) => {
					ctrl.enqueue(encoder.encode(html));
				}, (err) => {
					boundary = void 0;
					if (!cancelled) ctrl.error(err);
				}, () => {
					boundary = void 0;
					ctrl.close();
				});
			},
			cancel: (reason) => {
				cancelled = true;
				boundary?.abort(reason);
			}
		}, { highWaterMark: 0 });
	}
	then(onfulfilled, onrejected) {
		return this.#promise().then(onfulfilled, onrejected);
	}
	catch(onrejected) {
		return this.#promise().catch(onrejected);
	}
	finally(onfinally) {
		return this.#promise().finally(onfinally);
	}
	#promise() {
		return this.#cachedPromise ||= new Promise((resolve, reject) => {
			let head = this.#head;
			this.#head = null;
			if (!head) return reject(/* @__PURE__ */ new Error(CONSUMED_RESULT_MESSAGE));
			const { boundary } = head;
			let html = "";
			(boundary.onNext = () => {
				switch (!boundary.count && boundary.flush()) {
					case 2:
						settle(boundary);
						reject(boundary.reason);
						break;
					case 0:
						head = head.consume(boundary);
						if (boundary.aborted) break;
						html += head.flushHTML(boundary);
						if (!(boundary.count || boundary.aborted)) {
							settle(boundary);
							resolve(html);
						}
				}
			})();
		});
	}
	#read(onWrite, onAbort, onClose) {
		let tick = true;
		let flushing = false;
		let again = false;
		let head = this.#head;
		this.#head = null;
		if (!head) {
			onAbort(/* @__PURE__ */ new Error(CONSUMED_RESULT_MESSAGE));
			return;
		}
		const { boundary } = head;
		const onNext = boundary.onNext = (write) => {
			if (flushing) {
				again = true;
				return;
			}
			flushing = true;
			do {
				again = false;
				const status = boundary.flush();
				if (status === 2) {
					if (!tick) offTick(onNext);
					settle(boundary);
					onAbort(boundary.reason);
					return;
				}
				if (write || status === 0) {
					head = head.consume(boundary);
					if (boundary.aborted) continue;
					const html = head.flushHTML(boundary);
					if (boundary.aborted) continue;
					if (html) onWrite(html);
					if (!boundary.count) {
						if (!tick) offTick(onNext);
						settle(boundary);
						onClose();
						return;
					}
					if (write) tick = true;
				} else if (tick) {
					tick = false;
					queueTick(onNext);
				}
			} while (again);
			flushing = false;
		};
		onNext();
		return boundary;
	}
	toString() {
		const head = this.#head;
		this.#head = null;
		if (!head) throw new Error(CONSUMED_RESULT_MESSAGE);
		const { boundary } = head;
		const html = boundary.flush() === 0 ? head.consume(boundary).flushHTML(boundary) : "";
		if (boundary.count) boundary.abort(/* @__PURE__ */ new Error("Cannot consume asynchronous render with 'toString'"));
		settle(boundary);
		if (boundary.aborted) throw boundary.reason;
		return html;
	}
};
function settle(boundary) {
	boundary.onNext = NOOP$1;
	boundary.state.$global.signal?.removeEventListener("abort", boundary);
}
function NOOP$1() {}
//#endregion
//#region src/html/assets.ts
const kAssets = Symbol();
const kHead = Symbol();
function withLoadAssets(renderer, flush, assetId, triggers) {
	return register(renderer["id"], Object.assign((input) => {
		writeLoadAsset(assetId, flush, triggers);
		return writeWaitReady(assetId, renderer, input);
	}, {
		...renderer,
		[Lazy]: 1
	}));
}
function writeLoadAsset(assetId, flush, triggers) {
	const g = $global();
	writeAsset(g, addAsset(g, assetId, flush, triggers));
}
function withPageAssets(template, flush, assetId, runtimeId) {
	return Object.assign((input) => {
		const g = $global();
		if (runtimeId) {
			if (!g[kAssets]) {
				if (g.runtimeId !== "M" && g.runtimeId !== runtimeId) throw new Error(`$global.runtimeId ("${g.runtimeId}") conflicts with the runtimeId this entry was compiled with ("${runtimeId}").`);
				g.runtimeId = runtimeId;
			} else if (g.runtimeId !== runtimeId) console.error(`A page entry compiled with runtimeId "${runtimeId}" is nested in a render using runtimeId "${g.runtimeId}", so its content cannot resume.`);
		}
		const asset = addAsset(g, assetId, flush);
		if (g.__flush__) {
			writeAsset(g, asset);
			return writeWaitReady(assetId, template, input);
		}
		g.__flush__ = flushPage;
		return template(input);
	}, template);
}
function _flush_head() {
	const g = $global();
	if (!g[kAssets]) return "";
	g[kHead] = true;
	return takeAssets(g, catchableBoundary());
}
function flushPage(g, html) {
	return takeAssets(g, null) + html;
}
function takeAssets(g, at) {
	let block = "";
	let defer = "";
	for (const asset of g[kAssets]) if (asset.htmlAt === void 0) {
		asset.htmlAt = at;
		block += blockHTML(g, asset);
		if (!asset.triggers) defer += deferHTML(g, asset);
	}
	return block + defer;
}
function writeAsset(g, asset) {
	if (needsWrite(asset.htmlAt)) {
		asset.htmlAt = void 0;
		if (g[kHead] || g.__flush__ !== flushPage) {
			const block = blockHTML(g, asset);
			_html(block + (asset.triggers ? "" : deferHTML(g, asset)));
			if (block && isInResumedBranch()) writeScript(`document.head.insertAdjacentHTML("beforeend",${quoteScriptTemplateLiteral(block)})`);
			asset.htmlAt = catchableBoundary();
		}
	}
	if (asset.triggers && needsWrite(asset.scriptAt)) {
		const defer = deferHTML(g, asset);
		if (defer) writeScript(asset.script ||= triggerScript(asset.id, defer, asset.triggers));
		asset.scriptAt = catchableBoundary();
	}
}
function needsWrite(at) {
	return at === void 0 || at !== null && mayDrop(at);
}
function blockHTML(g, asset) {
	return asset.block ??= asset.flush(g, "block", asset.id);
}
function deferHTML(g, asset) {
	return asset.defer ??= asset.flush(g, "defer", asset.id);
}
function addAsset(g, id, flush, triggers) {
	const assets = g[kAssets] ||= [];
	let asset = assets.find((a) => a.id === id);
	if (!asset) assets.push(asset = {
		id,
		flush,
		triggers,
		block: void 0,
		defer: void 0,
		script: void 0,
		htmlAt: void 0,
		scriptAt: void 0
	});
	else if (JSON.stringify(asset.triggers) !== JSON.stringify(triggers)) console.error(`The lazy asset "${id}" is imported with different \`load\` triggers; an asset must use one consistent trigger.`);
	return asset;
}
function triggerScript(id, html, triggers) {
	const htmlStr = quoteScriptTemplateLiteral(html);
	const insert = `(d=new Range().createContextualFragment(h),d.querySelectorAll("script").forEach(s=>s.onerror=()=>console.error(${quoteScriptTemplateLiteral(`The lazy module for "${id}" failed to load; its server-rendered content cannot become interactive.`)})),document.head.append(d))`;
	const exprs = triggers.map((trigger) => {
		const options = trigger.options && toObjectExpression(trigger.options);
		switch (trigger.type) {
			case "visible": return `(e=>e&&new IntersectionObserver((e,i)=>e.some(e=>e.isIntersecting)&&i.disconnect()+l()${options ? `,${options}` : ""}).observe(e))(${querySelectorOrLoad(trigger.selector)})`;
			case "idle": return `(self.requestIdleCallback||l)(l${options ? `,${options}` : ""})`;
			case "media": return `(m=>m.matches?l():m.addEventListener("change",l,{once:1}))(matchMedia(${JSON.stringify(trigger.selector)}))`;
			default: return `(e=>e?.addEventListener("${trigger.type.slice(3)}",l,{once:1}))(${querySelectorOrLoad(trigger.selector)})`;
		}
	});
	return `((h,d,l=$=>{d||${insert}})=>${exprs.length > 1 ? `{${exprs.join(";")}}` : exprs[0]})(${htmlStr})`;
}
function querySelectorOrLoad(selector) {
	return `document.querySelector(${JSON.stringify(selector)})||${`(console.warn(${JSON.stringify(`A lazy load trigger could not find an element matching "${selector}". The module was loaded immediately.`)}),l())`}`;
}
function toObjectExpression(options) {
	let result = "{";
	let sep = "";
	for (const key in options) if (Object.hasOwn(options, key)) {
		result += sep + toObjectKey(key) + ":" + JSON.stringify(options[key]);
		sep = ",";
	}
	return result + "}";
}
//#endregion
//#region src/common/compat-meta.ts
const SET_SCOPE_REGISTER_ID = "$compat_setScope";
const RENDER_BODY_ID = "$compat_renderBody";
//#endregion
//#region src/common/for.ts
function forIn(obj, cb) {
	for (const key in obj) cb(key, obj[key]);
}
function forOf(list, cb) {
	assertValidList(list);
	if (list) {
		let i = 0;
		for (const item of list) cb(item, i++);
	}
}
function forTo(to, from, step, cb) {
	assertValidRangeBound("to", to);
	assertOptionalRangeNumber("from", from);
	assertOptionalRangeNumber("step", step);
	const start = from || 0;
	const delta = step || 1;
	for (let steps = (to - start) / delta, i = 0; i <= steps; i++) cb(start + i * delta);
}
function forUntil(until, from, step, cb) {
	assertValidRangeBound("until", until);
	assertOptionalRangeNumber("from", from);
	assertOptionalRangeNumber("step", step);
	const start = from || 0;
	const delta = step || 1;
	for (let steps = (until - start) / delta, i = 0; i < steps; i++) cb(start + i * delta);
}
//#endregion
//#region src/html/for.ts
function forOfBy(by, item, index) {
	return by ? typeof by === "string" ? item[by] : by(item, index) : index;
}
function forInBy(by, name, value) {
	return by ? by(name, value) : name;
}
function forStepBy(by, index) {
	return by ? by(index) : index;
}
//#endregion
//#region src/html/control-flow.ts
function _show_start(display, markerGuard, branchExprGuard, parentEndTag) {
	if (display) {
		if (resumesMarker(markerGuard, branchExprGuard, parentEndTag)) $chunk.writeHTML($chunk.boundary.state.mark("[", ""));
	} else $chunk.writeHTML("<t hidden>");
}
function _show_end(scopeId, accessor, display, markerGuard, branchExprGuard, parentEndTag, singleNode) {
	const branchId = _scope_id();
	const wrap = !display;
	if (wrap) $chunk.writeHTML("</t>");
	writeBranchEnd(scopeId, accessor, branchExprGuard, markerGuard, parentEndTag, wrap || singleNode ? 1 : void 0, " " + branchId);
}
function _for_of(list, cb, by, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
	forBranches(by, cb, iterateForOf(list, cb, by), scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode);
}
function iterateForOf(list, cb, by) {
	return (each) => each ? forOf(list, (item, index) => {
		const itemKey = forOfBy(by, item, index);
		each(itemKey, itemKey === index, item, index);
	}) : forOf(list, cb);
}
function _for_in(obj, cb, by, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
	forBranches(by, cb, iterateForIn(obj, cb, by), scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode);
}
function iterateForIn(obj, cb, by) {
	return (each) => each ? forIn(obj, (key, value) => {
		each(forInBy(by, key, value), false, key, value);
	}) : forIn(obj, cb);
}
function _for_to(to, from, step, cb, by, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
	forBranches(by, cb, iterateForTo(to, from, step, cb, by), scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode);
}
function iterateForTo(to, from, step, cb, by) {
	return (each) => {
		let index = 0;
		return each ? forTo(to, from, step, (value) => {
			const itemKey = forStepBy(by, value);
			each(itemKey, itemKey === index++, value);
		}) : forTo(to, from, step, cb);
	};
}
function _for_until(until, from, step, cb, by, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
	forBranches(by, cb, iterateForUntil(until, from, step, cb, by), scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode);
}
function iterateForUntil(until, from, step, cb, by) {
	return (each) => {
		let index = 0;
		return each ? forUntil(until, from, step, (value) => {
			const itemKey = forStepBy(by, value);
			each(itemKey, itemKey === index++, value);
		}) : forUntil(until, from, step, cb);
	};
}
function checkLoopKeys(cb, iterate) {
	const seenKeys = /* @__PURE__ */ new Set();
	return (each) => iterate((itemKey, sameAsIndex, a, b) => {
		assertValidLoopKey(itemKey, seenKeys);
		if (each) each(itemKey, sameAsIndex, a, b);
		else cb(a, b);
	});
}
function forBranches(by, cb, iterate, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
	if (by) iterate = checkLoopKeys(cb, iterate);
	if (branchGuard === 0) {
		iterate(0);
		writeBranchEnd(scopeId, accessor, branchExprGuard, markerGuard, parentEndTag, singleNode, "");
		return;
	}
	const { state } = $chunk.boundary;
	const resumeKeys = markerGuard !== 0;
	const resumeMarker = resumesMarker(markerGuard, branchExprGuard, parentEndTag);
	let flushBranchIds = "";
	let loopScopes;
	iterate((itemKey, sameAsIndex, a, b) => {
		const branchId = _peek_scope_id();
		if (resumeMarker) {
			if (singleNode) flushBranchIds = " " + branchId + flushBranchIds;
			else {
				$chunk.writeHTML(state.mark("[", flushBranchIds));
				flushBranchIds = branchId + "";
			}
		}
		withBranchId(branchId, cb, a, b);
		const branchScope = writeScope(branchId, resumeKeys && !sameAsIndex ? { [LoopKey]: itemKey } : {});
		if (!resumeMarker) loopScopes = push(loopScopes, branchScope);
	});
	if (loopScopes) writeScope(scopeId, { [BranchScopes + accessor]: loopScopes });
	writeBranchEnd(scopeId, accessor, branchExprGuard, markerGuard, parentEndTag, singleNode, singleNode ? flushBranchIds : flushBranchIds ? " " + flushBranchIds : "");
}
function _if(cb, scopeId, accessor, branchGuard, markerGuard, branchExprGuard, parentEndTag, singleNode) {
	const resumeBranch = branchGuard !== 0;
	const resumeMarker = resumesMarker(markerGuard, branchExprGuard, parentEndTag);
	const branchId = _peek_scope_id();
	const chunk = $chunk;
	const beforeBranch = resumeMarker && resumeBranch && !singleNode ? deferBranchStart(chunk) : void 0;
	const branchIndex = resumeBranch ? withBranchId(branchId, cb) : cb();
	const shouldWriteBranch = resumeBranch && branchIndex !== void 0;
	if (beforeBranch !== void 0) applyBranchStart(chunk, beforeBranch, shouldWriteBranch);
	if (shouldWriteBranch && (branchIndex || !resumeMarker)) writeScope(scopeId, {
		[ConditionalRenderer + accessor]: branchIndex || void 0,
		[BranchScopes + accessor]: resumeMarker ? void 0 : writeScope(branchId, {})
	});
	writeBranchEnd(scopeId, accessor, branchExprGuard, markerGuard, parentEndTag, singleNode, shouldWriteBranch ? " " + branchId : "");
}
function resumesMarker(markerGuard, branchExprGuard, parentEndTag) {
	return markerGuard !== 0 && (!parentEndTag || branchExprGuard !== 0);
}
function writeBranchEnd(scopeId, accessor, branchExprGuard, markerGuard, parentEndTag, singleNode, branchIds) {
	const endTag = parentEndTag || "";
	if (resumesMarker(markerGuard, branchExprGuard, parentEndTag)) {
		const { state } = $chunk.boundary;
		const mark = singleNode ? state.mark(parentEndTag ? "}" : "|", scopeId + " " + accessor + (branchIds || "")) : state.mark(parentEndTag ? ")" : "]", scopeId + " " + accessor + (branchIds || ""));
		$chunk.writeHTML(mark + endTag);
	} else if (markerGuard !== 0) $chunk.writeHTML(endTag + _el_resume(scopeId, accessor));
	else $chunk.writeHTML(endTag);
}
function _await(scopeId, accessor, promise, content, markerGuard) {
	const resumeMarker = markerGuard !== 0;
	if (!isPromise(promise)) {
		if (resumeMarker) {
			const branchId = _peek_scope_id();
			$chunk.writeHTML($chunk.boundary.state.mark("[", ""));
			withBranchId(branchId, content, promise);
			$chunk.writeHTML($chunk.boundary.state.mark("]", scopeId + " " + accessor + " " + branchId));
		} else content(promise);
		return;
	}
	const chunk = $chunk;
	const { boundary } = chunk;
	const startId = _peek_scope_id();
	const after = chunk.next = chunk.forkRest(boundary);
	chunk.async = true;
	captureContext(chunk);
	boundary.startAsync();
	promise.then((value) => {
		if (chunk.async) {
			chunk.async = false;
			if (!boundary.aborted) {
				const { state } = boundary;
				chunk.render(() => {
					if (resumeMarker) {
						const branchId = _peek_scope_id();
						$chunk.writeHTML($chunk.boundary.state.mark("[", ""));
						withBranchId(branchId, () => withAsyncContent({ parent: getAsyncContent(chunk) }, content, value));
						$chunk.writeHTML($chunk.boundary.state.mark("]", scopeId + " " + accessor + " " + branchId));
					} else {
						const renderedSince = _peek_scope_id() !== startId;
						const async = { parent: getAsyncContent(chunk) };
						withAsyncContent(async, content, value);
						async.visit = renderedSince && (after.html || after.next) ? $chunk.boundary.state.mark("]", scopeId + " " + accessor) : "";
						if (async.resumed) $chunk.writeHTML(async.visit);
						async.end = $chunk;
					}
				});
				if (!chunk.async && boundary.pendingReorders?.delete(chunk)) state.reorder(chunk);
				boundary.endAsync();
			}
		}
	}, (err) => {
		chunk.async = false;
		boundary.abort(err);
	});
}
function _try(scopeId, accessor, content, placeholderContent, catchContent, placeholderId, catchId) {
	const placeholderBranchId = placeholderContent ? _scope_id() : 0;
	const branchId = _peek_scope_id();
	const chunk = $chunk;
	const { boundary } = chunk;
	const { state } = boundary;
	const { resumeWrites } = boundary;
	const beforeBranch = deferBranchStart(chunk);
	const renderers = () => writeTryRenderers(branchId, catchContent && _resume(catchContent, catchId), placeholderContent && _resume(placeholderContent, placeholderId));
	const writesRenderers = tryBoundary(placeholderContent ? () => tryPlaceholder(content, placeholderContent, branchId, scopeId, placeholderBranchId) : content, catchContent, branchId, renderers);
	const keepsMarks = state.keepsTryMarks(chunk, resumeWrites);
	applyBranchStart(chunk, beforeBranch, keepsMarks);
	if (!keepsMarks) return;
	if (!writesRenderers) renderers();
	$chunk.writeHTML(state.mark("]", scopeId + " " + accessor + " " + branchId));
}
function tryPlaceholder(content, placeholder, branchId, scopeId, placeholderBranchId) {
	const chunk = $chunk;
	const { boundary } = chunk;
	const body = chunk.fork(boundary, null);
	if (body === body.render(content)) {
		chunk.append(body);
		return;
	}
	chunk.next = chunk.forkRest(boundary);
	captureContext(chunk);
	chunk.placeholder = {
		body,
		render: placeholder,
		branchId,
		scopeId,
		placeholderBranchId
	};
}
function tryBoundary(content, catchContent, branchId, renderers) {
	const chunk = $chunk;
	const { boundary } = chunk;
	const { state } = boundary;
	const bodyBoundary = new Boundary(state, void 0, boundary);
	if (catchContent) bodyBoundary.withinCatch = true;
	const body = chunk.fork(bodyBoundary, null);
	const bodyEnd = body.render(withBranchId, branchId, content);
	if (bodyBoundary.aborted) {
		if (!catchContent) throw bodyBoundary.reason;
		catchContent(bodyBoundary.reason);
		return true;
	}
	if (body === bodyEnd) {
		chunk.append(body);
		return false;
	}
	const renderersAtSettle = !bodyBoundary.resumeWrites;
	const bodyNext = bodyEnd.next = chunk.forkRest(boundary);
	chunk.next = body;
	boundary.startAsync();
	const reorderId = catchContent ? state.nextReorderId() : "";
	if (reorderId) {
		chunk.catchRange = {
			id: reorderId,
			end: bodyEnd
		};
		captureContext(chunk);
	}
	bodyBoundary.onNext = () => {
		if (boundary.aborted) return;
		if (bodyBoundary.aborted) {
			if (!reorderId) {
				boundary.abort(bodyBoundary.reason);
				return;
			}
			const streamed = !chunk.catchRange;
			const catchChunk = chunk.fork(boundary, null);
			chunk.catchRange = null;
			if (!renderersAtSettle) catchChunk.render(clearTryRenderers, branchId);
			const inOrder = catchChunk === catchChunk.render(catchContent, bodyBoundary.reason);
			if (boundary.aborted) return;
			if (bodyEnd.consumed || !inOrder) catchChunk.reorderBranch = branchId;
			if (bodyEnd.consumed) {
				catchChunk.reorderId = reorderId;
				state.reorder(catchChunk);
			} else {
				let reorder = null;
				if (!inOrder) reorder = catchChunk;
				else if (streamed) reorder = chunk.fork(boundary, null);
				if (reorder) reorder.reorderId = reorderId;
				const endMarker = state.mark("!", reorderId);
				let cut = body;
				while (cut.consumed) cut = cut.next;
				cut.async = false;
				cut.next = inOrder ? catchChunk : bodyNext;
				cut.html = streamed ? endMarker : inOrder ? "" : state.mark("!^", reorderId) + endMarker;
				cut.scripts = cut.effects = cut.lastEffect = "";
				cut.placeholder = cut.reorderId = cut.catchRange = null;
				cut.deferredReorder = reorder;
				if (inOrder) catchChunk.next = bodyNext;
			}
			boundary.endAsync();
		} else if (!bodyBoundary.count) {
			if (renderersAtSettle && bodyBoundary.resumeWrites) bodyEnd.render(renderers);
			chunk.catchRange = null;
			boundary.endAsync();
		} else boundary.onNext();
	};
	return renderersAtSettle;
}
function clearTryRenderers(branchId) {
	writeScope(branchId, {
		[CatchContent]: 0,
		[PlaceholderContent]: _scope_with_id(branchId)["#PlaceholderContent"] && 0
	});
}
function writeTryRenderers(branchId, catchContent, placeholderContent) {
	writeScope(branchId, {
		[CatchContent]: catchContent,
		[PlaceholderContent]: placeholderContent
	});
}
//#endregion
//#region src/html/compat.ts
const K_TAGS_API_STATE = Symbol();
const COMPAT_REGISTRY = /* @__PURE__ */ new WeakMap();
const compat = {
	$global,
	writeLoadAsset,
	fork: _await,
	write: _html,
	writeScript,
	nextScopeId: _scope_id,
	peekNextScopeId: _peek_scope_id,
	isInResumedBranch,
	withChunk,
	getChunk,
	ensureState($global) {
		let state = $global[K_TAGS_API_STATE] ||= getChunk()?.boundary.state;
		if (!state) {
			$global.runtimeId ||= "M";
			$global.renderId ||= $global.componentIdPrefix || $global.widgetIdPrefix || "_";
			$global[K_TAGS_API_STATE] = state = new State($global);
		}
		return state;
	},
	isTagsAPI(fn) {
		return !!fn["id"];
	},
	onFlush(fn) {
		const { flushHTML } = Chunk.prototype;
		Chunk.prototype.flushHTML = function(boundary) {
			const { state } = boundary;
			const reorders = swapReorders(state, null);
			fn(this);
			swapReorders(state, reorders);
			return flushHTML.call(this, boundary);
		};
	},
	patchDynamicTag,
	writeSetScopeForComponent(branchId, m5c, m5i) {
		writeScope(branchId, {
			m5c,
			m5i
		});
		_script(branchId, SET_SCOPE_REGISTER_ID);
	},
	toJSON() {
		return function toJSON() {
			let compatRegistered = COMPAT_REGISTRY.get(this);
			if (!compatRegistered) {
				const registered = REGISTRY.get(this);
				if (registered) {
					const scopeId = registered.scope ? getScopeId(registered.scope) : void 0;
					if (scopeId !== void 0) _script(scopeId, SET_SCOPE_REGISTER_ID);
					COMPAT_REGISTRY.set(this, compatRegistered = [registered.id, scopeId]);
				}
			}
			return compatRegistered;
		};
	},
	joinChunks(chunks) {
		let joined;
		for (const chunk of chunks) {
			if (chunk.boundary.aborted) continue;
			if (joined) joined.append(chunk);
			else joined = chunk;
		}
		return joined;
	},
	appendChunks(chunks) {
		const chunk = getChunk();
		for (const part of chunks) {
			chunk.append(part);
			if (part.effects) chunk.lastEffect = part.lastEffect;
		}
	},
	deferReorders(reorders) {
		const chunk = getChunk();
		for (let i = reorders.length; i--;) {
			const carrier = chunk.fork(chunk.boundary, chunk.next);
			carrier.deferredReorder = reorders[i];
			chunk.next = carrier;
		}
	},
	createChunk($global) {
		const state = this.ensureState($global);
		return new Chunk(new Boundary(state), null, null, state);
	},
	flushScript(chunk, reorders) {
		const { boundary } = chunk;
		const { state } = boundary;
		let html = "";
		let scripts = "";
		if (reorders) for (const reorder of reorders) state.reorder(reorder);
		if (boundary.flush() === 0) ({html, scripts} = chunk.flush(boundary));
		if (boundary.aborted) throw boundary.reason;
		if (boundary.count) throw new Error("Cannot serialize promise across tags/class compat layer.");
		return {
			html,
			scripts
		};
	},
	render(renderer, willRerender, classAPIOut, component, input, componentScopes, registerChildScope, parentChunk) {
		if (parentChunk?.boundary.aborted) return;
		const state = this.ensureState(classAPIOut.global);
		const boundary = new Boundary(state, void 0, parentChunk?.boundary);
		const context = getChunk()?.context ?? null;
		let head = new Chunk(boundary, new Chunk(boundary, null, context, state), context, state);
		let normalizedInput = input;
		if ("renderBody" in input) {
			normalizedInput = {};
			for (const key in input) normalizedInput[key === "renderBody" ? "content" : key] = input[key];
		}
		const componentScope = new Chunk(boundary, null, context, state);
		componentScope.render(() => {
			if (this.hasPendingClassFunctions(classAPIOut.global)) drainClassFunctions(classAPIOut.global, (hostId) => {
				const fnScopeId = _scope_id();
				const scope = writeScope(fnScopeId, {
					m5c: component.id,
					m5h: hostId
				});
				_script(fnScopeId, SET_SCOPE_REGISTER_ID);
				return scope;
			});
			if (willRerender || registerChildScope) {
				const scopeId = _peek_scope_id();
				writeScope(scopeId, { m5c: component.id });
				_script(scopeId, SET_SCOPE_REGISTER_ID);
			}
		});
		head.render(() => {
			_set_scope_reason(willRerender ? ALL_GROUPS : 0);
			try {
				renderer(normalizedInput);
			} finally {
				_set_scope_reason(void 0);
			}
			const asyncOut = classAPIOut.beginAsync({
				last: true,
				timeout: -1
			});
			classAPIOut.onLast((next) => {
				(boundary.onNext = () => {
					if (boundary.aborted) {
						boundary.onNext = NOOP;
						if (parentChunk?.boundary.aborted) {
							asyncOut.end();
							next();
						} else asyncOut.error(boundary.reason);
					} else if (!boundary.count) {
						boundary.onNext = NOOP;
						const queued = swapReorders(state, null);
						head = head.consume(boundary);
						const reorders = swapReorders(state, queued);
						if (reorders) asyncOut.writer.get("reorders").push(...reorders);
						const heldEffects = head.takeHeldEffects();
						if (heldEffects) {
							head.effects = joinHeldEffects(heldEffects, head.effects);
							head.lastEffect = "";
						}
						asyncOut.write(head.html);
						asyncOut.script(head.scripts);
						head.html = head.scripts = "";
						asyncOut.writer.get("chunks").push(head);
						asyncOut.end();
						componentScopes.push(componentScope);
						next();
					}
				})();
			});
		});
	},
	register,
	registerRenderBody(fn) {
		register(RENDER_BODY_ID, fn);
	},
	registerClassFunctions(input) {
		for (const key in input) {
			const value = input[key];
			if (typeof value === "function" && !REGISTRY.has(value)) register(RENDER_BODY_ID, value);
		}
	},
	registerClassFunction($global, id, fn, hostId) {
		let pending = pendingClassFunctions.get($global);
		if (!pending) pendingClassFunctions.set($global, pending = []);
		pending.push([
			id,
			fn,
			hostId
		]);
		return fn;
	},
	hasPendingClassFunctions($global) {
		return !!pendingClassFunctions.get($global)?.length;
	}
};
const pendingClassFunctions = /* @__PURE__ */ new WeakMap();
function drainClassFunctions($global, writeScope) {
	const pending = pendingClassFunctions.get($global);
	const scopeByHost = {};
	for (const [id, fn, hostId] of pending) register(id, fn, scopeByHost[hostId] ||= writeScope(hostId));
	pending.length = 0;
}
function swapReorders(state, reorders) {
	const { writeReorders } = state;
	state.writeReorders = reorders;
	return writeReorders;
}
function NOOP() {}
//#endregion
export { $global, _assert_class_toggles, _assert_hoist, _attr, _attr_and, _attr_class, _attr_content, _attr_details_or_dialog_open as _attr_details_open, _attr_details_or_dialog_open as _attr_dialog_open, _attr_input_checked, _attr_input_checkedValue, _attr_input_value, _attr_nonce, _attr_nullish, _attr_option_value, _attr_or, _attr_select_value, _attr_style, _attr_textarea_value, _attrs, _attrs_content, _attrs_partial, _attrs_partial_content, _attrs_select_value, _attrs_textarea_value, _await, _content, _content_resume, _dynamic_tag, _el, _el_read_error, _el_resume, _escape, _escape_comment, _escape_script, _escape_style, _escape_style_value, _existing_scope, _flush_head, _for_in, _for_of, _for_to, _for_until, _hoist, _hoist_read_error, _html, _html_resume, _id, _if, _peek_scope_id, _resume, _resume_branch, _resume_locals, writeScope as _scope, _scope_id, _scope_reason, _scope_with_id, _script, _set_scope_reason, _show_end, _show_start, _style_html, _subscribe, _template, _text_resume, _textarea_value, _to_text, _trailers, _try, _unescaped, _var, _write_guard, _write_if, attrTag, attrTags, compat, forIn, forOf, forTo, forUntil, withLoadAssets, withPageAssets };