marko
Version:
Optimized runtime for Marko templates.
2,280 lines • 106 kB
JavaScript
let empty = [], rest = Symbol(), unsafeStyleAttrReg = /[\\;]/g, replaceUnsafeStyleAttr = (c) => c === ";" ? "\\3B " : "\\\\", toDelimitedString = function toDelimitedString(val, delimiter, stringify) {
let str = "", sep = "", part;
if (val) if (typeof val != "object") str += val;
else if (Array.isArray(val)) for (let v of val) part = toDelimitedString(v, delimiter, stringify), part && (str += sep + part, sep = delimiter);
else for (let name in val) part = stringify(name, val[name]), part && (str += sep + part, sep = delimiter);
return str;
}, unsafeXMLReg = /[<&\r]/g, replaceUnsafeXML = (c) => c === "&" ? "&" : c === "<" ? "<" : " ", escapeXMLStr = (str) => unsafeXMLReg.test(str) ? str.replace(unsafeXMLReg, replaceUnsafeXML) : str, unsafeScriptReg = /<(\/?script|!--)/gi, escapeScriptStr = (str) => unsafeScriptReg.test(str) ? str.replace(unsafeScriptReg, "\\x3C$1") : str, unsafeStyleReg = /<(\/style)/gi, escapeStyleStr = (str) => unsafeStyleReg.test(str) ? str.replace(unsafeStyleReg, "\\3C$1") : str, unsafeCommentReg = />/g, escapeCommentStr = (str) => unsafeCommentReg.test(str) ? str.replace(unsafeCommentReg, ">") : str, K_SCOPE_ID = Symbol("Scope ID"), kTouchedIterator = /* @__PURE__ */ Symbol.for("marko.touchedIterator"), { hasOwnProperty } = {}, objectProto = Object.prototype, arrayProto = Array.prototype, Generator = (/* @__PURE__ */ (function* () {})()).constructor, AsyncGenerator = (/* @__PURE__ */ (async function* () {})()).constructor, REGISTRY = /* @__PURE__ */ new WeakMap(), KNOWN_SYMBOLS = /* @__PURE__ */ (() => {
let KNOWN_SYMBOLS = /* @__PURE__ */ new Map();
for (let name of Object.getOwnPropertyNames(Symbol)) {
let symbol = Symbol[name];
typeof symbol == "symbol" && KNOWN_SYMBOLS.set(symbol, "Symbol." + name);
}
return KNOWN_SYMBOLS;
})(), KNOWN_FUNCTIONS = /* @__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.clearImmediate, "clearImmediate"],
[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.setImmediate, "setImmediate"],
[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"]
]), KNOWN_OBJECTS = /* @__PURE__ */ new Map([
[Atomics, "Atomics"],
[console, "console"],
[globalThis, "globalThis"],
[globalThis.crypto, "crypto"],
[Intl, "Intl"],
[JSON, "JSON"],
[Math, "Math"],
[Reflect, "Reflect"]
]), unsafeRegExpSourceReg = /\\[\s\S]|[<\0\ud800-\udfff]/gu, unsafeRegExpSourceDetect = /[<\0\ud800-\udfff]/u, replaceUnsafeRegExpSourceChar = (match) => {
let ch = match.length === 3 ? "" : match[match.length - 1];
if (ch === "<") return "\\x3C";
if (ch === "\0") return "\\x00";
let code = ch.charCodeAt(0);
return code >= 55296 && code <= 57343 ? "\\u" + code.toString(16).padStart(4, "0") : match;
}, unsafeQuoteReg = /["\\<\n\r\u2028\u2029\0\ud800-\udfff]/u, $chunk, kPendingContexts = Symbol("Pending Contexts"), kBranchId = Symbol("Branch Id"), kIsAsync = Symbol("Is Async"), writeScope = (scopeId, partialScope) => {
let { state } = $chunk.boundary, target = $chunk.serializeState, scope = scopeWithId(state, scopeId), pending = target.writeScopes[scopeId];
return state.needsMainRuntime = !0, countResumeWrite($chunk.boundary), Object.assign(scope, partialScope), pending && pending !== partialScope ? Object.assign(pending, partialScope) : target.writeScopes[scopeId] = partialScope, target.flushScopes = !0, scope;
}, NOOP$2 = () => {}, tick = globalThis.setImmediate || globalThis.setTimeout || globalThis.queueMicrotask || ((cb) => Promise.resolve().then(cb)), tickQueue, kSelectedValue = Symbol("selectedValue"), checkedValuesRefs = /* @__PURE__ */ new WeakMap(), singleQuoteAttrReplacements = /['\r]|&(?=[#a-zA-Z])/g, doubleQuoteAttrReplacements = /["\r]|&(?=[#a-zA-Z])/g, needsQuotedAttr = /["'>\s]|&[#a-zA-Z]|\/$/g, voidElementsReg = /^(?:area|b(?:ase|r)|col|embed|hr|i(?:mg|nput)|link|meta|param|source|track|wbr)$/, _dynamic_tag = (scopeId, accessor, tag, inputOrArgs, content, inputIsArgs, serializeReason) => {
let shouldResume = serializeReason !== 0, renderer = normalizeDynamicRenderer(tag), state = getState(), branchId = _peek_scope_id(), rendered, result;
if (typeof renderer == "string") {
let input = (inputIsArgs ? inputOrArgs[0] : inputOrArgs) || {};
rendered = !0, (() => {
if (_scope_id(), _html(`<${renderer}${_attrs(input, "a", branchId, renderer)}>`), !voidElementsReg.test(renderer)) {
let renderContent = content || normalizeDynamicRenderer(input.content);
if (renderer === "textarea") _html(_attr_textarea_value(branchId, "a", input.value, input.valueChange, 1));
else {
if (renderContent && typeof renderContent != "function") throw Error(`Body content is not supported for the \`<${renderer}>\` tag.`);
renderer === "select" && ("value" in input || "valueChange" in input) ? _attr_select_value(branchId, "a", input.value, input.valueChange, renderContent ? () => _dynamic_tag(branchId, "a", renderContent, void 0, 0, void 0, serializeReason) : void 0, 1) : renderContent && _dynamic_tag(branchId, "a", renderContent, void 0, 0, void 0, serializeReason);
}
_html(`</${renderer}>`);
}
let childScope = getScopeById(branchId), needsScript = childScope && (childScope.Ia || childScope.Ea);
needsScript && _script(branchId, "_d"), (shouldResume || needsScript) && _html(state.mark("(", scopeId + " " + accessor + " " + branchId));
})(), result = _el(branchId, "_e");
} else {
let chunk = getChunk(), beforeBranch = shouldResume ? deferBranchStart(chunk) : void 0, render = () => {
if (renderer) try {
return _set_serialize_reason(shouldResume && inputOrArgs !== void 0 ? 1 : 0), inputIsArgs ? renderer(...inputOrArgs) : renderer(content ? {
...inputOrArgs,
content
} : inputOrArgs);
} finally {
_set_serialize_reason(void 0);
}
else if (content) return content();
};
result = shouldResume ? withBranchId(branchId, render) : render(), rendered = _peek_scope_id() !== branchId, beforeBranch !== void 0 && (applyBranchStart(chunk, beforeBranch, rendered), _html(state.mark("]", scopeId + " " + accessor + (rendered ? " " + branchId : ""))));
}
return rendered ? shouldResume && writeScope(scopeId, { ["D" + accessor]: rendererKey(renderer) }) : _scope_id(), result;
}, patchDynamicTag = /* @__PURE__ */ ((originalDynamicTag) => (patch) => {
_dynamic_tag = (scopeId, accessor, tag, input, content, inputIsArgs, resume) => {
let patched = patch(tag, scopeId, accessor);
return patched !== tag && (patched.a = tag), originalDynamicTag(scopeId, accessor, patched, input, content, inputIsArgs, resume);
};
})(_dynamic_tag), CONSUMED_RESULT_MESSAGE = "Cannot read from a consumed render result", _template = (templateId, renderer, page) => (renderer.render = render, renderer.i = !page, renderer._ = renderer, _content_resume(templateId, renderer)), kAssets = Symbol(), kBlockIndex = Symbol(), kDeferIndex = Symbol(), assetFlush, SET_SCOPE_REGISTER_ID = "$C_s", RENDER_BODY_ID = "$C_b", K_TAGS_API_STATE = Symbol(), COMPAT_REGISTRY = /* @__PURE__ */ new WeakMap(), compat = {
$global,
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;
return state || ($global.runtimeId ||= "M", $global.renderId ||= $global.componentIdPrefix || $global.widgetIdPrefix || "_", $global[K_TAGS_API_STATE] = state = new State($global)), state;
},
isTagsAPI(fn) {
return !!fn.a;
},
onFlush(fn) {
let { flushHTML } = Chunk.prototype;
Chunk.prototype.flushHTML = function() {
return fn(this), flushHTML.call(this);
};
},
patchDynamicTag,
writeSetScopeForComponent(branchId, m5c, m5i) {
writeScope(branchId, {
m5c,
m5i
}), _script(branchId, SET_SCOPE_REGISTER_ID);
},
toJSON() {
return function() {
let compatRegistered = COMPAT_REGISTRY.get(this);
if (!compatRegistered) {
let registered = getRegistered(this);
if (registered) {
let scopeId = registered.scope ? getScopeId(registered.scope) : void 0;
scopeId !== void 0 && _script(scopeId, SET_SCOPE_REGISTER_ID), COMPAT_REGISTRY.set(this, compatRegistered = [registered.id, scopeId]);
}
}
return compatRegistered;
};
},
createChunk($global) {
let state = this.ensureState($global);
return new Chunk(new Boundary(state), null, null, state);
},
flushScript($global, chunk) {
chunk ||= this.createChunk($global);
let { boundary } = chunk;
switch (boundary.flush()) {
case 2: throw boundary.signal.reason;
case 1: throw Error("Cannot serialize promise across tags/class compat layer.");
}
return chunk.flushScript().scripts;
},
render(renderer, willRerender, classAPIOut, component, input, completeChunks, registerChildScope) {
let state = this.ensureState(classAPIOut.global), boundary = new Boundary(state), head = new Chunk(boundary, null, getChunk()?.context ?? null, state), normalizedInput = input;
if ("renderBody" in input) {
normalizedInput = {};
for (let key in input) normalizedInput[key === "renderBody" ? "content" : key] = input[key];
}
head.render(() => {
if (this.hasPendingClassFunctions(classAPIOut.global) && drainClassFunctions(classAPIOut.global, (hostId) => {
let fnScopeId = _scope_id(), scope = writeScope(fnScopeId, {
m5c: component.id,
m5h: hostId
});
return _script(fnScopeId, SET_SCOPE_REGISTER_ID), scope;
}), willRerender || registerChildScope) {
let scopeId = _peek_scope_id();
writeScope(scopeId, { m5c: component.id }), _script(scopeId, SET_SCOPE_REGISTER_ID);
}
_set_serialize_reason(+!!willRerender);
try {
renderer(normalizedInput);
} finally {
_set_serialize_reason(void 0);
}
let asyncOut = classAPIOut.beginAsync({
last: !0,
timeout: -1
});
classAPIOut.onLast((next) => {
(boundary.onNext = () => {
boundary.signal.aborted ? (asyncOut.error(boundary.signal.reason), boundary.onNext = NOOP) : boundary.count || (boundary.onNext = NOOP, head = head.consume(), asyncOut.write(head.html), asyncOut.script(head.scripts), asyncOut.end(), head.html = head.scripts = "", completeChunks.push(head), next());
})();
});
});
},
register,
registerRenderBody(fn) {
register(RENDER_BODY_ID, fn);
},
registerClassFunctions(input) {
for (let key in input) {
let value = input[key];
typeof value == "function" && !getRegistered(value) && register(RENDER_BODY_ID, value);
}
},
registerClassFunction($global, id, fn, hostId) {
let pending = pendingClassFunctions.get($global);
return pending || pendingClassFunctions.set($global, pending = []), pending.push([
id,
fn,
hostId
]), fn;
},
hasPendingClassFunctions($global) {
return !!pendingClassFunctions.get($global)?.length;
}
}, pendingClassFunctions = /* @__PURE__ */ new WeakMap();
//#region src/common/attr-tag.ts
function attrTag(attrs) {
return attrs[Symbol.iterator] = attrTagIterator, attrs[rest] = empty, attrs;
}
function attrTags(first, attrs) {
return first ? (first[rest] === empty ? first[rest] = [attrs] : first[rest].push(attrs), first) : attrTag(attrs);
}
function* attrTagIterator() {
yield this, yield* this[rest];
}
//#endregion
//#region src/common/helpers.ts
function stringifyClassObject(name, value) {
return value ? name : "";
}
function stringifyStyleObject(name, value) {
return value || value === 0 ? escapeStyleAttr(name) + ":" + escapeStyleAttr(value + "") : "";
}
function escapeStyleAttr(str) {
return unsafeStyleAttrReg.test(str) ? str.replace(unsafeStyleAttrReg, replaceUnsafeStyleAttr) : str;
}
function escapeStyleValue(str) {
let closers = "", result = str.replace(/[\\"'{};<>]|\/(?=\*)/g, (c) => c === "<" ? "\\3C " : c === ";" ? "\\3B " : c === "{" ? "\\7B " : "\\" + c);
for (let c of result) c === "(" ? closers = ")" + closers : c === "[" ? closers = "]" + closers : c === closers[0] && (closers = closers.slice(1));
return result + closers;
}
function isEventHandler(name) {
return /^on[A-Z-]/.test(name);
}
function getEventHandlerName(name) {
return name[2] === "-" ? name.slice(3) : name.slice(2).toLowerCase();
}
function isVoid(value) {
return value == null || value === !1;
}
function isNotVoid(value) {
return value != null && value !== !1;
}
function isPromise(value) {
return value != null && typeof value.then == "function";
}
function normalizeDynamicRenderer(value) {
if (value) {
if (typeof value == "string") return value;
let normalized = value.content || value.default || value;
if ("a" in normalized) return normalized;
}
}
//#endregion
//#region src/common/errors.ts
function _el_read_error() {}
function _hoist_read_error() {}
function _assert_hoist(value) {}
//#endregion
//#region src/html/content.ts
function _to_text(val) {
return val || val === 0 ? val + "" : "";
}
function _unescaped(val) {
return val ? val + "" : val === 0 ? "0" : "";
}
function _escape(val) {
return val ? escapeXMLStr(val + "") : val === 0 ? "0" : "";
}
function _escape_script(val) {
return val ? escapeScriptStr(val + "") : val === 0 ? "0" : "";
}
function _escape_style(val) {
return val ? escapeStyleStr(val + "") : val === 0 ? "0" : "";
}
function _escape_style_value(val) {
return val || val === 0 ? escapeStyleValue(val + "") : "";
}
function _escape_comment(val) {
return val ? escapeCommentStr(val + "") : val === 0 ? "0" : "";
}
patchIteratorNext(Generator.prototype), patchIteratorNext(AsyncGenerator.prototype);
var State$1 = class {
ids = 0;
flushId = 0;
wroteUndefined = !1;
buf = [];
strs = /* @__PURE__ */ new Map();
refs = /* @__PURE__ */ new WeakMap();
pendingAssignments = /* @__PURE__ */ new Set();
boundary = void 0;
channel = void 0;
channelDeps = null;
mutated = [];
}, Reference = class {
assignments = null;
calls = null;
scopeId = void 0;
channel = void 0;
parent;
accessor;
flushId;
pos;
id;
constructor(parent, accessor, flushId, pos = null, id = null) {
this.parent = parent, this.accessor = accessor, this.flushId = flushId, this.pos = pos, this.id = id;
}
}, Serializer = class {
#state = new State$1();
pending(channel) {
return hasMatchingMutations(this.#state.mutated, channel?.readyId);
}
pendingReadyChannel() {
for (let mutation of this.#state.mutated) if (mutation.channel?.readyId) return mutation.channel;
}
stringifyScopes(flushes, boundary, channel) {
try {
return this.#state.boundary = boundary, this.#state.channel = channel, writeScopesRoot(this.#state, flushes);
} finally {
this.#state.flushId++, this.#state.buf = [];
}
}
written(val) {
return this.#state.refs.has(val);
}
takeChannelDeps() {
let deps = this.#state.channelDeps;
return this.#state.channelDeps = null, deps;
}
writeCall(value, object, property, channel) {
this.#state.mutated.push({
value,
object,
property,
channel
});
}
};
function register(id, val, scope) {
return REGISTRY.set(val, {
id,
scope,
access: "_._" + toAccess(toObjectKey(id))
}), val;
}
function getRegistered(val) {
let registered = REGISTRY.get(val);
if (registered) return {
id: registered.id,
scope: registered.scope
};
}
function writeScopesRoot(state, flushes) {
let { buf } = state, nextSlotId = -1, fillIndex = -1;
for (let flush of flushes) {
let scopeId = flush[0], scope = flush[1], ref = state.refs.get(scope) || newScopeReference(state, scope, scopeId), openIndex = buf.push("") - 1;
writeObjectProps(state, flush[2], ref) ? (buf[openIndex] = nextSlotId === -1 ? "[" + scopeId + ",{" : (scopeId === nextSlotId ? "" : "," + (scopeId - nextSlotId)) + ",{", fillIndex === -1 && (fillIndex = openIndex), nextSlotId = scopeId + 1, buf.push("}")) : buf.pop();
}
nextSlotId !== -1 && buf.push("]");
let extras = "";
(state.pendingAssignments.size || hasChannelMutations(state)) && (extras = ",0)", fillIndex !== -1 && (buf[fillIndex] = "_(" + buf[fillIndex], buf.push(")")), writeAssigned(state));
let result = extras && "(";
for (let chunk of buf) result += chunk;
return result += extras, result ? state.wroteUndefined ? (state.wroteUndefined = !1, "(_,$)=>" + result) : "_=>" + result : "";
}
function writeAssigned(state) {
let sep = state.buf.length ? "," : "";
if (state.pendingAssignments.size) {
let pending = state.pendingAssignments;
state.pendingAssignments = /* @__PURE__ */ new Set();
let buf = "", hasCalls = !1;
for (let ref of pending) ref.assignments && (buf += sep + assignmentsToString(ref.assignments, ref.id), ref.assignments = null, sep = ","), hasCalls ||= ref.calls !== null;
if (buf && state.buf.push(buf), hasCalls) {
for (let ref of pending) if (ref.calls) {
for (let { method, args } of ref.calls) {
state.buf.push((state.buf.length ? "," : "") + ref.id + "." + method + "(");
for (let a = 0; a < args.length; a++) a && state.buf.push(","), writeCallArg(state, args[a]);
state.buf.push(")");
}
ref.calls = null;
}
}
}
if (hasChannelMutations(state)) {
let remaining = [];
for (let mutation of state.mutated) {
if (!mutationMatchesReadyId(mutation, state.channel?.readyId)) {
remaining.push(mutation);
continue;
}
let hasSeen = state.refs.get(mutation.object)?.id, objectStartIndex = state.buf.push(state.buf.length === 0 ? "" : ",");
if (writeProp(state, mutation.object, null, "")) {
let objectRef = state.refs.get(mutation.object);
objectRef && objectRef.scopeId === void 0 && (objectRef.id ? hasSeen || (state.buf[objectStartIndex] = "(" + state.buf[objectStartIndex], state.buf.push(")")) : (objectRef.id = nextRefAccess(state), state.buf[objectStartIndex] = "(" + objectRef.id + "=" + state.buf[objectStartIndex], state.buf.push(")")));
} else state.buf.push("void 0");
let valueStartIndex = state.buf.push(toAccess(toObjectKey(mutation.property)) + "(");
if (mutation.value !== void 0) if (writeProp(state, mutation.value, null, "")) {
let valueRef = typeof mutation.value == "string" ? state.strs.get(mutation.value) : state.refs.get(mutation.value);
valueRef && !valueRef.id && valueRef.scopeId === void 0 && (valueRef.id = mutation.valueId || nextRefAccess(state), state.buf[valueStartIndex] = valueRef.id + "=" + state.buf[valueStartIndex]);
} else state.buf.push("void 0");
state.buf.push(")");
}
state.mutated = remaining;
}
state.pendingAssignments.size && writeAssigned(state);
}
function writeCallArg(state, val) {
if (val === void 0) state.wroteUndefined = !0, state.buf.push("$");
else if (writeProp(state, val, null, "")) {
let ref = state.refs.get(val) || state.strs.get(val);
ref && ref.id === null && assignId(state, ref);
} else state.buf.push("void 0");
}
function hasChannelMutations(state) {
return hasMatchingMutations(state.mutated, state.channel?.readyId);
}
function hasMatchingMutations(mutated, readyId) {
for (let mutation of mutated) if (mutationMatchesReadyId(mutation, readyId)) return !0;
return !1;
}
function mutationMatchesReadyId(mutation, readyId) {
return mutation.channel?.readyId ? mutation.channel.readyId === readyId : !readyId;
}
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: return !1;
}
}
function writeReferenceOr(state, write, val, parent, accessor) {
let ref = state.refs.get(val);
if (ref) return trackChannel(state, ref) ? parent && isCircular(parent, ref) ? (ensureId(state, ref), state.pendingAssignments.add(ref), addAssignment(ref, accessId(state, parent) + toAccess(accessor)), !1) : (state.buf.push(ensureId(state, ref)), !0) : !1;
let registered = REGISTRY.get(val);
return registered ? writeRegistered(state, val, parent, accessor, registered) : (state.refs.set(val, ref = new Reference(parent, accessor, state.flushId, state.buf.length)), ref.channel = state.channel, write(state, val, ref) ? !0 : (state.refs.delete(val), !1));
}
function trackScope(state, val, scopeId) {
let ref = state.refs.get(val);
ref ? trackChannel(state, ref) : newScopeReference(state, val, scopeId);
}
function newScopeReference(state, val, scopeId) {
let ref = new Reference(null, null, state.flushId);
return ref.scopeId = scopeId, ref.channel = state.channel, state.refs.set(val, ref), ref;
}
function writeRegistered(state, val, parent, accessor, registered) {
let { scope } = registered;
if (scope) {
let ref = new Reference(parent, accessor, state.flushId, state.buf.length);
ref.channel = state.channel, state.refs.set(val, ref);
let scopeId = scope[K_SCOPE_ID];
trackScope(state, scope, scopeId), state.buf.push("_(" + scopeId + "," + quote(registered.id, 0) + ")");
} else state.buf.push(registered.access);
return !0;
}
function writeString(state, val, parent, accessor) {
if (val.length > 12) {
let ref = state.strs.get(val);
if (ref) {
if (trackChannel(state, ref)) return state.buf.push(ensureId(state, ref)), !0;
} else {
let ref = new Reference(parent, accessor, state.flushId, state.buf.length);
ref.channel = state.channel, state.strs.set(val, ref);
}
}
return state.buf.push(quote(val, 0)), !0;
}
function writeNumber(state, val) {
return state.buf.push(val + ""), !0;
}
function writeBoolean(state, val) {
return state.buf.push(val ? "!0" : "!1"), !0;
}
function writeBigInt(state, val) {
return state.buf.push(val + "n"), !0;
}
function writeFunction(state, val, parent, accessor) {
let wellKnownFunction = KNOWN_FUNCTIONS.get(val);
return wellKnownFunction ? (state.buf.push(wellKnownFunction), !0) : writeReferenceOr(state, writeNever, val, parent, accessor);
}
function writeSymbol(state, val, parent, accessor) {
let wellKnownSymbol = KNOWN_SYMBOLS.get(val);
if (wellKnownSymbol) return state.buf.push(wellKnownSymbol), !0;
let key = Symbol.keyFor(val);
return key === void 0 ? writeReferenceOr(state, writeUnknownSymbol, val, parent, accessor) : (state.buf.push("Symbol.for(" + quote(key, 0) + ")"), !0);
}
function writeUnknownSymbol(state) {
return state.buf.push("Symbol()"), !0;
}
function writeNever(state, val, ref) {
return !1;
}
function writeNull(state) {
return state.buf.push("null"), !0;
}
function writeObject(state, val, parent, accessor) {
if (val === null) return writeNull(state);
let scopeId = val[K_SCOPE_ID];
if (scopeId !== void 0) return trackScope(state, val, scopeId), state.buf.push("_(" + scopeId + ")"), !0;
let wellKnownObject = KNOWN_OBJECTS.get(val);
return wellKnownObject ? (state.buf.push(wellKnownObject), !0) : writeReferenceOr(state, writeUnknownObject, val, parent, accessor);
}
function writeUnknownObject(state, val, ref) {
let proto = Object.getPrototypeOf(val);
if (proto === objectProto) return writePlainObject(state, val, ref);
if (proto === arrayProto) return writeArray(state, val, ref);
switch (proto?.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, 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, 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");
}
return !1;
}
function writePlainObject(state, val, ref) {
return state.buf.push("{"), writeMaybeIterableProps(state, val, ref), state.buf.push("}"), !0;
}
function writeArray(state, val, ref) {
let sep = "[";
for (let i = 0; i < val.length; i++) {
let item = val[i];
state.buf.push(sep), sep = ",", item === void 0 ? (state.wroteUndefined = !0, state.buf.push("$")) : writeProp(state, item, ref, "" + i);
}
return sep === "[" ? state.buf.push("[]") : state.buf.push("]"), !0;
}
function writeDate(state, val) {
return state.buf.push("new Date(" + +val + ")"), !0;
}
function writeRegExp(state, val) {
let { source } = val;
return source.includes("<") ? state.buf.push(`RegExp(${quote(source, 0)}${val.flags ? ",\"" + val.flags + "\"" : ""})`) : state.buf.push("/" + (unsafeRegExpSourceDetect.test(source) ? source.replace(unsafeRegExpSourceReg, replaceUnsafeRegExpSourceChar) : source) + "/" + val.flags), !0;
}
function writePromise(state, val, ref) {
let { boundary, channel } = state;
if (!boundary) return !1;
let pId = nextRefAccess(state), handle = newAsyncHandle(state, ref, pId);
return state.buf.push("(p=>p=new Promise((f,r)=>" + pId + "={f,r(e){p.catch(_=>0);r(e)}}))()"), val.then((v) => writeAsyncCall(state, boundary, handle, "f", v, channel, pId), (v) => writeAsyncCall(state, boundary, handle, "r", v, channel, pId)), boundary.startAsync(), !0;
}
function newAsyncHandle(state, parent, id) {
let handle = {}, handleRef = new Reference(parent, null, state.flushId, null, id);
return handleRef.channel = state.channel, state.refs.set(handle, handleRef), handle;
}
function writeMap(state, val, ref) {
if (!val.size) return state.buf.push("new Map"), !0;
let items = [], assignments, needsId, deferring = !1, i = 0;
if (val.size < 25) {
for (let [itemKey, itemValue] of val) {
if (!deferring && (itemKey !== val && isAncestorMember(state, ref, itemKey) || itemValue !== val && isAncestorMember(state, ref, itemValue)) && (deferring = !0), deferring) {
deferCall(state, ref, "set", [itemKey, itemValue]);
continue;
}
itemKey === val && (itemKey = void 0, (assignments ||= []).push("a[" + i + "][0]")), itemValue === val && (itemValue = void 0, (assignments ||= []).push("a[" + i + "][1]")), needsId ||= isDedupedMember(itemKey) || isDedupedMember(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 (let [itemKey, itemValue] of val) {
if (!deferring && (itemKey !== val && isAncestorMember(state, ref, itemKey) || itemValue !== val && isAncestorMember(state, ref, itemValue)) && (deferring = !0), deferring) {
deferCall(state, ref, "set", [itemKey, itemValue]);
continue;
}
itemKey === val && (itemKey = 0, (assignments ||= []).push("a[" + i + "]")), itemValue === val && (itemValue = 0, (assignments ||= []).push("a[" + (i + 1) + "]")), needsId ||= isDedupedMember(itemKey) || isDedupedMember(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 !0;
}
function writeSet(state, val, ref) {
if (!val.size) return state.buf.push("new Set"), !0;
let items = [], assignments, needsId, deferring = !1, i = 0;
for (let item of val) {
if (!deferring && item !== val && isAncestorMember(state, ref, item) && (deferring = !0), deferring) {
deferCall(state, ref, "add", [item]);
continue;
}
item === val ? (item = 0, (assignments ||= []).push("i[" + i + "]")) : needsId ||= isDedupedMember(item), i = items.push(item);
}
return writeArrayArg(state, ref, items, assignments && "((s,i)=>(" + assignmentsToString(assignments, "s") + ",i.forEach(i=>s.add(i)),s))(new Set,", "new Set(", needsId), !0;
}
function isAncestorMember(state, container, member) {
if (member === null || typeof member != "object" && typeof member != "function") return !1;
let ref = state.refs.get(member);
return ref !== void 0 && isCircular(container, ref);
}
function deferCall(state, ref, method, args) {
ensureId(state, ref), (ref.calls ||= []).push({
method,
args
}), state.pendingAssignments.add(ref);
}
function writeArrayArg(state, ref, items, assignsPrefix, plainPrefix, needsId) {
if (assignsPrefix || needsId) {
let 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 isDedupedMember(val) {
switch (typeof val) {
case "object": return val !== null && val[K_SCOPE_ID] === void 0;
case "function":
case "symbol": return !0;
case "string": return val.length > 12;
default: return !1;
}
}
function canWriteBuffer(state, buffer, ref) {
return Object.getPrototypeOf(buffer)?.constructor === ArrayBuffer;
}
function writeDataView(state, val, ref) {
let { buffer } = val;
if (!canWriteBuffer(state, buffer, ref)) return !1;
let needsLength = val.byteOffset + val.byteLength < buffer.byteLength;
return state.buf.push("new DataView("), writeProp(state, buffer, ref, "buffer"), state.buf.push((val.byteOffset || needsLength ? "," + val.byteOffset + (needsLength ? "," + val.byteLength : "") : "") + ")"), !0;
}
function writeArrayBuffer(state, val) {
let result;
if (val.byteLength) {
let view = new Int8Array(val);
result = hasOnlyZeros(view) ? "new ArrayBuffer(" + val.byteLength + ")" : "new Int8Array(" + typedArrayToInitString(view) + ").buffer";
} else result = "new ArrayBuffer";
return state.buf.push(result), !0;
}
function writeTypedArray(state, val, ref) {
if (val.byteOffset || val.byteLength < val.buffer.byteLength || state.refs.has(val.buffer)) {
if (!canWriteBuffer(state, val.buffer, ref)) return !1;
let needsLength = val.byteOffset + val.byteLength < val.buffer.byteLength;
state.buf.push("new " + val.constructor.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 " + val.constructor.name + (val.length === 0 ? "" : "(" + (hasOnlyZeros(val) ? val.length : typedArrayToInitString(val)) + ")"));
return !0;
}
function writeWeakSet(state) {
return state.buf.push("new WeakSet"), !0;
}
function writeWeakMap(state) {
return state.buf.push("new WeakMap"), !0;
}
function writeError(state, val, ref) {
let result = "new " + val.constructor.name + "(" + quote(val.message + "", 0);
if (val.cause !== void 0) {
let pos = state.buf.push(result + ",{cause:") - 1;
writeProp(state, val.cause, ref, "cause") ? state.buf.push("})") : state.buf[pos] = state.buf[pos].slice(0, -8) + ")";
} else state.buf.push(result + ")");
return !0;
}
function writeAggregateError(state, val, ref) {
state.buf.push("new AggregateError(");
let inlined = writeProp(state, val.errors, ref, "errors");
if (inlined || state.buf.push("[]"), val.message ? state.buf.push("," + quote(val.message + "", 0) + ")") : state.buf.push(")"), inlined) {
let errorsRef = state.refs.get(val.errors);
errorsRef?.id && (state.pendingAssignments.add(errorsRef), addAssignment(errorsRef, accessId(state, ref) + toAccess("errors")));
}
return !0;
}
function writeURL(state, val) {
return state.buf.push("new URL(" + quote(val.toString(), 0) + ")"), !0;
}
function writeURLSearchParams(state, val) {
let str = val.toString();
return str ? state.buf.push("new URLSearchParams(" + quote(str, 0) + ")") : state.buf.push("new URLSearchParams"), !0;
}
function writeHeaders(state, val) {
let headers = stringEntriesToHeadersInit(val);
return state.buf.push("new Headers" + (headers ? "(" + headers + ")" : "")), !0;
}
function writeFormData(state, val, ref) {
let sep = "[", valStr = "";
for (let [key, value] of val) {
if (typeof value != "string") return !1;
valStr += sep + quote(key, 0) + "," + quote(value, 0), sep = ",";
}
return sep === "[" ? state.buf.push("new FormData") : state.buf.push(valStr + "].reduce((f,v,i,a)=>i%2&&f.append(a[i-1],v)||f,new FormData)"), !0;
}
function writeRequest(state, val, ref) {
let sep = "", bodySerialized = !1, hasBody = val.body && !val.bodyUsed && val.duplex === "half";
state.buf.push("new Request(" + quote(val.url, 0)), hasBody && (state.buf.push(",{body:"), writeProp(state, val.body, ref, "body") ? (state.buf.push(",duplex:\"half\""), sep = ",", bodySerialized = !0) : state.buf.pop());
let options = "";
val.cache !== "default" && (options += sep + "cache:" + quote(val.cache, 0), sep = ","), val.credentials !== "same-origin" && (options += sep + "credentials:" + quote(val.credentials, 0), sep = ",");
let seenHeaders = state.refs.get(val.headers);
if (seenHeaders) options += sep + "headers:" + ensureId(state, seenHeaders), sep = ",";
else {
state.refs.set(val.headers, new Reference(ref, "headers", state.flushId, null));
let headers = stringEntriesToHeadersInit(val.headers);
headers && (options += sep + "headers:" + headers, sep = ",");
}
return val.integrity && (options += sep + "integrity:" + quote(val.integrity, 0), sep = ","), val.keepalive && (options += sep + "keepalive:true", sep = ","), val.method !== "GET" && (options += sep + "method:" + quote(val.method, 0), sep = ","), val.mode !== "cors" && (options += sep + "mode:" + quote(val.mode, 0), sep = ","), val.redirect !== "follow" && (options += sep + "redirect:" + quote(val.redirect, 0), sep = ","), val.referrer !== "about:client" && (options += sep + "referrer:" + quote(val.referrer, 0), sep = ","), val.referrerPolicy && (options += sep + "referrerPolicy:" + quote(val.referrerPolicy, 0)), state.buf.push(bodySerialized ? options + "})" : options ? ",{" + options + "})" : ")"), !0;
}
function writeResponse(state, val, ref) {
let sep = "", options = "";
val.status !== 200 && (options += "status:" + val.status, sep = ","), val.statusText && (options += sep + "statusText:" + quote(val.statusText, 0), sep = ",");
let seenHeaders = state.refs.get(val.headers);
if (seenHeaders) options += sep + "headers:" + ensureId(state, seenHeaders);
else {
state.refs.set(val.headers, new Reference(ref, "headers", state.flushId, null));
let headers = stringEntriesToHeadersInit(val.headers);
headers && (options += sep + "headers:" + headers);
}
return !val.body || val.bodyUsed ? state.buf.push("new Response" + (options ? "(null,{" + options + "})" : "")) : (state.buf.push("new Response("), state.buf.push((writeProp(state, val.body, ref, "body") ? "" : "null") + (options ? ",{" + options + "})" : ")"))), !0;
}
function writeIntl(state, val, name, ref) {
let { locale, ...options } = val.resolvedOptions(), needsId = !1;
for (let key in options) if (isDedupedMember(options[key])) {
needsId = !0;
break;
}
state.buf.push("new Intl." + name + "(" + quote(locale, 0) + ",");
let optionsRef;
return needsId ? (optionsRef = new Reference(ref, null, state.flushId, null, nextRefAccess(state)), state.buf.push(optionsRef.id + "={")) : (optionsRef = new Reference(ref, null, state.flushId, state.buf.length), state.buf.push("{")), writeObjectProps(state, options, optionsRef), state.buf.push("})"), !0;
}
function writeIntlLocale(state, val) {
return state.buf.push("new Intl.Locale(" + quote(val.toString(), 0) + ")"), !0;
}
function writeTemporal(state, val, name) {
return state.buf.push("Temporal." + name + ".from(" + quote(val.toString(), 0) + ")"), !0;
}
function writeReadableStream(state, val, ref) {
let { boundary, channel } = state;
if (!boundary || val.locked) return !1;
let reader = val.getReader(), iterId = nextRefAccess(state), handle = newAsyncHandle(state, ref, iterId), onFulfilled = ({ value, done }) => {
done ? writeAsyncCall(state, boundary, handle, "r", value, channel) : boundary.signal.aborted || (reader.read().then(onFulfilled, onRejected), boundary.startAsync(), writeAsyncCall(state, boundary, handle, "f", value, channel));
}, onRejected = (reason) => {
writeAsyncCall(state, boundary, handle, "j", reason, channel);
};
return 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(), !0;
}
function writeGenerator(state, iter, ref) {
if (iter[kTouchedIterator]) return state.buf.push("(function*(){}())"), !0;
let yields = [], returnValue, needsId;
for (;;) {
let { value, done } = iter.next();
if (done) {
returnValue = value;
break;
}
needsId ||= isDedupedMember(value), yields.push(value);
}
if (returnValue === void 0 && !yields.length) return state.buf.push("(function*(){})()"), !0;
let heldReturn = returnValue !== void 0 && isAncestorMember(state, ref, returnValue);
if (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})("), needsId) {
let 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) {
let 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) {
let sepIndex = state.buf.push(",") - 1;
if (writeProp(state, returnValue, ref, "") && isDedupedMember(returnValue)) {
let retRef = typeof returnValue == "string" ? state.strs.get(returnValue) : state.refs.get(returnValue);
retRef && !retRef.id && retRef.scopeId === void 0 && (retRef.id = nextRefAccess(state), state.buf[sepIndex] = "," + retRef.id + "=");
}
}
return state.buf.push(")"), !0;
}
function writeAsyncGenerator(state, iter, ref) {
if (iter[kTouchedIterator]) return state.buf.push("(async function*(){}())"), !0;
let { boundary, channel } = state;
if (!boundary) return !1;
let iterId = nextRefAccess(state), handle = newAsyncHandle(state, ref, iterId), onFulfilled = ({ value, done }) => {
done ? writeAsyncCall(state, boundary, handle, "r", value, channel) : boundary.signal.aborted || (iter.next().then(onFulfilled, onRejected), boundary.startAsync(), writeAsyncCall(state, boundary, handle, "f", value, channel));
}, onRejected = (reason) => {
writeAsyncCall(state, boundary, handle, "j", reason, channel);
};
return 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(), !0;
}
function writeNullObject(state, val, ref) {
return state.buf.push("{"), state.buf.push(writeMaybeIterableProps(state, val, ref) + "__proto__:null}"), !0;
}
function writeObjectProps(state, val, ref) {
let sep = "";
for (let key in val) if (hasOwnProperty.call(val, key)) {
let escapedKey = toObjectKey(key);
state.buf.push(sep + escapedKey + ":"), writeProp(state, val[key], ref, escapedKey) ? sep = "," : state.buf.pop();
}
return sep;
}
function writeMaybeIterableProps(state, val, ref) {
let sep = writeObjectProps(state, val, ref);
if (hasSymbolIterator(val)) {
let yieldSelf = "", iterArr = [];
for (let item of val) item === val && !(yieldSelf || iterArr.length) ? yieldSelf = "yield this;" : iterArr.push(item);
if (iterArr.length) {
let 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 writeAsyncCall(state, boundary, handle, method, value, channel, valueId = null) {
boundary.signal.aborted || (state.mutated.push({
value,
object: handle,
property: method,
channel,
valueId
}), boundary.endAsync());
}
function trackChannel(state, ref) {
let refReadyId = ref.channel?.readyId;
if (!refReadyId || refReadyId === state.channel?.readyId) return !0;
let cur = state.channel?.parent;
for (; cur;) {
if (cur.readyId === refReadyId) return (state.channelDeps ||= /* @__PURE__ */ new Set()).add(refReadyId), !0;
cur = cur.parent;
}
return !1;
}
function isCircular(parent, ref) {
let cur = parent;
for (; cur;) {
if (cur === ref) return !0;
cur = cur.parent;
}
return !1;
}
function toObjectKey(name) {
if (name === "") return "\"\"";
if (name === "__proto__") return "[\"__proto__\"]";
let len = name.length, 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++) {
let 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++) {
let 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) {
let start = accessor[0];
return start === "[" ? accessor : start === "\"" || start >= "0" && start <= "9" ? "[" + accessor + "]" : "." + accessor;
}
function quote(str, startPos) {
if (!unsafeQuoteReg.test(str)) return "\"" + str + "\"";
let result = "", lastPos = 0;
for (let i = startPos; i < str.length; i++) {
let replacement, 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) {
let 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 ensureId(state, ref) {
return ref.scopeId === void 0 ? ref.id ? (trackChannel(state, ref), ref.id) : assignId(state, ref) : (trackChannel(state, ref), "_(" + ref.scopeId + ")");
}
function accessId(state, ref) {
let id = ensureId(state, ref);
return id === ref.id || ref.scopeId !== void 0 ? id : "(" + id + ")";
}
function assignId(state, ref) {
let { pos } = ref;
if (ref.id = nextRefAccess(state), pos !== null && ref.flushId === state.flushId) return pos === 0 ? state.buf[0] = ref.id + "=" + state.buf[0] : state.buf[pos - 1] += ref.id + "=", ref.id;
ref.channel = state.channel;
let cur = ref, accessPrevValue = "";
do {
accessPrevValue = toAccess(cur.accessor) + accessPrevValue;
let parent = cur.parent;
if (parent.id && (trackChannel(state, parent) || !parent.parent)) {
accessPrevValue = parent.id + accessPrevValue;
break;
}
if (parent.flushId === state.flushId || parent.scopeId !== void 0) {
accessPrevValue = accessId(state, parent) + accessPrevValue;
break;
}
cur = parent;
} while (cur);
return ref.id + "=" + accessPrevValue;
}
function assignmentsToString(assignments, value) {
return assignments.length > 100 ? "($=>(" + assignments.join("=$,") + "=$))(" + value + ")" : assignments.join("=") + "=" + value;
}
function addAssignment(ref, assign) {
ref.assignments ? ref.assignments.push(assign) : ref.assignments = [assign];
}
function nextRefAccess(state) {
return "_." + nextId(state);
}
function nextId(state) {
let c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789", n = state.ids++, r = c[n % 53];
for (n = n / 53 | 0; n; n >>>= 6) r += c[n & 63];
return r;
}
function hasSymbolIterator(value) {
return Symbol.iterator in value;
}
function stringEntriesToHeadersInit(entries) {
let list = [...entries];
if (!list.length) return "";
let duplicate = !1, seen = /* @__PURE__ */ new Set();
for (let [key] of list) {
if (seen.has(key)) {
duplicate = !0;
break;
}
seen.add(key);
}
let result = "", sep = "";
for (let [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) {
let suffix = typeof view[0] == "bigint" ? "n" : "", result = "[", sep = "";
for (let i = 0; i < view.length; i++) result += sep + view[i] + suffix, sep = ",";
return result += "]", result;
}
function hasOnlyZeros(typedArray) {
let zero = typeof typedArray[0] == "bigint" ? 0n : 0;
for (let i = 0; i < typedArray.length; i++) if (typedArray[i] !== zero) return !1;
return !0;
}
function patchIteratorNext(proto) {
if (proto.next[kTouchedIterator]) return;
let { next } = proto;
proto.next = function(value) {
return this[kTouchedIterator] = 1, next.call(this, value);
}, proto.next[kTouchedIterator] = !0;
}
//#endregion
//#region src/common/for.ts
function forIn(obj, cb) {
for (let key in obj) cb(key, obj[key]);
}
function forOf(list, cb) {
if (list) {
let i = 0;
for (let item of list) cb(item, i++);
}
}
function forTo(to, from, step, cb) {
let start = from || 0, delta = step || 1;
for (let steps = (to - start) / delta, i = 0; i <= steps; i++) cb(start + i * delta);
}
function forUntil(until, from, step, cb) {
let start = from || 0, delta = step || 1;
for (let steps = (until - start) / delta, i = 0; i < steps; i++) cb(start + i * delta);
}
//#endregion
//#region src/common/opt.ts
function forEach(opt, cb) {
if (opt) if (Array.isArray(opt)) for (let item of opt) cb(item);
else cb(opt);
}
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 (let item of other) opt.push(item);
else opt.push(other);
return opt;
}
return Array.isArray(other) ? [opt, ...other] : [opt, other];
}
//#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/inlined-runtimes.ts
//#endregion
//#region src/html/writer.ts
function getChunk() {
return $chunk;
}
function withChunk(chunk, cb) {
let 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?.e === void 0 ? renderer?.a || renderer : renderer.a + " " + renderer.e;
}
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() {
let state = $chunk.boundary.state, { $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;
}
function withContext(key, value, cb, cbValue) {
let ctx = $chunk.context ||= { [kPendingContexts]: 0 }, prev = ctx[key];
ctx[kPendingContexts]++, ctx[key] = value;
try {
return cb(cbValue);
} finally {
ctx[kPendingContexts]--, ctx[key] = prev;
}
}
function isInResumedBranch() {
return $chunk?.context?.[kBranchId] !== void 0;
}
function withBranchId(branchId, cb, cbValue) {
return withContext(kBranchId, branchId, cb, cbValue);
}
function withIsAsync(cb, value) {
return withContext(kIsAsync, !0, cb, value);
}
function _html(html) {
$chunk.writeHTML(html);
}
function writeScript(script) {
$chunk.writeScript(script);
}
function _script(scopeId, registryId, serializeMarker) {
serializeMarker === 0 && ($chunk.serializeState.readyId || $chunk.context?.[kIsAsync]) && _resume_branch(scopeId), $chunk.boundary.state.needsMainRuntime = !0, $chunk.writeEffect(scopeId, registryId);
}
function _trailers(html) {
$chunk.boundary.state.trailerHTML += html;
}
function _resume(val, id, scopeId) {
return register(id, val, scopeId === void 0 ? void 0 : _scope_with_id(scopeId));
}
function _resume_locals(val, id, locals, ownerScopeId) {
return ownerScopeId !== void 0 && (locals._ = _scope_with_id(ownerScopeId)), register(id, val, writeScope(_scope_id(), locals));
}
function _el(scopeId, id) {
return _resume(() => void 0, id, scopeId);
}
function _hoist(scopeId, id) {
let getter = () => void 0;
return getter[Symbol.iterator] = _hoist_read_error, _resume(getter, id, scopeId);
}
function _el_resume(scopeId, accessor, shouldResume) {
if (shouldResume === 0) return "";
let { state } = $chunk.boundary;
return state.needsMainRuntime = !0, state.mark("$", scopeId + " " + accessor);
}
function _text_resume(scopeId, accessor, val, shouldResume) {
return markText(scopeId, accessor, _escape(val), shouldResume);
}
function _html_resume(scopeId, accessor, val, shouldResume) {
let html = _unescaped(val);
if (shouldResume === 0 || !~html.indexOf("<")) return markText(scopeId, accessor, html, shouldResume);
let { state } = $chunk.boundary;
return state.needsMainRuntime = !0, state.mark("&", "") + html + state.mark("'", scopeId + " " + accessor);
}
function markText(scopeId, accessor, text, shouldResume) {
if (shouldResume === 0) return text;
let { state } = $chunk.boundary;
return state.needsMainRuntime = !0, text ? (shouldResume === 2 ? "<!>" : "") + text + state.mark("$", scopeId + " " + accessor) : state.mark("%", scopeId + " " + accessor);
}
function _resume_branch(scopeId) {
let branchId = $chunk.context?.[kBranchId];
branchId !== void 0 && branchId !== scopeId && writeScope(scopeId, { G: branchId });
}
function _attr_content(nodeAccessor, scopeId, content, serializeReason) {
let shouldResume = serializeReason !== 0, render = normalizeServerRender(content), branchId = _peek_scope_id();
render && (shouldResume ? withBranchId(branchId, render) : render()), _peek_scope_id() === branchId ? _scope_id() : shouldResume && writeScope(scopeId, {
["A" + nodeAccessor]: writeScope(branchId, {}),
["D" + nodeAccessor]: rendererKey(render)
});
}
function normalizeServerRender(value) {
let renderer = normalizeDynamicRenderer(value);
if (renderer && typeof renderer == "function") return renderer;
}
function _var(parentScopeId, scopeOffsetAccessor, childScopeId, registryId, nodeAccessor) {
writeScopePassive(parentScopeId, { [scopeOffsetAccessor]: _scope_id() });
let childScope = writeScopePassive(childScopeId, { T: _resume({}, registryId, parentScopeId) });
nodeAccessor !== void 0 && writeScope(parentScopeId, { ["A" + nodeAccessor]: childScope });
}
function writeScopePassive(scopeId, partialScope) {
let target = $chunk.serializeState, scope = _scope_with_id(scopeId), passive = target.passiveScopes ||= {};
return Object.assign(scope, partialScope), passive[scopeId] = Object.assign(passive[scopeId] || {}, partialScope), scope;
}
function _show_start(display, mark) {
display ? mark && $chunk.writeHTML($chunk.boundary.state.mark("[", "")) : $chunk.writeHTML("<t hidden>");
}
function _show_end(scopeId, accessor, display, serializeMarker, serializeStateful, parentEndTag, singleNode) {
let branchId = _scope_id(), wrap = !display;
wrap && $chunk.writeHTML("</t>"), writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, parentEndTag, wrap || singleNode ? 1 : void 0, " " + branchId);
}
function _for_of(list, cb, by, scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode) {
forBranches(by, (each) => each ? forOf(list, (item, index) => {
let itemKey = forOfBy(by, item, index);
each(itemKey, itemKey === index, () => cb(item, index));
}) : forOf(list, cb), scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode);
}
function _for_in(obj, cb, by, scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode) {
forBranches(by, (each) => each ? forIn(obj, (key, value) => {
each(forInBy(by, key, value), !1, () => cb(key, value));
}) : forIn(obj, cb), scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode);
}
function _for_to(to, from, step, cb, by, scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode) {
forBranches(by, (each) => {
let index = 0;
return each ? forTo(to, from, step, (value) => {
let itemKey = forStepBy(by, value);
each(itemKey, itemKey === index++, () => cb(value));
}) : forTo(to, from, step, cb);
}, scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode);
}
function _for_until(to, from, step, cb, by, scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode) {
forBranches(by, (each) => {
let index = 0;
return each ? forUntil(to, from, step, (value) => {
let itemKey = forStepBy(by, value);
each(itemKey, itemKey === index++, () => cb(value));
}) : forUntil(to, from, step, cb);
}, scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode);
}
function forBranches(by, iterate, scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode) {
if (serializeBranch === 0) {
iterate(0), writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, parentEndTag, singleNode, "");
return;
}
let { state } = $chunk.boundary, resumeKeys = serializeMarker !== 0, resumeMarker = resumeKeys && (!parentEndTag || serializeStateful !== 0), flushBranchIds = "", loopScopes;
iterate((itemKey, sameAsIndex, render) => {
let branchId = _peek_scope_id();
resumeMarker && (singleNode ? flushBranchIds = " " + branchId + flushBranchIds : ($chunk.writeHTML(state.mark("[", flushBranchIds)), flushBranchIds = branchId + "")), withBranchId(branchId, () => {
render();
let branchScope = writeScope(branchId, resumeKeys && !sameAsIndex ? { M: itemKey } : {});
resumeMarker || (loopScopes = push(loopScopes, branchScope));
});
}), loopScopes && writeScope(scopeId, { ["A" + accessor]: loopScopes }), writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, parentEndTag, singleNode, singleNode ? flushBranchIds : flushBranchIds ? " " + flushBranchIds : "");
}
function _if(cb, scopeId, accessor, serializeBranch, serializeMarker, serializeStateful, parentEndTag, singleNode) {
let resumeBranch = serializeBranch !== 0, resumeMarker = serializeMarker !== 0 && (!parentEndTag || serializeStateful !== 0), branchId = _peek_scope_id(), chunk = $chunk, beforeBranch = resumeMarker && resumeBranch && !singleNode ? deferBranchStart(chunk) : void 0, branchIndex = resumeBranch ? withBranchId(branchId, cb) : cb(), shouldWriteBranch = resumeBranch && branchIndex !== void 0;
beforeBranch !== void 0 && applyBranchStart(chunk, beforeBranch, shouldWriteBranch), shouldWriteBranch && (branchIndex || !resumeMarker) && writeScope(scopeId, {
["D" + accessor]: branchIndex || void 0,
["A" + accessor]: resumeMarker ? void 0 : writeScope(branchId, {})
}), writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, parentEndTag, singleNode, shouldWriteBranch ? " " + branchId : "");
}
function deferBranchStart(chunk) {
let beforeBranch = chunk.html;
return chunk.html = "", beforeBranch;
}
function applyBranchStart(chunk, beforeBranch, rendered) {
chunk.html = beforeBranch + (rendered ? chunk.boundary.state.mark("[", "") : "") + chunk.html;
}
function writeBranchEnd(scopeId, accessor, serializeStateful, serializeMarker, parentEndTag, singleNode, branchIds) {
let endTag = parentEndTag || "";
if (serializeMarker !== 0) if (!parentEndTag || serializeStateful !== 0) {
let { state } = $chunk.boundary, mark = singleNode ? state.mark(parentEndTag ? "}" : "|", scopeId + " " + accessor + (branchIds || "")) : state.mark(parentEndTag ? ")" : "]", scopeId + " " + accessor + (branchIds || ""));
$chunk.writeHTML(mark + endTag);
} else $chunk.writeHTML(endTag + _el_resume(scopeId, accessor));
else $chunk.writeHTML(endTag);
}
function _existing_scope(scopeId) {
return writeScope(scopeId, {});
}
function _scope_with_id(scopeId) {
return scopeWithId($chunk.boundary.state, scopeId);
}
function scopeWithId(state, scopeId) {
let { scopes } = state, scope = scopes.get(scopeId);
return scope || scopes.set(scopeId, scope = { [K_SCOPE_ID]: scopeId }), scope;
}
function _subscribe(subscribers, scope) {
if (subscribers) {
let { serializer } = $chunk.boundary.state;
!$chunk.serializeState.readyId && !serializer.written(subscribers) ? subscribers.add(scope) : serializer.writeCall(scope, subscribers, "add", $chunk.serializeState);
}
return scope;
}
function _set_serialize_reason(reason) {
$chunk.boundary.state.serializeReason = reason;
}
function _scope_reason() {
let reason = $chunk.boundary.state.serializeReason;
return $chunk.boundary.state.serializeReason = void 0, reason;
}
function _serialize_if(condition, key) {
return condition && (condition === 1 || (typeof condition == "number" ? condition >>> key + 1 & 1 : condition[key])) ? 1 : void 0;
}
function _serialize_guard(condition, key) {
return _serialize_if(condition, key) || 0;
}
function writeWaitReady(readyId, renderer, input) {
let chunk = $chunk, { boundary } = chunk, body = new Chunk(boundary, null, chunk.context, {
readyId,
parent: chunk.serializeState,
resumes: "",
writeScopes: {},
flushScopes: !1
}), bodyEnd = body.render(renderer, input);
body === bodyEnd ? (chunk.writeHTML(body.html), body.deferOwnReady(), chunk.deferredReady = push(chunk.deferredReady, body)) : (bodyEnd.next = $chunk = chunk.fork(boundary, chunk.next), chunk.next = body);
}
function _await(scopeId, accessor, promise, content, serializeMarker) {
let resumeMarker = serializeMarker !== 0;
if (!isPromise(promise)) {
if (resumeMarker) {
let 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;
}
let chunk = $chunk, { boundary } = chunk;
chunk.next = $chunk = chunk.fork(boundary, chunk.next), chunk.async = !0, chunk.context?.[kPendingContexts] && (chunk.context = {
...chunk.context,
[kPendingContexts]: 0
}), boundary.startAsync(), promise.then((value) => {
chunk.async && (chunk.async = !1, boundary.signal.aborted || (chunk.render(() => {
if (resumeMarker) {
let branchId = _peek_scope_id();
$chunk.writeHTML($chunk.boundary.state.mark("[", "")), withBranchId(branchId, () => withIsAsync(content, value)), $chunk.writeHTML($chunk.boundary.state.mark("]", scopeId + " " + accessor + " " + branchId));
} else withIsAsync(content, value);
}), boundary.endAsync()));
}, (err) => {
chunk.async = !1, boundary.abort(err);
});
}
function _try(scopeId, accessor, content, input) {
let catchContent = input.catch ? normalizeDynamicRenderer(input.catch) || 0 : void 0, placeholderContent = normalizeDynamicRenderer(input.placeholder), placeholderBranchId = placeholderContent ? _scope_id() : 0, branchId = _peek_scope_id(), chunk = $chunk, { boundary } = chunk, { state } = boundary, { resumeWrites } = boundary, beforeBranch = deferBranchStart(chunk), renderersAtSettle = !1;
catchContent !== void 0 || placeholderContent ? renderersAtSettle = tryBoundary(placeholderContent ? () => tryPlaceholder(content, placeholderContent, branchId, scopeId, placeholderBranchId) : content, catchContent, placeholderContent, branchId) : withBranchId(branchId, content);
let rendered = chunk !== $chunk || boundary.resumeWrites !== resumeWrites;
applyBranchStart(chunk, beforeBranch, rendered), rendered && (renderersAtSettle || writeTryRenderers(branchId, catchContent, placeholderContent), $chunk.writeHTML(state.mark("]", scopeId + " " + accessor + " " + branchId)));
}
function tryPlaceholder(content, placeholder, branchId, scopeId, placeholderBranchId) {
let chunk = $chunk, { boundary } = chunk, body = chunk.fork(boundary, null);
if (body === body.render(content)) {
chunk.append(body);
return;
}
chunk.next = $chunk = chunk.fork(boundary, chunk.next), chunk.placeholder = {
body,
render: placeholder,
branchId,
scopeId,
placeholderBranchId
};
}
function tryBoundary(content, catchContent, placeholderContent, branchId) {
let chunk = $chunk, { boundary } = chunk, { state } = boundary, catchBoundary = new Boundary(state, boundary.signal, boundary), body = chunk.fork(catchBoundary, null), bodyEnd = withBranchId(branchId, () => body.render(content));
if (catchBoundary.signal.aborted) return catchContent === void 0 ? boundary.abort(catchBoundary.signal.reason) : catchContent && catchContent(catchBoundary.signal.reason), !1;
if (body === bodyEnd) return chunk.append(body), !1;
let renderersAtSettle = !catchBoundary.resumeWrites, bodyNext = bodyEnd.next = $chunk = chunk.fork(boundary, chunk.next);
chunk.next = body, boundary.startAsync();
let reorderId = catchContent === void 0 ? "" : state.nextReorderId(), endMarker = reorderId && state.mark("!", reorderId);
return reorderId && (chunk.writeHTML(state.mark("!^", reorderId)), bodyEnd.writeHTML(endMarker)), catchBoundary.onNext = () => {
if (!boundary.signal.aborted) if (catchBoundary.signal.aborted) {
if (!reorderId) {
boundary.abort(catchBoundary.signal.reason);
return;
}
if (!bodyEnd.consumed) {
let cur = body, writeMarker = !0;
do {
let next = cur.next;
cur.boundary !== catchBoundary && cur.boundary.abort(catchBoundary.signal.reason), writeMarker && !cur.consumed && (writeMarker = !1, cur.async = !1, cur.next = bodyNext, cur.needsWalk = !0, cur.html = endMarker, cur.scripts = cur.effects = cur.lastEffect = "", cur.placeholder = cur.reorderId = cur.deferredReady = null), cur = next;
} while (cur !== bodyNext);
}
let catchChunk = chunk.fork(boundary, null), { resumeWrites } = boundary;
catchChunk.reorderId = reorderId, (catchChunk.render(catchContent || NOOP$2, catchBoundary.signal.reason) !== catchChunk || boundary.resumeWrites !== resumeWrites) && renderersAtSettle && catchChunk.render(() => writeTryRenderers(branchId, catchContent, placeholderContent)), state.reorder(catchChunk), boundary.endAsync();
} else catchBoundary.count ? boundary.onNext() : (renderersAtSettle && catchBoundary.resumeWrites && bodyEnd.render(() => writeTryRenderers(branchId, catchContent, placeholderContent)), boundary.endAsync());
}, renderersAtSettle;
}
function writeTryRenderers(branchId, catchContent, placeholderContent) {
writeScope(branchId, {
E: catchContent,
Q: placeholderContent
});
}
function countResumeWrite(boundary) {
for (; boundary; boundary = boundary.parent) boundary.resumeWrites++;
}
var State = class {
tagId = 1;
scopeId = 1;
reorderId = 1;
readyGate = 1;
hasGlobals = !1;
needsMainRuntime = !1;
hasMainRuntime = !1;
hasReadyRuntime = !1;
hasReorderRuntime = !1;
hasWrittenResume = !1;
walkOnNextFlush = !1;
trailerHTML = "";
resumes = "";
nonceAttr = "";
serializer = new Serializer();
writeReorders = null;
scopes = /* @__PURE__ */ new Map();
flushScopes = !1;
writeScopes = {};
readyIds = null;
serializeReason;
$global;
constructor($global) {
this.$global = $global, $global.cspNonce && (this.nonceAttr = " nonce" + attrAssignment($global.cspNonce));
}
get runtimePrefix() {
let { $global } = this;
return $global.runtimeId + "." + $global.renderId;
}
get commentPrefix() {
let { $global } = this;
return $global.runtimeId + $global.renderId;
}
reorder(chunk) {
this.writeReorders ? this.writeReorders.push(chunk) : (this.needsMainRuntime = !0, this.writeReorders = [chunk]);
}
writeReady(id, resumes) {
let readyKey = toObjectKey(id);
return this.readyIds?.has(id) ? this.readyAccess(readyKey) + ".push(" + resumes + ")" : ((this.readyIds ||= /* @__PURE__ */ new Set()).add(id), this.hasReadyRuntime ? this.readyAccess(readyKey) + "=[" + resumes + "]" : (this.hasReadyRuntime = !0, this.runtimePrefix + ".b={" + readyKey + ":[" + resumes + "]}"));
}
readyAccess(readyKey) {
return this.runtimePrefix + ".b" + toAccess(readyKey);
}
nextReorderId() {
let c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789", n = this.reorderId++, 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 + "-->";
}
}, Boundary = class extends AbortController {
onNext = NOOP$2;
count = 0;
resumeWrites = 0;
state;
parent;
constructor(state, signal, parent) {
super(), this.state = state, this.parent = parent, this.signal.addEventListener("abort", () => {
this.count = 0, this.state = new State(this.state.$global), this.onNext();
}), signal && (signal.aborted ? this.abort(signal.reason) : signal.addEventListener("abort", () => {
this.abort(signal.reason);
}));
}
flush() {
return this.signal.aborted || flushSerializer(this, this.state), this.count ? 1 : this.signal.aborted ? 2 : 0;
}
startAsync() {
this.signal.aborted || this.count++;
}
endAsync() {
!this.signal.aborted && this.count && (this.count--, this.onNext());
}
}, Chunk = class Chunk {
html = "";
scripts = "";
effects = "";
lastEffect = "";
async = !1;
consumed = !1;
needsWalk = !1;
reorderId = null;
deferredReady = null;
placeholder = null;
boundary;
next;
context;
serializeState;
constructor(boundary, next, context, serializeState) {
this.boundary = boundary, this.next = next, this.context = context, this.serializeState = serializeState;
}
fork(boundary, next) {
return new Chunk(boundary, next, this.context, this.serializeState);
}
writeHTML(html) {
this.html += html;
}
writeEffect(scopeId, registryId) {
countResumeWrite(this.boundary), this.lastEffect === registryId ? this.effects += " " + scopeId : (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());
}
takeDeferredReady() {
let { deferredReady } = this;
return this.deferredReady = null, deferredReady;
}
deferOwnReady() {
if (this.serializeState.readyId && (this.effects || this.scripts || this.serializeState.flushScopes)) {
let 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);
}
}
flushPlaceholder() {
let { placeholder } = this;
if (placeholder) {
let body = placeholder.body.consume();
if (body.async) {
let { state } = this.boundary, { branchId, scopeId, placeholderBranchId } = placeholder, reorderId = body.reorderId = branchId ? branchId + "" : state.nextReorderId();
this.writeHTML(state.mark("!^", reorderId));
let { effects } = this, beforeBranch = deferBranchStart(this), after = this.render(() => withBranchId(placeholderBranchId, placeholder.render)), stateful = after === this && this.effects !== effects;
applyBranchStart(this, beforeBranch, stateful), after === this ? stateful && (this.render(() => writeScope(branchId, { P: scopeWithId(state, placeholderBranchId) })), this.writeHTML(state.mark("]", scopeId + " " + ("P" + branchId) + " " + placeholderBranchId)), body.writeEffect(branchId, "_f")) : this.boundary.abort(/* @__PURE__ */ Error("An @placeholder cannot contain async content.")), this.writeHTML(state.mark("!", reorderId)), state.reorder(body);
} else body.next = this.next, this.next = body;
this.placeholder = null;
}
}
consume() {
let cur = this, html = "", effects = "", scripts = "", lastEffect = "", needsWalk = !1, deferredReady;
for (; cur.next && !cur.async;) cur.flushPlaceholder(), needsWalk ||= cur.needsWalk, html += cur.html, cur.serializeState.readyId ? deferredReady = push(deferredReady, cur) : (effects = concatEffects(effects, cur.effects), scripts = concatScripts(scripts, cur.scripts), lastEffect = cur.lastEffect || lastEffect), deferredReady = concat(deferredReady, cur.takeDeferredReady()), cur.consumed = !0, cur = cur.next;
return cur.deferOwnReady(), cur.deferredReady = concat(deferredReady, cur.deferredReady), cur.needsWalk ||= needsWalk, cur.html = html + cur.html, cur.effects = concatEffects(effects, cur.effects), cur.scripts = concatScripts(scripts, cur.scripts), cur.lastEffect ||= lastEffect, cur;
}
render(content, val) {
let prev = $chunk;
$chunk = this;
try {
return content(val), $chunk;
} catch (err) {
return this.boundary.abort(err), this;
} finally {
$chunk = prev;
}
}
flushReadyScripts(reservations) {
let { boundary, serializeState } = this, { readyId } = serializeState, scripts = "";
if (forEach(this.takeDeferredReady(), (chunk) => {
scripts = concatScripts(scripts, chunk.flushReadyScripts(reservations));
}), readyId && !this.async) {
let { state } = boundary;
flushSerializer(boundary, serializeState);
let deps = state.serializer.takeChannelDeps(), { effects } = this, { resumes } = serializeState, chunkScripts = this.scripts;
if (serializeState.resumes = "", this.effects = this.scripts = "", this.lastEffect = "", resumes || effects) {
state.needsMainRuntime = !0;
let batch = concatSequence(depsMarker(deps), concatSequence(resumes, effects && `"${effects}"`));
if (reservations) {
let gate = state.readyGate++;
reservations.push(state.writeReady(readyId, gate + "")), scripts = concatScripts(scripts, "(b=>b.splice(b.indexOf(" + gate + "),1," + batch + "))(" + state.readyAccess(toObjectKey(readyId)) + ")");
} else scripts = concatScripts(scripts, state.writeReady(readyId, batch));
}
scripts = concatScripts(scripts, chunkScripts);
}
return scripts;
}
flushScript() {
let { boundary } = this, { state } = boundary, { $global, runtimePrefix } = state, needsWalk = state.walkOnNextFlush;
needsWalk && (state.walkOnNextFlush = !1);
let readyResumeScripts = this.flushReadyScripts();
for (let channel; channel = state.serializer.pendingReadyChannel();) {
let resumes = state.serializer.stringifyScopes([], boundary, channel), deps = state.serializer.takeChannelDeps();
state.needsMainRuntime = !0, readyResumeScripts = concatScripts(readyResumeScripts, state.writeReady(channel.readyId, concatSequence(depsMarker(deps), resumes)));
}
readyResumeScripts && (needsWalk = !0);
let effects = this.async ? "" : this.effects, { html, scripts } = this;
state.needsMainRuntime && !state.hasMainRuntime && (state.hasMainRuntime = !0, scripts = concatScripts(scripts, "(e=>(self[e]||=(l,f=e+l,s=f.length,a={},d=[],t=document,n=t.createTreeWalker(t,129))=>t=self[e][l]={i:f,d:t,l:a,v:d,x(){},w(e,l,r){for(;e=n.nextNode();)t.x(l=(l=e.data)&&!l.indexOf(f)&&(r=l.slice(s+1),(l=l[s])>\"#\"||(a[r]=e),l),r,e),l>\"#\"&&d.push(e)}},self[e]))(\"" + $global.runtimeId + "\")(\"" + $global.renderId + "\")")), scripts = concatScripts(scripts, readyResumeScripts), effects && (needsWalk = !0, state.resumes = state.resumes ? state.resumes + ",\"" + effects + "\"" : "\"" + effects + "\"");
let reordered = "", needsResumeArray = !1;
if (state.writeReorders) {
let carried = null;
for (let reorderedChunk of state.writeReorders) {
if (reorderedChunk.async && reorderedChunk.consumed) {
let aborted = reorderedChunk.boundary;
for (; aborted && !aborted.signal.aborted;) aborted = aborted.parent;
if (!aborted) {
(carried ||= []).push(reorderedChunk);
continue;
}
reorderedChunk.async = !1;
}
needsWalk = !0, state.hasReorderRuntime || (state.hasReorderRuntime = !0, scripts = concatScripts(scripts, "(e=>{if(e.j)return;let i,l,r,t=e.p={},c=(i,l)=>e.l[i].replaceWith(...l.childNodes);e.j={},e.x=(n,a,d,o,g)=>{d==r&&i(),\"#\"==n?(t[a]=l).i++:\"!\"==n?e.l[a]&&t[a]&&(r=d.nextSibling,i=()=>t[a].c()):\"T\"==d.tagName&&(a=d.getAttribute(e.i))&&(r=d.nextSibling,i=()=>{d.remove(),o||c(a,d),l.c()},l=t[a]||(o=t[a]={i:e.l[a]?1:2,r:a,c(i=e.l[\"^\"+a],f=d.cloneNode()){if(--o.i)return 1;for(;f.prepend(r=e.l[a].previousSibling||i),i!=r;);c(a,d)}}),e.v.push({data:e.i+\"*\"+l.r}),(n=e.j[a])&&(g=l.c,l.c=()=>g()||n(e.r)))}})(" + runtimePrefix + ")"));
let { reorderId } = reorderedChunk, readyReservations = [], reorderHTML = "", reorderEffects = "", reorderScripts = "", cur = reorderedChunk;
for (reorderedChunk.reorderId = null;;) {
cur.flushPlaceholder(), cur.deferOwnReady();
let { next } = cur, readyResumeScripts = cur.flushReadyScripts(readyReservations);
if (cur.consumed = !0, reorderHTML += cur.html, reorderEffects = concatEffects(reorderEffects, cur.effects), reorderScripts = concatScripts(reorderScripts, concatScripts(readyResumeScripts, cur.scripts)), cur.async && (reorderHTML += state.mark("#", cur.reorderId = state.nextReorderId()), state.reorder(cur), cur.html = cur.effects = cur.scripts = cur.lastEffect = "", cur.next = null), next) cur = next;
else break;
}
reorderEffects && (needsResumeArray = !0, reorderScripts = concatScripts(reorderScripts, "_.push(\"" + reorderEffects + "\")"));
for (let reservation of readyReservations) reordered = concatScripts(reordered, reservation);
reordered = concatScripts(reordered, reorderScripts && runtimePrefix + ".j" + toAccess(reorderId) + "=_=>{" + reorderScripts + "}"), html += "<t hidden " + state.commentPrefix + "=" + reorderId + ">" + reorderHTML + "</t>";
}
state.writeReorders = carried;
}
return flushSerializer(boundary, state), state.resumes ? state.hasWrittenResume ? scripts = concatScripts(scripts, runtimePrefix + ".r.push(" + state.resumes + ")") : (state.hasWrittenResume = !0, scripts = concatScripts(scripts, runtimePrefix + ".r=[" + state.resumes + "]")) : needsResumeArray && !state.hasWrittenResume && (state.hasWrittenResume = !0, scripts = concatScripts(scripts, runtimePrefix + ".r=[]")), scripts = concatScripts(scripts, reordered), needsWalk && (scripts = concatScripts(scripts, runtimePrefix + ".w()")), this.html = html, this.scripts = scripts, this.async || (this.effects = this.lastEffect = ""), state.resumes = "", this;
}
flushHTML() {
let { boundary } = this, { state } = boundary;
this.needsWalk && (this.needsWalk = !1, state.walkOnNextFlush = !0), this.flushScript();
let { scripts } = this, { $global, nonceAttr } = state, { __flush__ } = $global, { html } = this;
return this.html = this.scripts = "", scripts && (html += "<script" + nonceAttr + ">" + scripts + "<\/script>"), __flush__ && ($global.__flush__ = void 0, html = __flush__($global, html)), boundary.count || (html += state.trailerHTML), html;
}
};
function flushSerializer(boundary, serializeState) {
let { state } = boundary, { serializer } = state, pending = serializer.pending(serializeState);
if (serializeState.flushScopes || pending) {
let { writeScopes, passiveScopes } = serializeState, isBlockingState = serializeState !== state, flushes = [];
if (passiveScopes) for (let key in passiveScopes) {
let props = writeScopes[key];
props && (writeScopes[key] = Object.assign(passiveScopes[key], props), delete passiveScopes[key]);
}
if (!isBlockingState && !state.hasGlobals) {
state.hasGlobals = !0;
let globals = getFilteredGlobals(state.$global);
globals && flushes.push([
0,
globals,
globals
]);
}
for (let key in writeScopes) {
let scopeId = +key, props = writeScopes[scopeId];
Object.getOwnPropertyNames(props).length && flushes.push([
scopeId,
state.scopes.get(scopeId),
props
]);
}
(flushes.length || pending) && (isBlockingState && !state.hasGlobals && flushSerializerGlobals(boundary), serializeState.resumes = concatSequence(serializeState.resumes, serializer.stringifyScopes(flushes, boundary, serializeState))), serializeState.writeScopes = {}, serializeState.flushScopes = !1, pending && (state.walkOnNextFlush = !0);
}
}
function flushSerializerGlobals(boundary) {
let { state } = boundary, globals = getFilteredGlobals(state.$global);
globals && (state.hasGlobals = !0, state.needsMainRuntime = !0, state.resumes = concatSequence(state.resumes, state.serializer.stringifyScopes([[
0,
globals,
globals
]], boundary)));
}
function depsMarker(deps) {
let marker = "";
if (deps) {
for (let dep of deps) marker += (marker ? "," : "[") + quote(dep, 0);
marker += "]";
}
return marker;
}
function getFilteredGlobals($global) {
if (!$global) return 0;
let serializedGlobals = $global.serializedGlobals;
if (!serializedGlobals) return 0;
let filtered = 0;
if (Array.isArray(serializedGlobals)) for (let key of serializedGlobals) {
let value = $global[key];
value !== void 0 && (filtered ? filtered[key] = value : filtered = { [key]: value });
}
else for (let key in serializedGlobals) if (serializedGlobals[key]) {
let value = $global[key];
value !== void 0 && (filtered ? filtered[key] = value : 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;
}
function queueTick(cb) {
tickQueue ? tickQueue.add(cb) : (tickQueue = /* @__PURE__ */ new Set([cb]), tick(flushTickQueue));
}
function offTick(cb) {
tickQueue?.delete(cb);
}
function flushTickQueue() {
let queue = tickQueue;
tickQueue = void 0;
for (let cb of queue) try {
cb(!0);
} catch (err) {
tick(() => {
throw err;
});
}
}
//#endregion
//#region src/html/attrs.ts
function _attr_class(value) {
return stringAttr("class", toDelimitedString(value, " ", stringifyClassObject));
}
function _attr_style(value) {
return stringAttr("style", toDelimitedString(value, ";", stringifyStyleObject));
}
function _attr_option_value(value) {
let valueAttr = _attr("value", value), selectedValue = getContext(kSelectedValue);
return selectedValue !== void 0 && normalizedValueMatches(selectedValue, value) ? valueAttr + " selected" : valueAttr;
}
function _attr_select_value(scopeId, nodeAccessor, value, valueChange, content, serializeType) {
valueChange && writeControlledScope(3, scopeId, nodeAccessor, void 0, valueChange, serializeType), content && withContext(kSelectedValue, value ?? "", content);
}
function _attr_textarea_value(scopeId, nodeAccessor, value, valueChange, serializeType) {
return valueChange && writeControlledScope(2, scopeId, nodeAccessor, void 0, valueChange, serializeType), _textarea_value(value);
}
function _textarea_value(value) {
let escaped = _escape(normalizeStrAttrValue(value));
return escaped[0] === "\n" ? "\n" + escaped : escaped;
}
function _attr_input_value(scopeId, nodeAccessor, value, valueChange, serializeType) {
return valueChange && writeControlledScope(2, scopeId, nodeAccessor, void 0, valueChange, serializeType), _attr("value", value);
}
function _attr_input_checked(scopeId, nodeAccessor, checked, checkedChange, serializeType) {
return checkedChange && writeControlledScope(0, scopeId, nodeAccessor, void 0, checkedChange, serializeType), isNotVoid(checked) ? " checked" : "";
}
function _attr_input_checkedValue(scopeId, nodeAccessor, checkedValue, checkedValueChange, value, serializeType) {
let valueAttr = _attr("value", value);
return checkedValueChange && writeControlledScope(1, scopeId, nodeAccessor, getCheckedValueRef(checkedValue), checkedValueChange, serializeType), normalizedValueMatches(checkedValue, value) ? valueAttr + " checked" : valueAttr;
}
function getCheckedValueRef(checkedValue) {
if (Array.isArray(checkedValue)) {
let ref = checkedValuesRefs.get(checkedValue);
return ref || (ref = [], checkedValuesRefs.set(checkedValue, ref)), ref;
}
}
function _attr_details_or_dialog_open(scopeId, nodeAccessor, open, openChange, serializeType) {
let normalizedOpen = isNotVoid(open);
return openChange && writeControlledScope(4, scopeId, nodeAccessor, normalizedOpen || void 0, openChange, serializeType), normalizedOpen ? " open" : "";
}
function _attr_nonce() {
return getChunk().boundary.state.nonceAttr;
}
function _style_html(decls) {
let id = _id();
return `<style${_attr_nonce()} class=${id}>.${id}~*{${decls}}</style>`;
}
function _attr(name, value) {
return isVoid(value) ? "" : nonVoidAttr(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 = "", skip = /[\s/>"'=]/, events;
switch (data && tagName) {
case "input":
data.checkedChange ? (result += _attr_input_checked(scopeId, nodeAccessor, data.checked, data.checkedChange, 1), skip = /^checked(?:Value)?(?:Change)?$|[\s/>"'=]/) : "checkedValue" in data || data.checkedValueChange ? (result += _attr_input_checkedValue(scopeId, nodeAccessor, data.checkedValue, data.checkedValueChange, data.value, 1), skip = /^(?:value|checked(?:Value)?)(?:Change)?$|[\s/>"'=]/) : data.valueChange && (result += _attr_input_value(scopeId, nodeAccessor, data.value, data.valueChange, 1), skip = /^value(?:Change)?$|[\s/>"'=]/);
break;
case "select":
case "textarea":
("value" in data || data.valueChange) && (skip = /^value(?:Change)?$|[\s/>"'=]/);
break;
case "option":
"value" in data && (result += _attr_option_value(data.value), skip = /^value$|[\s/>"'=]/);
break;
case "details":
case "dialog":
data.openChange && (result += _attr_details_or_dialog_open(scopeId, nodeAccessor, data.open, data.openChange, 1), skip = /^open(?:Change)?$|[\s/>"'=]/);
break;
}
for (let name in data) {
let value = data[name];
switch (name) {
case "class":
result += _attr_class(value);
break;
case "style":
result += _attr_style(value);
break;
default:
name && !(isVoid(value) || skip.test(name) || name === "content" && tagName !== "meta") && (isEventHandler(name) ? (events || (events = {}, writeScope(scopeId, { ["I" + nodeAccessor]: events })), events[getEventHandlerName(name)] = value) : result += nonVoidAttr(name, value));
break;
}
}
return result;
}
function _attrs_content(data, nodeAccessor, scopeId, tagName, serializeReason) {
_html(`${_attrs(data, nodeAccessor, scopeId, tagName)}>`), _attr_content(nodeAccessor, scopeId, data?.content, serializeReason);
}
function _attrs_partial(data, skip, nodeAccessor, scopeId, tagName) {
let partial = {};
for (let name in data) {
let key = isEventHandler(name) ? `on-${getEventHandlerName(name)}` : name;
skip[key] || (partial[key] = data[name]);
}
return _attrs(partial, nodeAccessor, scopeId, tagName);
}
function _attrs_partial_content(data, skip, nodeAccessor, scopeId, tagName, serializeReason) {
_html(`${_attrs_partial(data, skip, nodeAccessor, scopeId, tagName)}>`), _attr_content(nodeAccessor, scopeId, data?.content, serializeReason);
}
function writeControlledScope(type, scopeId, nodeAccessor, value, valueChange, serializeType) {
writeScope(scopeId, serializeType ? {
["F" + nodeAccessor]: type,
["G" + nodeAccessor]: value,
["E" + nodeAccessor]: valueChange
} : {
["G" + nodeAccessor]: value,
["E" + nodeAccessor]: valueChange
});
}
function stringAttr(name, value) {
return value && " " + name + attrAssignment(value);
}
function nonVoidAttr(name, value) {
switch (typeof value) {
case "string": return " " + name + attrAssignment(value);
case "boolean": return " " + name;
case "number": return " " + name + "=" + value;
}
return " " + name + attrAssignment(value + "");
}
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 === "'" ? "'" : match === "\r" ? " " : "&";
}
function escapeDoubleQuotedAttrValue(value) {
return doubleQuoteAttrReplacements.test(value) ? value.replace(doubleQuoteAttrReplacements, replaceUnsafeDoubleQuoteAttrChar) : value;
}
function replaceUnsafeDoubleQuoteAttrChar(match) {
return match === "\"" ? """ : match === "\r" ? " " : "&";
}
function normalizedValueMatches(a, b) {
let value = normalizeStrAttrValue(b);
if (Array.isArray(a)) {
for (let item of a) if (normalizeStrAttrValue(item) === value) return !0;
} else if (normalizeStrAttrValue(a) === value) return !0;
return !1;
}
function normalizeStrAttrValue(value) {
return isNotVoid(value) && value !== !0 ? value + "" : "";
}
//#endregion
//#region src/html/dynamic-tag.ts
function _content(id, fn, scopeId) {
return fn.a = id, fn.e = scopeId, fn;
}
function _content_resume(id, fn, scopeId) {
return _resume(_content(id, fn, scopeId), id, scopeId);
}
//#endregion
//#region src/html/template.ts
function render(input = {}) {
let { $global } = input;
$global ? ({$global, ...input} = input, $global = {
runtimeId: "M",
renderId: getDefaultRenderId(this),
...$global
}) : $global = {
runtimeId: "M",
renderId: getDefaultRenderId(this)
};
let state = new State($global), head = new Chunk(new Boundary(state, $global.signal), null, null, state);
return this.i ? head.render(() => writeWaitReady(this.a, this, input)) : head.render(this, input), new ServerRendered(head);
}
function getDefaultRenderId(template) {
if (template.i) {
let ENCODE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789", n = Math.random() * 4294967296 >>> 0, 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, reject, value = "", done = !1, aborted = !1, reason, boundary = this.#read((html) => {
if (value += html, resolve) {
let settle = resolve;
resolve = reject = void 0, settle({
value,
done
}), value = "";
}
}, (err) => {
if (aborted = !0, reason = err, reject) {
let settle = reject;
resolve = reject = void 0, settle(err);
}
}, () => {
if (done = !0, resolve) {
let settle = resolve;
resolve = reject = void 0, settle({
value,
done: !value
}), value = "";
}
});
return {
next() {
if (aborted) return Promise.reject(reason);
if (value) {
let result = {
value,
done: !1
};
return value = "", Promise.resolve(result);
} else if (done) return Promise.resolve({
value: "",
done
});
else return new Promise(exec);
},
throw(error) {
return done || aborted || boundary?.abort(error), Promise.resolve({
value: "",
done: !0
});
},
return(value) {
return done || aborted || boundary?.abort(/* @__PURE__ */ Error("Iterator returned before consumed.")), Promise.resolve({
value,
done: !0
});
}
};
function exec(_resolve, _reject) {
resolve = _resolve, reject = _reject;
}
}
pipe(stream) {
this.#read((html) => {
stream.write(html), stream.flush?.();
}, (err) => {
let socket = "socket" in stream && stream.socket;
if (socket && typeof socket.destroySoon == "function" ? socket.destroySoon() : stream.destroy ? stream.destroy() : stream.end(), !stream.emit?.("error", err)) throw err;
}, () => {
stream.end();
});
}
toReadable() {
let cancelled = !1, started = !1, boundary, encoder = new TextEncoder();
return new ReadableStream({
pull: (ctrl) => {
started || (started = !0, boundary = this.#read((html) => {
ctrl.enqueue(encoder.encode(html));
}, (err) => {
boundary = void 0, cancelled || ctrl.error(err);
}, () => {
boundary = void 0, ctrl.close();
}));
},
cancel: (reason) => {
cancelled = !0, 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;
if (this.#head = null, !head) return reject(/* @__PURE__ */ Error(CONSUMED_RESULT_MESSAGE));
let { boundary } = head;
(boundary.onNext = () => {
switch (!boundary.count && boundary.flush()) {
case 2:
boundary.onNext = NOOP$1, reject(boundary.signal.reason);
break;
case 0: {
let consumed = head.consume();
boundary.signal.aborted || resolve(consumed.flushHTML());
break;
}
}
})();
});
}
#read(onWrite, onAbort, onClose) {
let tick = !0, head = this.#head;
if (this.#head = null, !head) {
onAbort(/* @__PURE__ */ Error(CONSUMED_RESULT_MESSAGE));
return;
}
let { boundary } = head, onNext = boundary.onNext = (write) => {
let status = boundary.flush();
if (status === 2) tick || offTick(onNext), boundary.onNext = NOOP$1, onAbort(boundary.signal.reason);
else if (write || status === 0) {
if (head = head.consume(), boundary.signal.aborted) return;
let html = head.flushHTML();
html && onWrite(html), status === 0 ? (tick || offTick(onNext), onClose()) : tick = !0;
} else tick && (tick = !1, queueTick(onNext));
};
return onNext(), boundary;
}
toString() {
let head = this.#head;
if (this.#head = null, !head) throw Error(CONSUMED_RESULT_MESSAGE);
let { boundary } = head;
switch (boundary.flush()) {
case 2: throw boundary.signal.reason;
case 1: throw Error("Cannot consume asynchronous render with 'toString'");
}
return head.consume().flushHTML();
}
};
function NOOP$1() {}
//#endregion
//#region src/html/assets.ts
function withLoadAssets(renderer, assetId, triggers) {
return Object.assign((input) => {
let g = $global();
return addAsset(g, assetId, triggers), _html(flush(g, "")), writeWaitReady(assetId, renderer, input);
}, renderer);
}
function withPageAssets(template, runtime, assetId, runtimeId) {
return assetFlush = runtime, Object.assign((input) => {
let g = $global();
return runtimeId && (g.runtimeId = runtimeId), addAsset(g, assetId), g.__flush__ ? (_html(flush(g, "")), writeWaitReady(assetId, template, input)) : (g.__flush__ = flush, template(input));
}, template);
}
function _flush_head() {
let g = $global();
return g[kAssets] ? flush(g, "") : "";
}
function flush(g, html) {
let result = "", assets = g[kAssets], { length } = assets, bi = g[kBlockIndex], di = g[kDeferIndex];
for (; bi < length; bi++) result += assetFlush(g, "block", assets[bi].id);
for (; di < length; di++) {
let { id, triggers } = assets[di], deferHTML = assetFlush(g, "defer", id);
triggers ? deferHTML && writeTriggerScript(id, deferHTML, triggers) : result += deferHTML;
}
return g[kBlockIndex] = bi, g[kDeferIndex] = di, result + html;
}
function addAsset(g, id, triggers) {
let assets = g[kAssets];
assets ? assets.find((a) => a.id === id) || assets.push({
id,
triggers
}) : (g[kAssets] = [{
id,
triggers
}], g[kBlockIndex] = g[kDeferIndex] = 0);
}
function writeTriggerScript(id, html, triggers) {
let htmlStr = _escape_script(JSON.stringify(html)), exprs = triggers.map((trigger) => {
let 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)})`;
}
});
writeScript(`((p,h,d,l=$=>{d||p.after(new Range().createContextualFragment(d=h))})=>${exprs.length > 1 ? `{${exprs.join(";")}}` : exprs[0]})(document.currentScript,${htmlStr})`);
}
function querySelectorOrLoad(selector) {
return `document.querySelector(${JSON.stringify(selector)})||l()`;
}
function toObjectExpression(options) {
let result = "{", sep = "";
for (let key in options) Object.hasOwn(options, key) && (result += sep + toObjectKey(key) + ":" + JSON.stringify(options[key]), sep = ",");
return result + "}";
}
//#endregion
//#region src/common/compat-meta.ts
//#endregion
//#region src/html/compat.ts
function drainClassFunctions($global, writeScope) {
let pending = pendingClassFunctions.get($global), scopeByHost = {};
for (let [id, fn, hostId] of pending) register(id, fn, scopeByHost[hostId] ||= writeScope(hostId));
pending.length = 0;
}
function NOOP() {}
//#endregion
export { $global, _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, _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, _serialize_guard, _serialize_if, _set_serialize_reason, _show_end, _show_start, _style_html, _subscribe, _template, _text_resume, _textarea_value, _to_text, _trailers, _try, _unescaped, _var, attrTag, attrTags, compat, forIn, forOf, forTo, forUntil, withLoadAssets, withPageAssets };