var __defProp = Object.defineProperty; var __typeError = (msg) => { throw TypeError(msg); }; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); import require$$0, { AsyncLocalStorage as AsyncLocalStorage$1 } from "node:async_hooks"; import path from "node:path"; import { createServer } from "http"; import { Http2ServerRequest } from "http2"; import { Readable } from "stream"; import crypto from "crypto"; import { existsSync, statSync, createReadStream } from "fs"; import { join } from "path"; import { versions } from "process"; import assetsManifest from "../__vite_rsc_assets_manifest.js"; import { buildMetadata } from "../__waku_build_metadata.js"; let INTERNAL_setAllEnv, __vite_rsc_react__, jsxRuntime_reactServerExports, joinPath, registerClientReference, serverEntry; let __tla = (async () => { var _body, _init, _a, _validatedData, _matchResult, _HonoRequest_instances, getDecodedParam_fn, getAllDecodedParams_fn, getParamValue_fn, _cachedBody, _b, _rawRequest, _req, _var, _status, _executionCtx, _res, _layout, _renderer, _notFoundHandler, _preparedHeaders, _matchResult2, _path, _Context_instances, newResponse_fn, _c, _path2, __Hono_instances, clone_fn, _notFoundHandler2, addRoute_fn, handleError_fn, dispatch_fn, _d, _routes, _e; function tinyassert(value, message) { if (value) return; if (message instanceof Error) throw message; throw new TinyAssertionError(message, tinyassert); } var TinyAssertionError = class extends Error { constructor(message, stackStartFunction) { super(message ?? "TinyAssertionError"); if (stackStartFunction && "captureStackTrace" in Error) Error.captureStackTrace(this, stackStartFunction); } }; function safeFunctionCast(f) { return f; } function memoize(f, options) { const keyFn = ((...args) => args[0]); const cache = /* @__PURE__ */ new Map(); return safeFunctionCast(function(...args) { const key = keyFn(...args); const value = cache.get(key); if (typeof value !== "undefined") return value; const newValue = f.apply(this, args); cache.set(key, newValue); return newValue; }); } const SERVER_REFERENCE_PREFIX = "$$server:"; const SERVER_DECODE_CLIENT_PREFIX = "$$decode-client:"; function removeReferenceCacheTag(id) { return id.split("$$cache=")[0]; } function setInternalRequire() { globalThis.__vite_rsc_require__ = (id) => { if (id.startsWith(SERVER_REFERENCE_PREFIX)) { id = id.slice(9); return globalThis.__vite_rsc_server_require__(id); } return globalThis.__vite_rsc_client_require__(id); }; } function getDefaultExportFromCjs(x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; } var server_edge = {}; var reactServerDomWebpackServer_edge_production = {}; var reactDom_reactServer = { exports: {} }; var reactDom_reactServer_production = {}; var react_reactServer = { exports: {} }; var react_reactServer_production = {}; var hasRequiredReact_reactServer_production; function requireReact_reactServer_production() { if (hasRequiredReact_reactServer_production) return react_reactServer_production; hasRequiredReact_reactServer_production = 1; var ReactSharedInternals = { H: null, A: null }; function formatProdErrorMessage(code) { var url = "https://react.dev/errors/" + code; if (1 < arguments.length) { url += "?args[]=" + encodeURIComponent(arguments[1]); for (var i = 2; i < arguments.length; i++) url += "&args[]=" + encodeURIComponent(arguments[i]); } return "Minified React error #" + code + "; visit " + url + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings."; } var isArrayImpl = Array.isArray; function noop() { } var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator; function getIteratorFn(maybeIterable) { if (null === maybeIterable || "object" !== typeof maybeIterable) return null; maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"]; return "function" === typeof maybeIterable ? maybeIterable : null; } var hasOwnProperty = Object.prototype.hasOwnProperty, assign = Object.assign; function ReactElement(type, key, props) { var refProp = props.ref; return { $$typeof: REACT_ELEMENT_TYPE, type, key, ref: void 0 !== refProp ? refProp : null, props }; } function cloneAndReplaceKey(oldElement, newKey) { return ReactElement(oldElement.type, newKey, oldElement.props); } function isValidElement(object) { return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE; } function escape(key) { var escaperLookup = { "=": "=0", ":": "=2" }; return "$" + key.replace(/[=:]/g, function(match) { return escaperLookup[match]; }); } var userProvidedKeyEscapeRegex = /\/+/g; function getElementKey(element, index) { return "object" === typeof element && null !== element && null != element.key ? escape("" + element.key) : index.toString(36); } function resolveThenable(thenable) { switch (thenable.status) { case "fulfilled": return thenable.value; case "rejected": throw thenable.reason; default: switch ("string" === typeof thenable.status ? thenable.then(noop, noop) : (thenable.status = "pending", thenable.then(function(fulfilledValue) { "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue); }, function(error) { "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error); })), thenable.status) { case "fulfilled": return thenable.value; case "rejected": throw thenable.reason; } } throw thenable; } function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { var type = typeof children; if ("undefined" === type || "boolean" === type) children = null; var invokeCallback = false; if (null === children) invokeCallback = true; else switch (type) { case "bigint": case "string": case "number": invokeCallback = true; break; case "object": switch (children.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: invokeCallback = true; break; case REACT_LAZY_TYPE: return invokeCallback = children._init, mapIntoArray(invokeCallback(children._payload), array, escapedPrefix, nameSoFar, callback); } } if (invokeCallback) return callback = callback(children), invokeCallback = "" === nameSoFar ? "." + getElementKey(children, 0) : nameSoFar, isArrayImpl(callback) ? (escapedPrefix = "", null != invokeCallback && (escapedPrefix = invokeCallback.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array, escapedPrefix, "", function(c) { return c; })) : null != callback && (isValidElement(callback) && (callback = cloneAndReplaceKey(callback, escapedPrefix + (null == callback.key || children && children.key === callback.key ? "" : ("" + callback.key).replace(userProvidedKeyEscapeRegex, "$&/") + "/") + invokeCallback)), array.push(callback)), 1; invokeCallback = 0; var nextNamePrefix = "" === nameSoFar ? "." : nameSoFar + ":"; if (isArrayImpl(children)) for (var i = 0; i < children.length; i++) nameSoFar = children[i], type = nextNamePrefix + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray(nameSoFar, array, escapedPrefix, type, callback); else if (i = getIteratorFn(children), "function" === typeof i) for (children = i.call(children), i = 0; !(nameSoFar = children.next()).done; ) nameSoFar = nameSoFar.value, type = nextNamePrefix + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray(nameSoFar, array, escapedPrefix, type, callback); else if ("object" === type) { if ("function" === typeof children.then) return mapIntoArray(resolveThenable(children), array, escapedPrefix, nameSoFar, callback); array = String(children); throw Error(formatProdErrorMessage(31, "[object Object]" === array ? "object with keys {" + Object.keys(children).join(", ") + "}" : array)); } return invokeCallback; } function mapChildren(children, func, context) { if (null == children) return children; var result = [], count = 0; mapIntoArray(children, result, "", "", function(child) { return func.call(context, child, count++); }); return result; } function lazyInitializer(payload) { if (-1 === payload._status) { var ctor = payload._result; ctor = ctor(); ctor.then(function(moduleObject) { if (0 === payload._status || -1 === payload._status) payload._status = 1, payload._result = moduleObject; }, function(error) { if (0 === payload._status || -1 === payload._status) payload._status = 2, payload._result = error; }); -1 === payload._status && (payload._status = 0, payload._result = ctor); } if (1 === payload._status) return payload._result.default; throw payload._result; } function createCacheRoot() { return /* @__PURE__ */ new WeakMap(); } function createCacheNode() { return { s: 0, v: void 0, o: null, p: null }; } react_reactServer_production.Children = { map: mapChildren, forEach: function(children, forEachFunc, forEachContext) { mapChildren(children, function() { forEachFunc.apply(this, arguments); }, forEachContext); }, count: function(children) { var n = 0; mapChildren(children, function() { n++; }); return n; }, toArray: function(children) { return mapChildren(children, function(child) { return child; }) || []; }, only: function(children) { if (!isValidElement(children)) throw Error(formatProdErrorMessage(143)); return children; } }; react_reactServer_production.Fragment = REACT_FRAGMENT_TYPE; react_reactServer_production.Profiler = REACT_PROFILER_TYPE; react_reactServer_production.StrictMode = REACT_STRICT_MODE_TYPE; react_reactServer_production.Suspense = REACT_SUSPENSE_TYPE; react_reactServer_production.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals; react_reactServer_production.cache = function(fn) { return function() { var dispatcher = ReactSharedInternals.A; if (!dispatcher) return fn.apply(null, arguments); var fnMap = dispatcher.getCacheForType(createCacheRoot); dispatcher = fnMap.get(fn); void 0 === dispatcher && (dispatcher = createCacheNode(), fnMap.set(fn, dispatcher)); fnMap = 0; for (var l = arguments.length; fnMap < l; fnMap++) { var arg = arguments[fnMap]; if ("function" === typeof arg || "object" === typeof arg && null !== arg) { var objectCache = dispatcher.o; null === objectCache && (dispatcher.o = objectCache = /* @__PURE__ */ new WeakMap()); dispatcher = objectCache.get(arg); void 0 === dispatcher && (dispatcher = createCacheNode(), objectCache.set(arg, dispatcher)); } else objectCache = dispatcher.p, null === objectCache && (dispatcher.p = objectCache = /* @__PURE__ */ new Map()), dispatcher = objectCache.get(arg), void 0 === dispatcher && (dispatcher = createCacheNode(), objectCache.set(arg, dispatcher)); } if (1 === dispatcher.s) return dispatcher.v; if (2 === dispatcher.s) throw dispatcher.v; try { var result = fn.apply(null, arguments); fnMap = dispatcher; fnMap.s = 1; return fnMap.v = result; } catch (error) { throw result = dispatcher, result.s = 2, result.v = error, error; } }; }; react_reactServer_production.cacheSignal = function() { var dispatcher = ReactSharedInternals.A; return dispatcher ? dispatcher.cacheSignal() : null; }; react_reactServer_production.captureOwnerStack = function() { return null; }; react_reactServer_production.cloneElement = function(element, config2, children) { if (null === element || void 0 === element) throw Error(formatProdErrorMessage(267, element)); var props = assign({}, element.props), key = element.key; if (null != config2) for (propName in void 0 !== config2.key && (key = "" + config2.key), config2) !hasOwnProperty.call(config2, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config2.ref || (props[propName] = config2[propName]); var propName = arguments.length - 2; if (1 === propName) props.children = children; else if (1 < propName) { for (var childArray = Array(propName), i = 0; i < propName; i++) childArray[i] = arguments[i + 2]; props.children = childArray; } return ReactElement(element.type, key, props); }; react_reactServer_production.createElement = function(type, config2, children) { var propName, props = {}, key = null; if (null != config2) for (propName in void 0 !== config2.key && (key = "" + config2.key), config2) hasOwnProperty.call(config2, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (props[propName] = config2[propName]); var childrenLength = arguments.length - 2; if (1 === childrenLength) props.children = children; else if (1 < childrenLength) { for (var childArray = Array(childrenLength), i = 0; i < childrenLength; i++) childArray[i] = arguments[i + 2]; props.children = childArray; } if (type && type.defaultProps) for (propName in childrenLength = type.defaultProps, childrenLength) void 0 === props[propName] && (props[propName] = childrenLength[propName]); return ReactElement(type, key, props); }; react_reactServer_production.createRef = function() { return { current: null }; }; react_reactServer_production.forwardRef = function(render) { return { $$typeof: REACT_FORWARD_REF_TYPE, render }; }; react_reactServer_production.isValidElement = isValidElement; react_reactServer_production.lazy = function(ctor) { return { $$typeof: REACT_LAZY_TYPE, _payload: { _status: -1, _result: ctor }, _init: lazyInitializer }; }; react_reactServer_production.memo = function(type, compare) { return { $$typeof: REACT_MEMO_TYPE, type, compare: void 0 === compare ? null : compare }; }; react_reactServer_production.use = function(usable) { return ReactSharedInternals.H.use(usable); }; react_reactServer_production.useCallback = function(callback, deps) { return ReactSharedInternals.H.useCallback(callback, deps); }; react_reactServer_production.useDebugValue = function() { }; react_reactServer_production.useId = function() { return ReactSharedInternals.H.useId(); }; react_reactServer_production.useMemo = function(create, deps) { return ReactSharedInternals.H.useMemo(create, deps); }; react_reactServer_production.version = "19.2.4"; return react_reactServer_production; } var hasRequiredReact_reactServer; function requireReact_reactServer() { if (hasRequiredReact_reactServer) return react_reactServer.exports; hasRequiredReact_reactServer = 1; { react_reactServer.exports = requireReact_reactServer_production(); } return react_reactServer.exports; } var hasRequiredReactDom_reactServer_production; function requireReactDom_reactServer_production() { if (hasRequiredReactDom_reactServer_production) return reactDom_reactServer_production; hasRequiredReactDom_reactServer_production = 1; var React = requireReact_reactServer(); function noop() { } var Internals = { d: { f: noop, r: function() { throw Error("Invalid form element. requestFormReset must be passed a form that was rendered by React."); }, D: noop, C: noop, L: noop, m: noop, X: noop, S: noop, M: noop }, p: 0, findDOMNode: null }; if (!React.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE) throw Error('The "react" package in this environment is not configured correctly. The "react-server" condition must be enabled in any environment that runs React Server Components.'); function getCrossOriginStringAs(as, input) { if ("font" === as) return ""; if ("string" === typeof input) return "use-credentials" === input ? input : ""; } reactDom_reactServer_production.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = Internals; reactDom_reactServer_production.preconnect = function(href, options) { "string" === typeof href && (options ? (options = options.crossOrigin, options = "string" === typeof options ? "use-credentials" === options ? options : "" : void 0) : options = null, Internals.d.C(href, options)); }; reactDom_reactServer_production.prefetchDNS = function(href) { "string" === typeof href && Internals.d.D(href); }; reactDom_reactServer_production.preinit = function(href, options) { if ("string" === typeof href && options && "string" === typeof options.as) { var as = options.as, crossOrigin = getCrossOriginStringAs(as, options.crossOrigin), integrity = "string" === typeof options.integrity ? options.integrity : void 0, fetchPriority = "string" === typeof options.fetchPriority ? options.fetchPriority : void 0; "style" === as ? Internals.d.S(href, "string" === typeof options.precedence ? options.precedence : void 0, { crossOrigin, integrity, fetchPriority }) : "script" === as && Internals.d.X(href, { crossOrigin, integrity, fetchPriority, nonce: "string" === typeof options.nonce ? options.nonce : void 0 }); } }; reactDom_reactServer_production.preinitModule = function(href, options) { if ("string" === typeof href) if ("object" === typeof options && null !== options) { if (null == options.as || "script" === options.as) { var crossOrigin = getCrossOriginStringAs(options.as, options.crossOrigin); Internals.d.M(href, { crossOrigin, integrity: "string" === typeof options.integrity ? options.integrity : void 0, nonce: "string" === typeof options.nonce ? options.nonce : void 0 }); } } else null == options && Internals.d.M(href); }; reactDom_reactServer_production.preload = function(href, options) { if ("string" === typeof href && "object" === typeof options && null !== options && "string" === typeof options.as) { var as = options.as, crossOrigin = getCrossOriginStringAs(as, options.crossOrigin); Internals.d.L(href, as, { crossOrigin, integrity: "string" === typeof options.integrity ? options.integrity : void 0, nonce: "string" === typeof options.nonce ? options.nonce : void 0, type: "string" === typeof options.type ? options.type : void 0, fetchPriority: "string" === typeof options.fetchPriority ? options.fetchPriority : void 0, referrerPolicy: "string" === typeof options.referrerPolicy ? options.referrerPolicy : void 0, imageSrcSet: "string" === typeof options.imageSrcSet ? options.imageSrcSet : void 0, imageSizes: "string" === typeof options.imageSizes ? options.imageSizes : void 0, media: "string" === typeof options.media ? options.media : void 0 }); } }; reactDom_reactServer_production.preloadModule = function(href, options) { if ("string" === typeof href) if (options) { var crossOrigin = getCrossOriginStringAs(options.as, options.crossOrigin); Internals.d.m(href, { as: "string" === typeof options.as && "script" !== options.as ? options.as : void 0, crossOrigin, integrity: "string" === typeof options.integrity ? options.integrity : void 0 }); } else Internals.d.m(href); }; reactDom_reactServer_production.version = "19.2.4"; return reactDom_reactServer_production; } var hasRequiredReactDom_reactServer; function requireReactDom_reactServer() { if (hasRequiredReactDom_reactServer) return reactDom_reactServer.exports; hasRequiredReactDom_reactServer = 1; { reactDom_reactServer.exports = requireReactDom_reactServer_production(); } return reactDom_reactServer.exports; } var hasRequiredReactServerDomWebpackServer_edge_production; function requireReactServerDomWebpackServer_edge_production() { if (hasRequiredReactServerDomWebpackServer_edge_production) return reactServerDomWebpackServer_edge_production; hasRequiredReactServerDomWebpackServer_edge_production = 1; const __viteRscAsyncHooks = require$$0; globalThis.AsyncLocalStorage = __viteRscAsyncHooks.AsyncLocalStorage; var ReactDOM = requireReactDom_reactServer(), React = requireReact_reactServer(), REACT_LEGACY_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.element"), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_MEMO_CACHE_SENTINEL = /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel"); var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; function getIteratorFn(maybeIterable) { if (null === maybeIterable || "object" !== typeof maybeIterable) return null; maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"]; return "function" === typeof maybeIterable ? maybeIterable : null; } var ASYNC_ITERATOR = Symbol.asyncIterator; function handleErrorInNextTick(error) { setTimeout(function() { throw error; }); } var LocalPromise = Promise, scheduleMicrotask = "function" === typeof queueMicrotask ? queueMicrotask : function(callback) { LocalPromise.resolve(null).then(callback).catch(handleErrorInNextTick); }, currentView = null, writtenBytes = 0; function writeChunkAndReturn(destination, chunk) { if (0 !== chunk.byteLength) if (2048 < chunk.byteLength) 0 < writtenBytes && (destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes)), currentView = new Uint8Array(2048), writtenBytes = 0), destination.enqueue(chunk); else { var allowableBytes = currentView.length - writtenBytes; allowableBytes < chunk.byteLength && (0 === allowableBytes ? destination.enqueue(currentView) : (currentView.set(chunk.subarray(0, allowableBytes), writtenBytes), destination.enqueue(currentView), chunk = chunk.subarray(allowableBytes)), currentView = new Uint8Array(2048), writtenBytes = 0); currentView.set(chunk, writtenBytes); writtenBytes += chunk.byteLength; } return true; } var textEncoder = new TextEncoder(); function stringToChunk(content) { return textEncoder.encode(content); } function byteLengthOfChunk(chunk) { return chunk.byteLength; } function closeWithError(destination, error) { "function" === typeof destination.error ? destination.error(error) : destination.close(); } var CLIENT_REFERENCE_TAG$1 = /* @__PURE__ */ Symbol.for("react.client.reference"), SERVER_REFERENCE_TAG = /* @__PURE__ */ Symbol.for("react.server.reference"); function registerClientReferenceImpl(proxyImplementation, id, async) { return Object.defineProperties(proxyImplementation, { $$typeof: { value: CLIENT_REFERENCE_TAG$1 }, $$id: { value: id }, $$async: { value: async } }); } var FunctionBind = Function.prototype.bind, ArraySlice = Array.prototype.slice; function bind() { var newFn = FunctionBind.apply(this, arguments); if (this.$$typeof === SERVER_REFERENCE_TAG) { var args = ArraySlice.call(arguments, 1), $$typeof = { value: SERVER_REFERENCE_TAG }, $$id = { value: this.$$id }; args = { value: this.$$bound ? this.$$bound.concat(args) : args }; return Object.defineProperties(newFn, { $$typeof, $$id, $$bound: args, bind: { value: bind, configurable: true } }); } return newFn; } var serverReferenceToString = { value: function() { return "function () { [omitted code] }"; }, configurable: true, writable: true }, PROMISE_PROTOTYPE = Promise.prototype, deepProxyHandlers = { get: function(target, name) { switch (name) { case "$$typeof": return target.$$typeof; case "$$id": return target.$$id; case "$$async": return target.$$async; case "name": return target.name; case "displayName": return; case "defaultProps": return; case "_debugInfo": return; case "toJSON": return; case Symbol.toPrimitive: return Object.prototype[Symbol.toPrimitive]; case Symbol.toStringTag: return Object.prototype[Symbol.toStringTag]; case "Provider": throw Error("Cannot render a Client Context Provider on the Server. Instead, you can export a Client Component wrapper that itself renders a Client Context Provider."); case "then": throw Error("Cannot await or return from a thenable. You cannot await a client module from a server component."); } throw Error("Cannot access " + (String(target.name) + "." + String(name)) + " on the server. You cannot dot into a client module from a server component. You can only pass the imported name through."); }, set: function() { throw Error("Cannot assign to a client module from a server module."); } }; function getReference(target, name) { switch (name) { case "$$typeof": return target.$$typeof; case "$$id": return target.$$id; case "$$async": return target.$$async; case "name": return target.name; case "defaultProps": return; case "_debugInfo": return; case "toJSON": return; case Symbol.toPrimitive: return Object.prototype[Symbol.toPrimitive]; case Symbol.toStringTag: return Object.prototype[Symbol.toStringTag]; case "__esModule": var moduleId = target.$$id; target.default = registerClientReferenceImpl(function() { throw Error("Attempted to call the default export of " + moduleId + " from the server but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component."); }, target.$$id + "#", target.$$async); return true; case "then": if (target.then) return target.then; if (target.$$async) return; var clientReference = registerClientReferenceImpl({}, target.$$id, true), proxy = new Proxy(clientReference, proxyHandlers$1); target.status = "fulfilled"; target.value = proxy; return target.then = registerClientReferenceImpl(function(resolve) { return Promise.resolve(resolve(proxy)); }, target.$$id + "#then", false); } if ("symbol" === typeof name) throw Error("Cannot read Symbol exports. Only named exports are supported on a client module imported on the server."); clientReference = target[name]; clientReference || (clientReference = registerClientReferenceImpl(function() { throw Error("Attempted to call " + String(name) + "() from the server but " + String(name) + " is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component."); }, target.$$id + "#" + name, target.$$async), Object.defineProperty(clientReference, "name", { value: name }), clientReference = target[name] = new Proxy(clientReference, deepProxyHandlers)); return clientReference; } var proxyHandlers$1 = { get: function(target, name) { return getReference(target, name); }, getOwnPropertyDescriptor: function(target, name) { var descriptor = Object.getOwnPropertyDescriptor(target, name); descriptor || (descriptor = { value: getReference(target, name), writable: false, configurable: false, enumerable: false }, Object.defineProperty(target, name, descriptor)); return descriptor; }, getPrototypeOf: function() { return PROMISE_PROTOTYPE; }, set: function() { throw Error("Cannot assign to a client module from a server module."); } }, ReactDOMSharedInternals = ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, previousDispatcher = ReactDOMSharedInternals.d; ReactDOMSharedInternals.d = { f: previousDispatcher.f, r: previousDispatcher.r, D: prefetchDNS, C: preconnect, L: preload, m: preloadModule$1, X: preinitScript, S: preinitStyle, M: preinitModuleScript }; function prefetchDNS(href) { if ("string" === typeof href && href) { var request = resolveRequest(); if (request) { var hints = request.hints, key = "D|" + href; hints.has(key) || (hints.add(key), emitHint(request, "D", href)); } else previousDispatcher.D(href); } } function preconnect(href, crossOrigin) { if ("string" === typeof href) { var request = resolveRequest(); if (request) { var hints = request.hints, key = "C|" + (null == crossOrigin ? "null" : crossOrigin) + "|" + href; hints.has(key) || (hints.add(key), "string" === typeof crossOrigin ? emitHint(request, "C", [ href, crossOrigin ]) : emitHint(request, "C", href)); } else previousDispatcher.C(href, crossOrigin); } } function preload(href, as, options) { if ("string" === typeof href) { var request = resolveRequest(); if (request) { var hints = request.hints, key = "L"; if ("image" === as && options) { var imageSrcSet = options.imageSrcSet, imageSizes = options.imageSizes, uniquePart = ""; "string" === typeof imageSrcSet && "" !== imageSrcSet ? (uniquePart += "[" + imageSrcSet + "]", "string" === typeof imageSizes && (uniquePart += "[" + imageSizes + "]")) : uniquePart += "[][]" + href; key += "[image]" + uniquePart; } else key += "[" + as + "]" + href; hints.has(key) || (hints.add(key), (options = trimOptions(options)) ? emitHint(request, "L", [ href, as, options ]) : emitHint(request, "L", [ href, as ])); } else previousDispatcher.L(href, as, options); } } function preloadModule$1(href, options) { if ("string" === typeof href) { var request = resolveRequest(); if (request) { var hints = request.hints, key = "m|" + href; if (hints.has(key)) return; hints.add(key); return (options = trimOptions(options)) ? emitHint(request, "m", [ href, options ]) : emitHint(request, "m", href); } previousDispatcher.m(href, options); } } function preinitStyle(href, precedence, options) { if ("string" === typeof href) { var request = resolveRequest(); if (request) { var hints = request.hints, key = "S|" + href; if (hints.has(key)) return; hints.add(key); return (options = trimOptions(options)) ? emitHint(request, "S", [ href, "string" === typeof precedence ? precedence : 0, options ]) : "string" === typeof precedence ? emitHint(request, "S", [ href, precedence ]) : emitHint(request, "S", href); } previousDispatcher.S(href, precedence, options); } } function preinitScript(src, options) { if ("string" === typeof src) { var request = resolveRequest(); if (request) { var hints = request.hints, key = "X|" + src; if (hints.has(key)) return; hints.add(key); return (options = trimOptions(options)) ? emitHint(request, "X", [ src, options ]) : emitHint(request, "X", src); } previousDispatcher.X(src, options); } } function preinitModuleScript(src, options) { if ("string" === typeof src) { var request = resolveRequest(); if (request) { var hints = request.hints, key = "M|" + src; if (hints.has(key)) return; hints.add(key); return (options = trimOptions(options)) ? emitHint(request, "M", [ src, options ]) : emitHint(request, "M", src); } previousDispatcher.M(src, options); } } function trimOptions(options) { if (null == options) return null; var hasProperties = false, trimmed = {}, key; for (key in options) null != options[key] && (hasProperties = true, trimmed[key] = options[key]); return hasProperties ? trimmed : null; } function getChildFormatContext(parentContext, type, props) { switch (type) { case "img": type = props.src; var srcSet = props.srcSet; if (!("lazy" === props.loading || !type && !srcSet || "string" !== typeof type && null != type || "string" !== typeof srcSet && null != srcSet || "low" === props.fetchPriority || parentContext & 3) && ("string" !== typeof type || ":" !== type[4] || "d" !== type[0] && "D" !== type[0] || "a" !== type[1] && "A" !== type[1] || "t" !== type[2] && "T" !== type[2] || "a" !== type[3] && "A" !== type[3]) && ("string" !== typeof srcSet || ":" !== srcSet[4] || "d" !== srcSet[0] && "D" !== srcSet[0] || "a" !== srcSet[1] && "A" !== srcSet[1] || "t" !== srcSet[2] && "T" !== srcSet[2] || "a" !== srcSet[3] && "A" !== srcSet[3])) { var sizes = "string" === typeof props.sizes ? props.sizes : void 0; var input = props.crossOrigin; preload(type || "", "image", { imageSrcSet: srcSet, imageSizes: sizes, crossOrigin: "string" === typeof input ? "use-credentials" === input ? input : "" : void 0, integrity: props.integrity, type: props.type, fetchPriority: props.fetchPriority, referrerPolicy: props.referrerPolicy }); } return parentContext; case "link": type = props.rel; srcSet = props.href; if (!(parentContext & 1 || null != props.itemProp || "string" !== typeof type || "string" !== typeof srcSet || "" === srcSet)) switch (type) { case "preload": preload(srcSet, props.as, { crossOrigin: props.crossOrigin, integrity: props.integrity, nonce: props.nonce, type: props.type, fetchPriority: props.fetchPriority, referrerPolicy: props.referrerPolicy, imageSrcSet: props.imageSrcSet, imageSizes: props.imageSizes, media: props.media }); break; case "modulepreload": preloadModule$1(srcSet, { as: props.as, crossOrigin: props.crossOrigin, integrity: props.integrity, nonce: props.nonce }); break; case "stylesheet": preload(srcSet, "stylesheet", { crossOrigin: props.crossOrigin, integrity: props.integrity, nonce: props.nonce, type: props.type, fetchPriority: props.fetchPriority, referrerPolicy: props.referrerPolicy, media: props.media }); } return parentContext; case "picture": return parentContext | 2; case "noscript": return parentContext | 1; default: return parentContext; } } var supportsRequestStorage = "function" === typeof AsyncLocalStorage, requestStorage = supportsRequestStorage ? new AsyncLocalStorage() : null, TEMPORARY_REFERENCE_TAG = /* @__PURE__ */ Symbol.for("react.temporary.reference"), proxyHandlers = { get: function(target, name) { switch (name) { case "$$typeof": return target.$$typeof; case "name": return; case "displayName": return; case "defaultProps": return; case "_debugInfo": return; case "toJSON": return; case Symbol.toPrimitive: return Object.prototype[Symbol.toPrimitive]; case Symbol.toStringTag: return Object.prototype[Symbol.toStringTag]; case "Provider": throw Error("Cannot render a Client Context Provider on the Server. Instead, you can export a Client Component wrapper that itself renders a Client Context Provider."); case "then": return; } throw Error("Cannot access " + String(name) + " on the server. You cannot dot into a temporary client reference from a server component. You can only pass the value through to the client."); }, set: function() { throw Error("Cannot assign to a temporary client reference from a server module."); } }; function createTemporaryReference(temporaryReferences, id) { var reference = Object.defineProperties(function() { throw Error("Attempted to call a temporary Client Reference from the server but it is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component."); }, { $$typeof: { value: TEMPORARY_REFERENCE_TAG } }); reference = new Proxy(reference, proxyHandlers); temporaryReferences.set(reference, id); return reference; } function noop() { } var SuspenseException = Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`."); function trackUsedThenable(thenableState2, thenable, index) { index = thenableState2[index]; void 0 === index ? thenableState2.push(thenable) : index !== thenable && (thenable.then(noop, noop), thenable = index); switch (thenable.status) { case "fulfilled": return thenable.value; case "rejected": throw thenable.reason; default: "string" === typeof thenable.status ? thenable.then(noop, noop) : (thenableState2 = thenable, thenableState2.status = "pending", thenableState2.then(function(fulfilledValue) { if ("pending" === thenable.status) { var fulfilledThenable = thenable; fulfilledThenable.status = "fulfilled"; fulfilledThenable.value = fulfilledValue; } }, function(error) { if ("pending" === thenable.status) { var rejectedThenable = thenable; rejectedThenable.status = "rejected"; rejectedThenable.reason = error; } })); switch (thenable.status) { case "fulfilled": return thenable.value; case "rejected": throw thenable.reason; } suspendedThenable = thenable; throw SuspenseException; } } var suspendedThenable = null; function getSuspendedThenable() { if (null === suspendedThenable) throw Error("Expected a suspended thenable. This is a bug in React. Please file an issue."); var thenable = suspendedThenable; suspendedThenable = null; return thenable; } var currentRequest$1 = null, thenableIndexCounter = 0, thenableState = null; function getThenableStateAfterSuspending() { var state = thenableState || []; thenableState = null; return state; } var HooksDispatcher = { readContext: unsupportedContext, use, useCallback: function(callback) { return callback; }, useContext: unsupportedContext, useEffect: unsupportedHook, useImperativeHandle: unsupportedHook, useLayoutEffect: unsupportedHook, useInsertionEffect: unsupportedHook, useMemo: function(nextCreate) { return nextCreate(); }, useReducer: unsupportedHook, useRef: unsupportedHook, useState: unsupportedHook, useDebugValue: function() { }, useDeferredValue: unsupportedHook, useTransition: unsupportedHook, useSyncExternalStore: unsupportedHook, useId, useHostTransitionStatus: unsupportedHook, useFormState: unsupportedHook, useActionState: unsupportedHook, useOptimistic: unsupportedHook, useMemoCache: function(size) { for (var data = Array(size), i = 0; i < size; i++) data[i] = REACT_MEMO_CACHE_SENTINEL; return data; }, useCacheRefresh: function() { return unsupportedRefresh; } }; HooksDispatcher.useEffectEvent = unsupportedHook; function unsupportedHook() { throw Error("This Hook is not supported in Server Components."); } function unsupportedRefresh() { throw Error("Refreshing the cache is not supported in Server Components."); } function unsupportedContext() { throw Error("Cannot read a Client Context from a Server Component."); } function useId() { if (null === currentRequest$1) throw Error("useId can only be used while React is rendering"); var id = currentRequest$1.identifierCount++; return "_" + currentRequest$1.identifierPrefix + "S_" + id.toString(32) + "_"; } function use(usable) { if (null !== usable && "object" === typeof usable || "function" === typeof usable) { if ("function" === typeof usable.then) { var index = thenableIndexCounter; thenableIndexCounter += 1; null === thenableState && (thenableState = []); return trackUsedThenable(thenableState, usable, index); } usable.$$typeof === REACT_CONTEXT_TYPE && unsupportedContext(); } if (usable.$$typeof === CLIENT_REFERENCE_TAG$1) { if (null != usable.value && usable.value.$$typeof === REACT_CONTEXT_TYPE) throw Error("Cannot read a Client Context from a Server Component."); throw Error("Cannot use() an already resolved Client Reference."); } throw Error("An unsupported type was passed to use(): " + String(usable)); } var DefaultAsyncDispatcher = { getCacheForType: function(resourceType) { var JSCompiler_inline_result = (JSCompiler_inline_result = resolveRequest()) ? JSCompiler_inline_result.cache : /* @__PURE__ */ new Map(); var entry = JSCompiler_inline_result.get(resourceType); void 0 === entry && (entry = resourceType(), JSCompiler_inline_result.set(resourceType, entry)); return entry; }, cacheSignal: function() { var request = resolveRequest(); return request ? request.cacheController.signal : null; } }, ReactSharedInternalsServer = React.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE; if (!ReactSharedInternalsServer) throw Error('The "react" package in this environment is not configured correctly. The "react-server" condition must be enabled in any environment that runs React Server Components.'); var isArrayImpl = Array.isArray, getPrototypeOf = Object.getPrototypeOf; function objectName(object) { object = Object.prototype.toString.call(object); return object.slice(8, object.length - 1); } function describeValueForErrorMessage(value) { switch (typeof value) { case "string": return JSON.stringify(10 >= value.length ? value : value.slice(0, 10) + "..."); case "object": if (isArrayImpl(value)) return "[...]"; if (null !== value && value.$$typeof === CLIENT_REFERENCE_TAG) return "client"; value = objectName(value); return "Object" === value ? "{...}" : value; case "function": return value.$$typeof === CLIENT_REFERENCE_TAG ? "client" : (value = value.displayName || value.name) ? "function " + value : "function"; default: return String(value); } } function describeElementType(type) { if ("string" === typeof type) return type; switch (type) { case REACT_SUSPENSE_TYPE: return "Suspense"; case REACT_SUSPENSE_LIST_TYPE: return "SuspenseList"; } if ("object" === typeof type) switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeElementType(type.render); case REACT_MEMO_TYPE: return describeElementType(type.type); case REACT_LAZY_TYPE: var payload = type._payload; type = type._init; try { return describeElementType(type(payload)); } catch (x) { } } return ""; } var CLIENT_REFERENCE_TAG = /* @__PURE__ */ Symbol.for("react.client.reference"); function describeObjectForErrorMessage(objectOrArray, expandedName) { var objKind = objectName(objectOrArray); if ("Object" !== objKind && "Array" !== objKind) return objKind; objKind = -1; var length = 0; if (isArrayImpl(objectOrArray)) { var str = "["; for (var i = 0; i < objectOrArray.length; i++) { 0 < i && (str += ", "); var value = objectOrArray[i]; value = "object" === typeof value && null !== value ? describeObjectForErrorMessage(value) : describeValueForErrorMessage(value); "" + i === expandedName ? (objKind = str.length, length = value.length, str += value) : str = 10 > value.length && 40 > str.length + value.length ? str + value : str + "..."; } str += "]"; } else if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) str = "<" + describeElementType(objectOrArray.type) + "/>"; else { if (objectOrArray.$$typeof === CLIENT_REFERENCE_TAG) return "client"; str = "{"; i = Object.keys(objectOrArray); for (value = 0; value < i.length; value++) { 0 < value && (str += ", "); var name = i[value], encodedKey = JSON.stringify(name); str += ('"' + name + '"' === encodedKey ? name : encodedKey) + ": "; encodedKey = objectOrArray[name]; encodedKey = "object" === typeof encodedKey && null !== encodedKey ? describeObjectForErrorMessage(encodedKey) : describeValueForErrorMessage(encodedKey); name === expandedName ? (objKind = str.length, length = encodedKey.length, str += encodedKey) : str = 10 > encodedKey.length && 40 > str.length + encodedKey.length ? str + encodedKey : str + "..."; } str += "}"; } return void 0 === expandedName ? str : -1 < objKind && 0 < length ? (objectOrArray = " ".repeat(objKind) + "^".repeat(length), "\n " + str + "\n " + objectOrArray) : "\n " + str; } var hasOwnProperty = Object.prototype.hasOwnProperty, ObjectPrototype$1 = Object.prototype, stringify = JSON.stringify; function defaultErrorHandler(error) { console.error(error); } function RequestInstance(type, model, bundlerConfig, onError, onPostpone, onAllReady, onFatalError, identifierPrefix, temporaryReferences) { if (null !== ReactSharedInternalsServer.A && ReactSharedInternalsServer.A !== DefaultAsyncDispatcher) throw Error("Currently React only supports one RSC renderer at a time."); ReactSharedInternalsServer.A = DefaultAsyncDispatcher; var abortSet = /* @__PURE__ */ new Set(), pingedTasks = [], hints = /* @__PURE__ */ new Set(); this.type = type; this.status = 10; this.flushScheduled = false; this.destination = this.fatalError = null; this.bundlerConfig = bundlerConfig; this.cache = /* @__PURE__ */ new Map(); this.cacheController = new AbortController(); this.pendingChunks = this.nextChunkId = 0; this.hints = hints; this.abortableTasks = abortSet; this.pingedTasks = pingedTasks; this.completedImportChunks = []; this.completedHintChunks = []; this.completedRegularChunks = []; this.completedErrorChunks = []; this.writtenSymbols = /* @__PURE__ */ new Map(); this.writtenClientReferences = /* @__PURE__ */ new Map(); this.writtenServerReferences = /* @__PURE__ */ new Map(); this.writtenObjects = /* @__PURE__ */ new WeakMap(); this.temporaryReferences = temporaryReferences; this.identifierPrefix = identifierPrefix || ""; this.identifierCount = 1; this.taintCleanupQueue = []; this.onError = void 0 === onError ? defaultErrorHandler : onError; this.onPostpone = void 0 === onPostpone ? noop : onPostpone; this.onAllReady = onAllReady; this.onFatalError = onFatalError; type = createTask(this, model, null, false, 0, abortSet); pingedTasks.push(type); } var currentRequest = null; function resolveRequest() { if (currentRequest) return currentRequest; if (supportsRequestStorage) { var store = requestStorage.getStore(); if (store) return store; } return null; } function serializeThenable(request, task, thenable) { var newTask = createTask(request, thenable, task.keyPath, task.implicitSlot, task.formatContext, request.abortableTasks); switch (thenable.status) { case "fulfilled": return newTask.model = thenable.value, pingTask(request, newTask), newTask.id; case "rejected": return erroredTask(request, newTask, thenable.reason), newTask.id; default: if (12 === request.status) return request.abortableTasks.delete(newTask), 21 === request.type ? (haltTask(newTask), finishHaltedTask(newTask, request)) : (task = request.fatalError, abortTask(newTask), finishAbortedTask(newTask, request, task)), newTask.id; "string" !== typeof thenable.status && (thenable.status = "pending", thenable.then(function(fulfilledValue) { "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue); }, function(error) { "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error); })); } thenable.then(function(value) { newTask.model = value; pingTask(request, newTask); }, function(reason) { 0 === newTask.status && (erroredTask(request, newTask, reason), enqueueFlush(request)); }); return newTask.id; } function serializeReadableStream(request, task, stream) { function progress(entry) { if (0 === streamTask.status) if (entry.done) streamTask.status = 1, entry = streamTask.id.toString(16) + ":C\n", request.completedRegularChunks.push(stringToChunk(entry)), request.abortableTasks.delete(streamTask), request.cacheController.signal.removeEventListener("abort", abortStream), enqueueFlush(request), callOnAllReadyIfReady(request); else try { streamTask.model = entry.value, request.pendingChunks++, tryStreamTask(request, streamTask), enqueueFlush(request), reader.read().then(progress, error); } catch (x$11) { error(x$11); } } function error(reason) { 0 === streamTask.status && (request.cacheController.signal.removeEventListener("abort", abortStream), erroredTask(request, streamTask, reason), enqueueFlush(request), reader.cancel(reason).then(error, error)); } function abortStream() { if (0 === streamTask.status) { var signal = request.cacheController.signal; signal.removeEventListener("abort", abortStream); signal = signal.reason; 21 === request.type ? (request.abortableTasks.delete(streamTask), haltTask(streamTask), finishHaltedTask(streamTask, request)) : (erroredTask(request, streamTask, signal), enqueueFlush(request)); reader.cancel(signal).then(error, error); } } var supportsBYOB = stream.supportsBYOB; if (void 0 === supportsBYOB) try { stream.getReader({ mode: "byob" }).releaseLock(), supportsBYOB = true; } catch (x) { supportsBYOB = false; } var reader = stream.getReader(), streamTask = createTask(request, task.model, task.keyPath, task.implicitSlot, task.formatContext, request.abortableTasks); request.pendingChunks++; task = streamTask.id.toString(16) + ":" + (supportsBYOB ? "r" : "R") + "\n"; request.completedRegularChunks.push(stringToChunk(task)); request.cacheController.signal.addEventListener("abort", abortStream); reader.read().then(progress, error); return serializeByValueID(streamTask.id); } function serializeAsyncIterable(request, task, iterable, iterator) { function progress(entry) { if (0 === streamTask.status) if (entry.done) { streamTask.status = 1; if (void 0 === entry.value) var endStreamRow = streamTask.id.toString(16) + ":C\n"; else try { var chunkId = outlineModelWithFormatContext(request, entry.value, 0); endStreamRow = streamTask.id.toString(16) + ":C" + stringify(serializeByValueID(chunkId)) + "\n"; } catch (x) { error(x); return; } request.completedRegularChunks.push(stringToChunk(endStreamRow)); request.abortableTasks.delete(streamTask); request.cacheController.signal.removeEventListener("abort", abortIterable); enqueueFlush(request); callOnAllReadyIfReady(request); } else try { streamTask.model = entry.value, request.pendingChunks++, tryStreamTask(request, streamTask), enqueueFlush(request), iterator.next().then(progress, error); } catch (x$12) { error(x$12); } } function error(reason) { 0 === streamTask.status && (request.cacheController.signal.removeEventListener("abort", abortIterable), erroredTask(request, streamTask, reason), enqueueFlush(request), "function" === typeof iterator.throw && iterator.throw(reason).then(error, error)); } function abortIterable() { if (0 === streamTask.status) { var signal = request.cacheController.signal; signal.removeEventListener("abort", abortIterable); var reason = signal.reason; 21 === request.type ? (request.abortableTasks.delete(streamTask), haltTask(streamTask), finishHaltedTask(streamTask, request)) : (erroredTask(request, streamTask, signal.reason), enqueueFlush(request)); "function" === typeof iterator.throw && iterator.throw(reason).then(error, error); } } iterable = iterable === iterator; var streamTask = createTask(request, task.model, task.keyPath, task.implicitSlot, task.formatContext, request.abortableTasks); request.pendingChunks++; task = streamTask.id.toString(16) + ":" + (iterable ? "x" : "X") + "\n"; request.completedRegularChunks.push(stringToChunk(task)); request.cacheController.signal.addEventListener("abort", abortIterable); iterator.next().then(progress, error); return serializeByValueID(streamTask.id); } function emitHint(request, code, model) { model = stringify(model); code = stringToChunk(":H" + code + model + "\n"); request.completedHintChunks.push(code); enqueueFlush(request); } function readThenable(thenable) { if ("fulfilled" === thenable.status) return thenable.value; if ("rejected" === thenable.status) throw thenable.reason; throw thenable; } function createLazyWrapperAroundWakeable(request, task, wakeable) { switch (wakeable.status) { case "fulfilled": return wakeable.value; case "rejected": break; default: "string" !== typeof wakeable.status && (wakeable.status = "pending", wakeable.then(function(fulfilledValue) { "pending" === wakeable.status && (wakeable.status = "fulfilled", wakeable.value = fulfilledValue); }, function(error) { "pending" === wakeable.status && (wakeable.status = "rejected", wakeable.reason = error); })); } return { $$typeof: REACT_LAZY_TYPE, _payload: wakeable, _init: readThenable }; } function voidHandler() { } function processServerComponentReturnValue(request, task, Component, result) { if ("object" !== typeof result || null === result || result.$$typeof === CLIENT_REFERENCE_TAG$1) return result; if ("function" === typeof result.then) return createLazyWrapperAroundWakeable(request, task, result); var iteratorFn = getIteratorFn(result); return iteratorFn ? (request = {}, request[Symbol.iterator] = function() { return iteratorFn.call(result); }, request) : "function" !== typeof result[ASYNC_ITERATOR] || "function" === typeof ReadableStream && result instanceof ReadableStream ? result : (request = {}, request[ASYNC_ITERATOR] = function() { return result[ASYNC_ITERATOR](); }, request); } function renderFunctionComponent(request, task, key, Component, props) { var prevThenableState = task.thenableState; task.thenableState = null; thenableIndexCounter = 0; thenableState = prevThenableState; props = Component(props, void 0); if (12 === request.status) throw "object" === typeof props && null !== props && "function" === typeof props.then && props.$$typeof !== CLIENT_REFERENCE_TAG$1 && props.then(voidHandler, voidHandler), null; props = processServerComponentReturnValue(request, task, Component, props); Component = task.keyPath; prevThenableState = task.implicitSlot; null !== key ? task.keyPath = null === Component ? key : Component + "," + key : null === Component && (task.implicitSlot = true); request = renderModelDestructive(request, task, emptyRoot, "", props); task.keyPath = Component; task.implicitSlot = prevThenableState; return request; } function renderFragment(request, task, children) { return null !== task.keyPath ? (request = [ REACT_ELEMENT_TYPE, REACT_FRAGMENT_TYPE, task.keyPath, { children } ], task.implicitSlot ? [ request ] : request) : children; } var serializedSize = 0; function deferTask(request, task) { task = createTask(request, task.model, task.keyPath, task.implicitSlot, task.formatContext, request.abortableTasks); pingTask(request, task); return serializeLazyID(task.id); } function renderElement(request, task, type, key, ref, props) { if (null !== ref && void 0 !== ref) throw Error("Refs cannot be used in Server Components, nor passed to Client Components."); if ("function" === typeof type && type.$$typeof !== CLIENT_REFERENCE_TAG$1 && type.$$typeof !== TEMPORARY_REFERENCE_TAG) return renderFunctionComponent(request, task, key, type, props); if (type === REACT_FRAGMENT_TYPE && null === key) return type = task.implicitSlot, null === task.keyPath && (task.implicitSlot = true), props = renderModelDestructive(request, task, emptyRoot, "", props.children), task.implicitSlot = type, props; if (null != type && "object" === typeof type && type.$$typeof !== CLIENT_REFERENCE_TAG$1) switch (type.$$typeof) { case REACT_LAZY_TYPE: var init2 = type._init; type = init2(type._payload); if (12 === request.status) throw null; return renderElement(request, task, type, key, ref, props); case REACT_FORWARD_REF_TYPE: return renderFunctionComponent(request, task, key, type.render, props); case REACT_MEMO_TYPE: return renderElement(request, task, type.type, key, ref, props); } else "string" === typeof type && (ref = task.formatContext, init2 = getChildFormatContext(ref, type, props), ref !== init2 && null != props.children && outlineModelWithFormatContext(request, props.children, init2)); request = key; key = task.keyPath; null === request ? request = key : null !== key && (request = key + "," + request); props = [ REACT_ELEMENT_TYPE, type, request, props ]; task = task.implicitSlot && null !== request ? [ props ] : props; return task; } function pingTask(request, task) { var pingedTasks = request.pingedTasks; pingedTasks.push(task); 1 === pingedTasks.length && (request.flushScheduled = null !== request.destination, 21 === request.type || 10 === request.status ? scheduleMicrotask(function() { return performWork(request); }) : setTimeout(function() { return performWork(request); }, 0)); } function createTask(request, model, keyPath, implicitSlot, formatContext, abortSet) { request.pendingChunks++; var id = request.nextChunkId++; "object" !== typeof model || null === model || null !== keyPath || implicitSlot || request.writtenObjects.set(model, serializeByValueID(id)); var task = { id, status: 0, model, keyPath, implicitSlot, formatContext, ping: function() { return pingTask(request, task); }, toJSON: function(parentPropertyName, value) { serializedSize += parentPropertyName.length; var prevKeyPath = task.keyPath, prevImplicitSlot = task.implicitSlot; try { var JSCompiler_inline_result = renderModelDestructive(request, task, this, parentPropertyName, value); } catch (thrownValue) { if (parentPropertyName = task.model, parentPropertyName = "object" === typeof parentPropertyName && null !== parentPropertyName && (parentPropertyName.$$typeof === REACT_ELEMENT_TYPE || parentPropertyName.$$typeof === REACT_LAZY_TYPE), 12 === request.status) task.status = 3, 21 === request.type ? (prevKeyPath = request.nextChunkId++, prevKeyPath = parentPropertyName ? serializeLazyID(prevKeyPath) : serializeByValueID(prevKeyPath), JSCompiler_inline_result = prevKeyPath) : (prevKeyPath = request.fatalError, JSCompiler_inline_result = parentPropertyName ? serializeLazyID(prevKeyPath) : serializeByValueID(prevKeyPath)); else if (value = thrownValue === SuspenseException ? getSuspendedThenable() : thrownValue, "object" === typeof value && null !== value && "function" === typeof value.then) { JSCompiler_inline_result = createTask(request, task.model, task.keyPath, task.implicitSlot, task.formatContext, request.abortableTasks); var ping = JSCompiler_inline_result.ping; value.then(ping, ping); JSCompiler_inline_result.thenableState = getThenableStateAfterSuspending(); task.keyPath = prevKeyPath; task.implicitSlot = prevImplicitSlot; JSCompiler_inline_result = parentPropertyName ? serializeLazyID(JSCompiler_inline_result.id) : serializeByValueID(JSCompiler_inline_result.id); } else task.keyPath = prevKeyPath, task.implicitSlot = prevImplicitSlot, request.pendingChunks++, prevKeyPath = request.nextChunkId++, prevImplicitSlot = logRecoverableError(request, value), emitErrorChunk(request, prevKeyPath, prevImplicitSlot), JSCompiler_inline_result = parentPropertyName ? serializeLazyID(prevKeyPath) : serializeByValueID(prevKeyPath); } return JSCompiler_inline_result; }, thenableState: null }; abortSet.add(task); return task; } function serializeByValueID(id) { return "$" + id.toString(16); } function serializeLazyID(id) { return "$L" + id.toString(16); } function encodeReferenceChunk(request, id, reference) { request = stringify(reference); id = id.toString(16) + ":" + request + "\n"; return stringToChunk(id); } function serializeClientReference(request, parent, parentPropertyName, clientReference) { var clientReferenceKey = clientReference.$$async ? clientReference.$$id + "#async" : clientReference.$$id, writtenClientReferences = request.writtenClientReferences, existingId = writtenClientReferences.get(clientReferenceKey); if (void 0 !== existingId) return parent[0] === REACT_ELEMENT_TYPE && "1" === parentPropertyName ? serializeLazyID(existingId) : serializeByValueID(existingId); try { var config2 = request.bundlerConfig, modulePath = clientReference.$$id; existingId = ""; var resolvedModuleData = config2[modulePath]; if (resolvedModuleData) existingId = resolvedModuleData.name; else { var idx = modulePath.lastIndexOf("#"); -1 !== idx && (existingId = modulePath.slice(idx + 1), resolvedModuleData = config2[modulePath.slice(0, idx)]); if (!resolvedModuleData) throw Error('Could not find the module "' + modulePath + '" in the React Client Manifest. This is probably a bug in the React Server Components bundler.'); } if (true === resolvedModuleData.async && true === clientReference.$$async) throw Error('The module "' + modulePath + '" is marked as an async ESM module but was loaded as a CJS proxy. This is probably a bug in the React Server Components bundler.'); var JSCompiler_inline_result = true === resolvedModuleData.async || true === clientReference.$$async ? [ resolvedModuleData.id, resolvedModuleData.chunks, existingId, 1 ] : [ resolvedModuleData.id, resolvedModuleData.chunks, existingId ]; request.pendingChunks++; var importId = request.nextChunkId++, json = stringify(JSCompiler_inline_result), row = importId.toString(16) + ":I" + json + "\n", processedChunk = stringToChunk(row); request.completedImportChunks.push(processedChunk); writtenClientReferences.set(clientReferenceKey, importId); return parent[0] === REACT_ELEMENT_TYPE && "1" === parentPropertyName ? serializeLazyID(importId) : serializeByValueID(importId); } catch (x) { return request.pendingChunks++, parent = request.nextChunkId++, parentPropertyName = logRecoverableError(request, x), emitErrorChunk(request, parent, parentPropertyName), serializeByValueID(parent); } } function outlineModelWithFormatContext(request, value, formatContext) { value = createTask(request, value, null, false, formatContext, request.abortableTasks); retryTask(request, value); return value.id; } function serializeTypedArray(request, tag, typedArray) { request.pendingChunks++; var bufferId = request.nextChunkId++; emitTypedArrayChunk(request, bufferId, tag, typedArray, false); return serializeByValueID(bufferId); } function serializeBlob(request, blob) { function progress(entry) { if (0 === newTask.status) if (entry.done) request.cacheController.signal.removeEventListener("abort", abortBlob), pingTask(request, newTask); else return model.push(entry.value), reader.read().then(progress).catch(error); } function error(reason) { 0 === newTask.status && (request.cacheController.signal.removeEventListener("abort", abortBlob), erroredTask(request, newTask, reason), enqueueFlush(request), reader.cancel(reason).then(error, error)); } function abortBlob() { if (0 === newTask.status) { var signal = request.cacheController.signal; signal.removeEventListener("abort", abortBlob); signal = signal.reason; 21 === request.type ? (request.abortableTasks.delete(newTask), haltTask(newTask), finishHaltedTask(newTask, request)) : (erroredTask(request, newTask, signal), enqueueFlush(request)); reader.cancel(signal).then(error, error); } } var model = [ blob.type ], newTask = createTask(request, model, null, false, 0, request.abortableTasks), reader = blob.stream().getReader(); request.cacheController.signal.addEventListener("abort", abortBlob); reader.read().then(progress).catch(error); return "$B" + newTask.id.toString(16); } var modelRoot = false; function renderModelDestructive(request, task, parent, parentPropertyName, value) { task.model = value; if (value === REACT_ELEMENT_TYPE) return "$"; if (null === value) return null; if ("object" === typeof value) { switch (value.$$typeof) { case REACT_ELEMENT_TYPE: var elementReference = null, writtenObjects = request.writtenObjects; if (null === task.keyPath && !task.implicitSlot) { var existingReference = writtenObjects.get(value); if (void 0 !== existingReference) if (modelRoot === value) modelRoot = null; else return existingReference; else -1 === parentPropertyName.indexOf(":") && (parent = writtenObjects.get(parent), void 0 !== parent && (elementReference = parent + ":" + parentPropertyName, writtenObjects.set(value, elementReference))); } if (3200 < serializedSize) return deferTask(request, task); parentPropertyName = value.props; parent = parentPropertyName.ref; request = renderElement(request, task, value.type, value.key, void 0 !== parent ? parent : null, parentPropertyName); "object" === typeof request && null !== request && null !== elementReference && (writtenObjects.has(request) || writtenObjects.set(request, elementReference)); return request; case REACT_LAZY_TYPE: if (3200 < serializedSize) return deferTask(request, task); task.thenableState = null; parentPropertyName = value._init; value = parentPropertyName(value._payload); if (12 === request.status) throw null; return renderModelDestructive(request, task, emptyRoot, "", value); case REACT_LEGACY_ELEMENT_TYPE: throw Error('A React Element from an older version of React was rendered. This is not supported. It can happen if:\n- Multiple copies of the "react" package is used.\n- A library pre-bundled an old copy of "react" or "react/jsx-runtime".\n- A compiler tries to "inline" JSX instead of using the runtime.'); } if (value.$$typeof === CLIENT_REFERENCE_TAG$1) return serializeClientReference(request, parent, parentPropertyName, value); if (void 0 !== request.temporaryReferences && (elementReference = request.temporaryReferences.get(value), void 0 !== elementReference)) return "$T" + elementReference; elementReference = request.writtenObjects; writtenObjects = elementReference.get(value); if ("function" === typeof value.then) { if (void 0 !== writtenObjects) { if (null !== task.keyPath || task.implicitSlot) return "$@" + serializeThenable(request, task, value).toString(16); if (modelRoot === value) modelRoot = null; else return writtenObjects; } request = "$@" + serializeThenable(request, task, value).toString(16); elementReference.set(value, request); return request; } if (void 0 !== writtenObjects) if (modelRoot === value) { if (writtenObjects !== serializeByValueID(task.id)) return writtenObjects; modelRoot = null; } else return writtenObjects; else if (-1 === parentPropertyName.indexOf(":") && (writtenObjects = elementReference.get(parent), void 0 !== writtenObjects)) { existingReference = parentPropertyName; if (isArrayImpl(parent) && parent[0] === REACT_ELEMENT_TYPE) switch (parentPropertyName) { case "1": existingReference = "type"; break; case "2": existingReference = "key"; break; case "3": existingReference = "props"; break; case "4": existingReference = "_owner"; } elementReference.set(value, writtenObjects + ":" + existingReference); } if (isArrayImpl(value)) return renderFragment(request, task, value); if (value instanceof Map) return value = Array.from(value), "$Q" + outlineModelWithFormatContext(request, value, 0).toString(16); if (value instanceof Set) return value = Array.from(value), "$W" + outlineModelWithFormatContext(request, value, 0).toString(16); if ("function" === typeof FormData && value instanceof FormData) return value = Array.from(value.entries()), "$K" + outlineModelWithFormatContext(request, value, 0).toString(16); if (value instanceof Error) return "$Z"; if (value instanceof ArrayBuffer) return serializeTypedArray(request, "A", new Uint8Array(value)); if (value instanceof Int8Array) return serializeTypedArray(request, "O", value); if (value instanceof Uint8Array) return serializeTypedArray(request, "o", value); if (value instanceof Uint8ClampedArray) return serializeTypedArray(request, "U", value); if (value instanceof Int16Array) return serializeTypedArray(request, "S", value); if (value instanceof Uint16Array) return serializeTypedArray(request, "s", value); if (value instanceof Int32Array) return serializeTypedArray(request, "L", value); if (value instanceof Uint32Array) return serializeTypedArray(request, "l", value); if (value instanceof Float32Array) return serializeTypedArray(request, "G", value); if (value instanceof Float64Array) return serializeTypedArray(request, "g", value); if (value instanceof BigInt64Array) return serializeTypedArray(request, "M", value); if (value instanceof BigUint64Array) return serializeTypedArray(request, "m", value); if (value instanceof DataView) return serializeTypedArray(request, "V", value); if ("function" === typeof Blob && value instanceof Blob) return serializeBlob(request, value); if (elementReference = getIteratorFn(value)) return parentPropertyName = elementReference.call(value), parentPropertyName === value ? (value = Array.from(parentPropertyName), "$i" + outlineModelWithFormatContext(request, value, 0).toString(16)) : renderFragment(request, task, Array.from(parentPropertyName)); if ("function" === typeof ReadableStream && value instanceof ReadableStream) return serializeReadableStream(request, task, value); elementReference = value[ASYNC_ITERATOR]; if ("function" === typeof elementReference) return null !== task.keyPath ? (request = [ REACT_ELEMENT_TYPE, REACT_FRAGMENT_TYPE, task.keyPath, { children: value } ], request = task.implicitSlot ? [ request ] : request) : (parentPropertyName = elementReference.call(value), request = serializeAsyncIterable(request, task, value, parentPropertyName)), request; if (value instanceof Date) return "$D" + value.toJSON(); request = getPrototypeOf(value); if (request !== ObjectPrototype$1 && (null === request || null !== getPrototypeOf(request))) throw Error("Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported." + describeObjectForErrorMessage(parent, parentPropertyName)); return value; } if ("string" === typeof value) { serializedSize += value.length; if ("Z" === value[value.length - 1] && parent[parentPropertyName] instanceof Date) return "$D" + value; if (1024 <= value.length && null !== byteLengthOfChunk) return request.pendingChunks++, task = request.nextChunkId++, emitTextChunk(request, task, value, false), serializeByValueID(task); request = "$" === value[0] ? "$" + value : value; return request; } if ("boolean" === typeof value) return value; if ("number" === typeof value) return Number.isFinite(value) ? 0 === value && -Infinity === 1 / value ? "$-0" : value : Infinity === value ? "$Infinity" : -Infinity === value ? "$-Infinity" : "$NaN"; if ("undefined" === typeof value) return "$undefined"; if ("function" === typeof value) { if (value.$$typeof === CLIENT_REFERENCE_TAG$1) return serializeClientReference(request, parent, parentPropertyName, value); if (value.$$typeof === SERVER_REFERENCE_TAG) return task = request.writtenServerReferences, parentPropertyName = task.get(value), void 0 !== parentPropertyName ? request = "$h" + parentPropertyName.toString(16) : (parentPropertyName = value.$$bound, parentPropertyName = null === parentPropertyName ? null : Promise.resolve(parentPropertyName), request = outlineModelWithFormatContext(request, { id: value.$$id, bound: parentPropertyName }, 0), task.set(value, request), request = "$h" + request.toString(16)), request; if (void 0 !== request.temporaryReferences && (request = request.temporaryReferences.get(value), void 0 !== request)) return "$T" + request; if (value.$$typeof === TEMPORARY_REFERENCE_TAG) throw Error("Could not reference an opaque temporary reference. This is likely due to misconfiguring the temporaryReferences options on the server."); if (/^on[A-Z]/.test(parentPropertyName)) throw Error("Event handlers cannot be passed to Client Component props." + describeObjectForErrorMessage(parent, parentPropertyName) + "\nIf you need interactivity, consider converting part of this to a Client Component."); throw Error('Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server". Or maybe you meant to call this function rather than return it.' + describeObjectForErrorMessage(parent, parentPropertyName)); } if ("symbol" === typeof value) { task = request.writtenSymbols; elementReference = task.get(value); if (void 0 !== elementReference) return serializeByValueID(elementReference); elementReference = value.description; if (Symbol.for(elementReference) !== value) throw Error("Only global symbols received from Symbol.for(...) can be passed to Client Components. The symbol Symbol.for(" + (value.description + ") cannot be found among global symbols.") + describeObjectForErrorMessage(parent, parentPropertyName)); request.pendingChunks++; parentPropertyName = request.nextChunkId++; parent = encodeReferenceChunk(request, parentPropertyName, "$S" + elementReference); request.completedImportChunks.push(parent); task.set(value, parentPropertyName); return serializeByValueID(parentPropertyName); } if ("bigint" === typeof value) return "$n" + value.toString(10); throw Error("Type " + typeof value + " is not supported in Client Component props." + describeObjectForErrorMessage(parent, parentPropertyName)); } function logRecoverableError(request, error) { var prevRequest = currentRequest; currentRequest = null; try { var onError = request.onError; var errorDigest = supportsRequestStorage ? requestStorage.run(void 0, onError, error) : onError(error); } finally { currentRequest = prevRequest; } if (null != errorDigest && "string" !== typeof errorDigest) throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "' + typeof errorDigest + '" instead'); return errorDigest || ""; } function fatalError(request, error) { var onFatalError = request.onFatalError; onFatalError(error); null !== request.destination ? (request.status = 14, closeWithError(request.destination, error)) : (request.status = 13, request.fatalError = error); request.cacheController.abort(Error("The render was aborted due to a fatal error.", { cause: error })); } function emitErrorChunk(request, id, digest) { digest = { digest }; id = id.toString(16) + ":E" + stringify(digest) + "\n"; id = stringToChunk(id); request.completedErrorChunks.push(id); } function emitModelChunk(request, id, json) { id = id.toString(16) + ":" + json + "\n"; id = stringToChunk(id); request.completedRegularChunks.push(id); } function emitTypedArrayChunk(request, id, tag, typedArray, debug) { debug ? request.pendingDebugChunks++ : request.pendingChunks++; debug = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); typedArray = 2048 < typedArray.byteLength ? debug.slice() : debug; debug = typedArray.byteLength; id = id.toString(16) + ":" + tag + debug.toString(16) + ","; id = stringToChunk(id); request.completedRegularChunks.push(id, typedArray); } function emitTextChunk(request, id, text, debug) { if (null === byteLengthOfChunk) throw Error("Existence of byteLengthOfChunk should have already been checked. This is a bug in React."); debug ? request.pendingDebugChunks++ : request.pendingChunks++; text = stringToChunk(text); debug = text.byteLength; id = id.toString(16) + ":T" + debug.toString(16) + ","; id = stringToChunk(id); request.completedRegularChunks.push(id, text); } function emitChunk(request, task, value) { var id = task.id; "string" === typeof value && null !== byteLengthOfChunk ? emitTextChunk(request, id, value, false) : value instanceof ArrayBuffer ? emitTypedArrayChunk(request, id, "A", new Uint8Array(value), false) : value instanceof Int8Array ? emitTypedArrayChunk(request, id, "O", value, false) : value instanceof Uint8Array ? emitTypedArrayChunk(request, id, "o", value, false) : value instanceof Uint8ClampedArray ? emitTypedArrayChunk(request, id, "U", value, false) : value instanceof Int16Array ? emitTypedArrayChunk(request, id, "S", value, false) : value instanceof Uint16Array ? emitTypedArrayChunk(request, id, "s", value, false) : value instanceof Int32Array ? emitTypedArrayChunk(request, id, "L", value, false) : value instanceof Uint32Array ? emitTypedArrayChunk(request, id, "l", value, false) : value instanceof Float32Array ? emitTypedArrayChunk(request, id, "G", value, false) : value instanceof Float64Array ? emitTypedArrayChunk(request, id, "g", value, false) : value instanceof BigInt64Array ? emitTypedArrayChunk(request, id, "M", value, false) : value instanceof BigUint64Array ? emitTypedArrayChunk(request, id, "m", value, false) : value instanceof DataView ? emitTypedArrayChunk(request, id, "V", value, false) : (value = stringify(value, task.toJSON), emitModelChunk(request, task.id, value)); } function erroredTask(request, task, error) { task.status = 4; error = logRecoverableError(request, error); emitErrorChunk(request, task.id, error); request.abortableTasks.delete(task); callOnAllReadyIfReady(request); } var emptyRoot = {}; function retryTask(request, task) { if (0 === task.status) { task.status = 5; var parentSerializedSize = serializedSize; try { modelRoot = task.model; var resolvedModel = renderModelDestructive(request, task, emptyRoot, "", task.model); modelRoot = resolvedModel; task.keyPath = null; task.implicitSlot = false; if ("object" === typeof resolvedModel && null !== resolvedModel) request.writtenObjects.set(resolvedModel, serializeByValueID(task.id)), emitChunk(request, task, resolvedModel); else { var json = stringify(resolvedModel); emitModelChunk(request, task.id, json); } task.status = 1; request.abortableTasks.delete(task); callOnAllReadyIfReady(request); } catch (thrownValue) { if (12 === request.status) if (request.abortableTasks.delete(task), task.status = 0, 21 === request.type) haltTask(task), finishHaltedTask(task, request); else { var errorId = request.fatalError; abortTask(task); finishAbortedTask(task, request, errorId); } else { var x = thrownValue === SuspenseException ? getSuspendedThenable() : thrownValue; if ("object" === typeof x && null !== x && "function" === typeof x.then) { task.status = 0; task.thenableState = getThenableStateAfterSuspending(); var ping = task.ping; x.then(ping, ping); } else erroredTask(request, task, x); } } finally { serializedSize = parentSerializedSize; } } } function tryStreamTask(request, task) { var parentSerializedSize = serializedSize; try { emitChunk(request, task, task.model); } finally { serializedSize = parentSerializedSize; } } function performWork(request) { var prevDispatcher = ReactSharedInternalsServer.H; ReactSharedInternalsServer.H = HooksDispatcher; var prevRequest = currentRequest; currentRequest$1 = currentRequest = request; try { var pingedTasks = request.pingedTasks; request.pingedTasks = []; for (var i = 0; i < pingedTasks.length; i++) retryTask(request, pingedTasks[i]); flushCompletedChunks(request); } catch (error) { logRecoverableError(request, error), fatalError(request, error); } finally { ReactSharedInternalsServer.H = prevDispatcher, currentRequest$1 = null, currentRequest = prevRequest; } } function abortTask(task) { 0 === task.status && (task.status = 3); } function finishAbortedTask(task, request, errorId) { 3 === task.status && (errorId = serializeByValueID(errorId), task = encodeReferenceChunk(request, task.id, errorId), request.completedErrorChunks.push(task)); } function haltTask(task) { 0 === task.status && (task.status = 3); } function finishHaltedTask(task, request) { 3 === task.status && request.pendingChunks--; } function flushCompletedChunks(request) { var destination = request.destination; if (null !== destination) { currentView = new Uint8Array(2048); writtenBytes = 0; try { for (var importsChunks = request.completedImportChunks, i = 0; i < importsChunks.length; i++) request.pendingChunks--, writeChunkAndReturn(destination, importsChunks[i]); importsChunks.splice(0, i); var hintChunks = request.completedHintChunks; for (i = 0; i < hintChunks.length; i++) writeChunkAndReturn(destination, hintChunks[i]); hintChunks.splice(0, i); var regularChunks = request.completedRegularChunks; for (i = 0; i < regularChunks.length; i++) request.pendingChunks--, writeChunkAndReturn(destination, regularChunks[i]); regularChunks.splice(0, i); var errorChunks = request.completedErrorChunks; for (i = 0; i < errorChunks.length; i++) request.pendingChunks--, writeChunkAndReturn(destination, errorChunks[i]); errorChunks.splice(0, i); } finally { request.flushScheduled = false, currentView && 0 < writtenBytes && (destination.enqueue(new Uint8Array(currentView.buffer, 0, writtenBytes)), currentView = null, writtenBytes = 0); } } 0 === request.pendingChunks && (12 > request.status && request.cacheController.abort(Error("This render completed successfully. All cacheSignals are now aborted to allow clean up of any unused resources.")), null !== request.destination && (request.status = 14, request.destination.close(), request.destination = null)); } function startWork(request) { request.flushScheduled = null !== request.destination; supportsRequestStorage ? scheduleMicrotask(function() { requestStorage.run(request, performWork, request); }) : scheduleMicrotask(function() { return performWork(request); }); setTimeout(function() { 10 === request.status && (request.status = 11); }, 0); } function enqueueFlush(request) { false === request.flushScheduled && 0 === request.pingedTasks.length && null !== request.destination && (request.flushScheduled = true, setTimeout(function() { request.flushScheduled = false; flushCompletedChunks(request); }, 0)); } function callOnAllReadyIfReady(request) { 0 === request.abortableTasks.size && (request = request.onAllReady, request()); } function startFlowing(request, destination) { if (13 === request.status) request.status = 14, closeWithError(destination, request.fatalError); else if (14 !== request.status && null === request.destination) { request.destination = destination; try { flushCompletedChunks(request); } catch (error) { logRecoverableError(request, error), fatalError(request, error); } } } function finishHalt(request, abortedTasks) { try { abortedTasks.forEach(function(task) { return finishHaltedTask(task, request); }); var onAllReady = request.onAllReady; onAllReady(); flushCompletedChunks(request); } catch (error) { logRecoverableError(request, error), fatalError(request, error); } } function finishAbort(request, abortedTasks, errorId) { try { abortedTasks.forEach(function(task) { return finishAbortedTask(task, request, errorId); }); var onAllReady = request.onAllReady; onAllReady(); flushCompletedChunks(request); } catch (error) { logRecoverableError(request, error), fatalError(request, error); } } function abort(request, reason) { if (!(11 < request.status)) try { request.status = 12; request.cacheController.abort(reason); var abortableTasks = request.abortableTasks; if (0 < abortableTasks.size) if (21 === request.type) abortableTasks.forEach(function(task) { return haltTask(task, request); }), setTimeout(function() { return finishHalt(request, abortableTasks); }, 0); else { var error = void 0 === reason ? Error("The render was aborted by the server without a reason.") : "object" === typeof reason && null !== reason && "function" === typeof reason.then ? Error("The render was aborted by the server with a promise.") : reason, digest = logRecoverableError(request, error, null), errorId = request.nextChunkId++; request.fatalError = errorId; request.pendingChunks++; emitErrorChunk(request, errorId, digest, error, false, null); abortableTasks.forEach(function(task) { return abortTask(task, request, errorId); }); setTimeout(function() { return finishAbort(request, abortableTasks, errorId); }, 0); } else { var onAllReady = request.onAllReady; onAllReady(); flushCompletedChunks(request); } } catch (error$26) { logRecoverableError(request, error$26), fatalError(request, error$26); } } function resolveServerReference(bundlerConfig, id) { var name = "", resolvedModuleData = bundlerConfig[id]; if (resolvedModuleData) name = resolvedModuleData.name; else { var idx = id.lastIndexOf("#"); -1 !== idx && (name = id.slice(idx + 1), resolvedModuleData = bundlerConfig[id.slice(0, idx)]); if (!resolvedModuleData) throw Error('Could not find the module "' + id + '" in the React Server Manifest. This is probably a bug in the React Server Components bundler.'); } return resolvedModuleData.async ? [ resolvedModuleData.id, resolvedModuleData.chunks, name, 1 ] : [ resolvedModuleData.id, resolvedModuleData.chunks, name ]; } var chunkCache = /* @__PURE__ */ new Map(); function requireAsyncModule(id) { var promise = __vite_rsc_require__(id); if ("function" !== typeof promise.then || "fulfilled" === promise.status) return null; promise.then(function(value) { promise.status = "fulfilled"; promise.value = value; }, function(reason) { promise.status = "rejected"; promise.reason = reason; }); return promise; } function ignoreReject() { } function preloadModule(metadata) { for (var chunks = metadata[1], promises = [], i = 0; i < chunks.length; ) { var chunkId = chunks[i++]; chunks[i++]; var entry = chunkCache.get(chunkId); if (void 0 === entry) { entry = __webpack_chunk_load__(chunkId); promises.push(entry); var resolve = chunkCache.set.bind(chunkCache, chunkId, null); entry.then(resolve, ignoreReject); chunkCache.set(chunkId, entry); } else null !== entry && promises.push(entry); } return 4 === metadata.length ? 0 === promises.length ? requireAsyncModule(metadata[0]) : Promise.all(promises).then(function() { return requireAsyncModule(metadata[0]); }) : 0 < promises.length ? Promise.all(promises) : null; } function requireModule2(metadata) { var moduleExports = __vite_rsc_require__(metadata[0]); if (4 === metadata.length && "function" === typeof moduleExports.then) if ("fulfilled" === moduleExports.status) moduleExports = moduleExports.value; else throw moduleExports.reason; if ("*" === metadata[2]) return moduleExports; if ("" === metadata[2]) return moduleExports.__esModule ? moduleExports.default : moduleExports; if (hasOwnProperty.call(moduleExports, metadata[2])) return moduleExports[metadata[2]]; } var RESPONSE_SYMBOL = /* @__PURE__ */ Symbol(); function ReactPromise(status, value, reason) { this.status = status; this.value = value; this.reason = reason; } ReactPromise.prototype = Object.create(Promise.prototype); ReactPromise.prototype.then = function(resolve, reject) { switch (this.status) { case "resolved_model": initializeModelChunk(this); } switch (this.status) { case "fulfilled": if ("function" === typeof resolve) { for (var inspectedValue = this.value, cycleProtection = 0, visited = /* @__PURE__ */ new Set(); inspectedValue instanceof ReactPromise; ) { cycleProtection++; if (inspectedValue === this || visited.has(inspectedValue) || 1e3 < cycleProtection) { "function" === typeof reject && reject(Error("Cannot have cyclic thenables.")); return; } visited.add(inspectedValue); if ("fulfilled" === inspectedValue.status) inspectedValue = inspectedValue.value; else break; } resolve(this.value); } break; case "pending": case "blocked": "function" === typeof resolve && (null === this.value && (this.value = []), this.value.push(resolve)); "function" === typeof reject && (null === this.reason && (this.reason = []), this.reason.push(reject)); break; default: "function" === typeof reject && reject(this.reason); } }; var ObjectPrototype = Object.prototype, ArrayPrototype = Array.prototype; function wakeChunk(response, listeners, value, chunk) { for (var i = 0; i < listeners.length; i++) { var listener = listeners[i]; "function" === typeof listener ? listener(value) : fulfillReference(response, listener, value, chunk.reason); } } function rejectChunk(response, listeners, error) { for (var i = 0; i < listeners.length; i++) { var listener = listeners[i]; "function" === typeof listener ? listener(error) : rejectReference(response, listener.handler, error); } } function triggerErrorOnChunk(response, chunk, error) { if ("pending" !== chunk.status && "blocked" !== chunk.status) chunk.reason.error(error); else { var listeners = chunk.reason; chunk.status = "rejected"; chunk.reason = error; null !== listeners && rejectChunk(response, listeners, error); } } function createResolvedModelChunk(response, value, id) { var $jscomp$compprop2 = {}; return new ReactPromise("resolved_model", value, ($jscomp$compprop2.id = id, $jscomp$compprop2[RESPONSE_SYMBOL] = response, $jscomp$compprop2)); } function resolveModelChunk(response, chunk, value, id) { if ("pending" !== chunk.status) chunk = chunk.reason, "C" === value[0] ? chunk.close("C" === value ? '"$undefined"' : value.slice(1)) : chunk.enqueueModel(value); else { var resolveListeners = chunk.value, rejectListeners = chunk.reason; chunk.status = "resolved_model"; chunk.value = value; value = {}; chunk.reason = (value.id = id, value[RESPONSE_SYMBOL] = response, value); if (null !== resolveListeners) switch (initializeModelChunk(chunk), chunk.status) { case "fulfilled": wakeChunk(response, resolveListeners, chunk.value, chunk); break; case "blocked": case "pending": if (chunk.value) for (response = 0; response < resolveListeners.length; response++) chunk.value.push(resolveListeners[response]); else chunk.value = resolveListeners; if (chunk.reason) { if (rejectListeners) for (resolveListeners = 0; resolveListeners < rejectListeners.length; resolveListeners++) chunk.reason.push(rejectListeners[resolveListeners]); } else chunk.reason = rejectListeners; break; case "rejected": rejectListeners && rejectChunk(response, rejectListeners, chunk.reason); } } } function createResolvedIteratorResultChunk(response, value, done) { var $jscomp$compprop4 = {}; return new ReactPromise("resolved_model", (done ? '{"done":true,"value":' : '{"done":false,"value":') + value + "}", ($jscomp$compprop4.id = -1, $jscomp$compprop4[RESPONSE_SYMBOL] = response, $jscomp$compprop4)); } function resolveIteratorResultChunk(response, chunk, value, done) { resolveModelChunk(response, chunk, (done ? '{"done":true,"value":' : '{"done":false,"value":') + value + "}", -1); } function loadServerReference$1(response, metaData, parentObject, key) { function reject(error) { var rejectListeners = blockedPromise.reason, erroredPromise = blockedPromise; erroredPromise.status = "rejected"; erroredPromise.value = null; erroredPromise.reason = error; null !== rejectListeners && rejectChunk(response, rejectListeners, error); rejectReference(response, handler, error); } var id = metaData.id; if ("string" !== typeof id || "then" === key) return null; var cachedPromise = metaData.$$promise; if (void 0 !== cachedPromise) { if ("fulfilled" === cachedPromise.status) return cachedPromise = cachedPromise.value, "__proto__" === key ? null : parentObject[key] = cachedPromise; initializingHandler ? (id = initializingHandler, id.deps++) : id = initializingHandler = { chunk: null, value: null, reason: null, deps: 1, errored: false }; cachedPromise.then(resolveReference.bind(null, response, id, parentObject, key), rejectReference.bind(null, response, id)); return null; } var blockedPromise = new ReactPromise("blocked", null, null); metaData.$$promise = blockedPromise; var serverReference = resolveServerReference(response._bundlerConfig, id); cachedPromise = metaData.bound; if (id = preloadModule(serverReference)) cachedPromise instanceof ReactPromise && (id = Promise.all([ id, cachedPromise ])); else if (cachedPromise instanceof ReactPromise) id = Promise.resolve(cachedPromise); else return cachedPromise = requireModule2(serverReference), id = blockedPromise, id.status = "fulfilled", id.value = cachedPromise; if (initializingHandler) { var handler = initializingHandler; handler.deps++; } else handler = initializingHandler = { chunk: null, value: null, reason: null, deps: 1, errored: false }; id.then(function() { var resolvedValue = requireModule2(serverReference); if (metaData.bound) { var promiseValue = metaData.bound.value; promiseValue = isArrayImpl(promiseValue) ? promiseValue.slice(0) : []; if (1e3 < promiseValue.length) { reject(Error("Server Function has too many bound arguments. Received " + promiseValue.length + " but the limit is 1000.")); return; } promiseValue.unshift(null); resolvedValue = resolvedValue.bind.apply(resolvedValue, promiseValue); } promiseValue = blockedPromise.value; var initializedPromise = blockedPromise; initializedPromise.status = "fulfilled"; initializedPromise.value = resolvedValue; initializedPromise.reason = null; null !== promiseValue && wakeChunk(response, promiseValue, resolvedValue, initializedPromise); resolveReference(response, handler, parentObject, key, resolvedValue); }, reject); return null; } function reviveModel(response, parentObj, parentKey, value, reference, arrayRoot) { if ("string" === typeof value) return parseModelString(response, parentObj, parentKey, value, reference, arrayRoot); if ("object" === typeof value && null !== value) if (void 0 !== reference && void 0 !== response._temporaryReferences && response._temporaryReferences.set(value, reference), isArrayImpl(value)) { if (null === arrayRoot) { var childContext = { count: 0, fork: false }; response._rootArrayContexts.set(value, childContext); } else childContext = arrayRoot; 1 < value.length && (childContext.fork = true); bumpArrayCount(childContext, value.length + 1, response); for (parentObj = 0; parentObj < value.length; parentObj++) value[parentObj] = reviveModel(response, value, "" + parentObj, value[parentObj], void 0 !== reference ? reference + ":" + parentObj : void 0, childContext); } else for (childContext in value) hasOwnProperty.call(value, childContext) && ("__proto__" === childContext ? delete value[childContext] : (parentObj = void 0 !== reference && -1 === childContext.indexOf(":") ? reference + ":" + childContext : void 0, parentObj = reviveModel(response, value, childContext, value[childContext], parentObj, null), void 0 !== parentObj ? value[childContext] = parentObj : delete value[childContext])); return value; } function bumpArrayCount(arrayContext, slots, response) { if ((arrayContext.count += slots) > response._arraySizeLimit && arrayContext.fork) throw Error("Maximum array nesting exceeded. Large nested arrays can be dangerous. Try adding intermediate objects."); } var initializingHandler = null; function initializeModelChunk(chunk) { var prevHandler = initializingHandler; initializingHandler = null; var _chunk$reason = chunk.reason, response = _chunk$reason[RESPONSE_SYMBOL]; _chunk$reason = _chunk$reason.id; _chunk$reason = -1 === _chunk$reason ? void 0 : _chunk$reason.toString(16); var resolvedModel = chunk.value; chunk.status = "blocked"; chunk.value = null; chunk.reason = null; try { var rawModel = JSON.parse(resolvedModel); resolvedModel = { count: 0, fork: false }; var value = reviveModel(response, { "": rawModel }, "", rawModel, _chunk$reason, resolvedModel), resolveListeners = chunk.value; if (null !== resolveListeners) for (chunk.value = null, chunk.reason = null, rawModel = 0; rawModel < resolveListeners.length; rawModel++) { var listener = resolveListeners[rawModel]; "function" === typeof listener ? listener(value) : fulfillReference(response, listener, value, resolvedModel); } if (null !== initializingHandler) { if (initializingHandler.errored) throw initializingHandler.reason; if (0 < initializingHandler.deps) { initializingHandler.value = value; initializingHandler.reason = resolvedModel; initializingHandler.chunk = chunk; return; } } chunk.status = "fulfilled"; chunk.value = value; chunk.reason = resolvedModel; } catch (error) { chunk.status = "rejected", chunk.reason = error; } finally { initializingHandler = prevHandler; } } function reportGlobalError(response, error) { response._closed = true; response._closedReason = error; response._chunks.forEach(function(chunk) { "pending" === chunk.status ? triggerErrorOnChunk(response, chunk, error) : "fulfilled" === chunk.status && null !== chunk.reason && (chunk = chunk.reason, "function" === typeof chunk.error && chunk.error(error)); }); } function getChunk(response, id) { var chunks = response._chunks, chunk = chunks.get(id); chunk || (chunk = response._formData.get(response._prefix + id), chunk = "string" === typeof chunk ? createResolvedModelChunk(response, chunk, id) : response._closed ? new ReactPromise("rejected", null, response._closedReason) : new ReactPromise("pending", null, null), chunks.set(id, chunk)); return chunk; } function fulfillReference(response, reference, value, arrayRoot) { var handler = reference.handler, parentObject = reference.parentObject, key = reference.key, map = reference.map, path2 = reference.path; try { for (var localLength = 0, rootArrayContexts = response._rootArrayContexts, i = 1; i < path2.length; i++) { var name = path2[i]; if ("object" !== typeof value || null === value || getPrototypeOf(value) !== ObjectPrototype && getPrototypeOf(value) !== ArrayPrototype || !hasOwnProperty.call(value, name)) throw Error("Invalid reference."); value = value[name]; if (isArrayImpl(value)) localLength = 0, arrayRoot = rootArrayContexts.get(value) || arrayRoot; else if (arrayRoot = null, "string" === typeof value) localLength = value.length; else if ("bigint" === typeof value) { var n = Math.abs(Number(value)); localLength = 0 === n ? 1 : Math.floor(Math.log10(n)) + 1; } else localLength = ArrayBuffer.isView(value) ? value.byteLength : 0; } var resolvedValue = map(response, value, parentObject, key); var referenceArrayRoot = reference.arrayRoot; null !== referenceArrayRoot && (null !== arrayRoot ? (arrayRoot.fork && (referenceArrayRoot.fork = true), bumpArrayCount(referenceArrayRoot, arrayRoot.count, response)) : 0 < localLength && bumpArrayCount(referenceArrayRoot, localLength, response)); } catch (error) { rejectReference(response, handler, error); return; } resolveReference(response, handler, parentObject, key, resolvedValue); } function resolveReference(response, handler, parentObject, key, resolvedValue) { "__proto__" !== key && (parentObject[key] = resolvedValue); "" === key && null === handler.value && (handler.value = resolvedValue); handler.deps--; 0 === handler.deps && (parentObject = handler.chunk, null !== parentObject && "blocked" === parentObject.status && (key = parentObject.value, parentObject.status = "fulfilled", parentObject.value = handler.value, parentObject.reason = handler.reason, null !== key && wakeChunk(response, key, handler.value, parentObject))); } function rejectReference(response, handler, error) { handler.errored || (handler.errored = true, handler.value = null, handler.reason = error, handler = handler.chunk, null !== handler && "blocked" === handler.status && triggerErrorOnChunk(response, handler, error)); } function getOutlinedModel(response, reference, parentObject, key, referenceArrayRoot, map) { reference = reference.split(":"); var id = parseInt(reference[0], 16), chunk = getChunk(response, id); switch (chunk.status) { case "resolved_model": initializeModelChunk(chunk); } switch (chunk.status) { case "fulfilled": id = chunk.value; chunk = chunk.reason; for (var localLength = 0, rootArrayContexts = response._rootArrayContexts, i = 1; i < reference.length; i++) { localLength = reference[i]; if ("object" !== typeof id || null === id || getPrototypeOf(id) !== ObjectPrototype && getPrototypeOf(id) !== ArrayPrototype || !hasOwnProperty.call(id, localLength)) throw Error("Invalid reference."); id = id[localLength]; isArrayImpl(id) ? (localLength = 0, chunk = rootArrayContexts.get(id) || chunk) : (chunk = null, "string" === typeof id ? localLength = id.length : "bigint" === typeof id ? (localLength = Math.abs(Number(id)), localLength = 0 === localLength ? 1 : Math.floor(Math.log10(localLength)) + 1) : localLength = ArrayBuffer.isView(id) ? id.byteLength : 0); } parentObject = map(response, id, parentObject, key); null !== referenceArrayRoot && (null !== chunk ? (chunk.fork && (referenceArrayRoot.fork = true), bumpArrayCount(referenceArrayRoot, chunk.count, response)) : 0 < localLength && bumpArrayCount(referenceArrayRoot, localLength, response)); return parentObject; case "blocked": return initializingHandler ? (response = initializingHandler, response.deps++) : response = initializingHandler = { chunk: null, value: null, reason: null, deps: 1, errored: false }, referenceArrayRoot = { handler: response, parentObject, key, map, path: reference, arrayRoot: referenceArrayRoot }, null === chunk.value ? chunk.value = [ referenceArrayRoot ] : chunk.value.push(referenceArrayRoot), null === chunk.reason ? chunk.reason = [ referenceArrayRoot ] : chunk.reason.push(referenceArrayRoot), null; case "pending": throw Error("Invalid forward reference."); default: return initializingHandler ? (initializingHandler.errored = true, initializingHandler.value = null, initializingHandler.reason = chunk.reason) : initializingHandler = { chunk: null, value: null, reason: chunk.reason, deps: 0, errored: true }, null; } } function createMap(response, model) { if (!isArrayImpl(model)) throw Error("Invalid Map initializer."); if (true === model.$$consumed) throw Error("Already initialized Map."); response = new Map(model); model.$$consumed = true; return response; } function createSet(response, model) { if (!isArrayImpl(model)) throw Error("Invalid Set initializer."); if (true === model.$$consumed) throw Error("Already initialized Set."); response = new Set(model); model.$$consumed = true; return response; } function extractIterator(response, model) { if (!isArrayImpl(model)) throw Error("Invalid Iterator initializer."); if (true === model.$$consumed) throw Error("Already initialized Iterator."); response = model[Symbol.iterator](); model.$$consumed = true; return response; } function createModel(response, model, parentObject, key) { return "then" === key && "function" === typeof model ? null : model; } function parseTypedArray(response, reference, constructor, bytesPerElement, parentObject, parentKey, referenceArrayRoot) { function reject(error) { if (!handler.errored) { handler.errored = true; handler.value = null; handler.reason = error; var chunk = handler.chunk; null !== chunk && "blocked" === chunk.status && triggerErrorOnChunk(response, chunk, error); } } reference = parseInt(reference.slice(2), 16); var key = response._prefix + reference; bytesPerElement = response._chunks; if (bytesPerElement.has(reference)) throw Error("Already initialized typed array."); bytesPerElement.set(reference, new ReactPromise("rejected", null, Error("Already initialized typed array."))); reference = response._formData.get(key).arrayBuffer(); if (initializingHandler) { var handler = initializingHandler; handler.deps++; } else handler = initializingHandler = { chunk: null, value: null, reason: null, deps: 1, errored: false }; reference.then(function(buffer) { try { null !== referenceArrayRoot && bumpArrayCount(referenceArrayRoot, buffer.byteLength, response); var resolvedValue = constructor === ArrayBuffer ? buffer : new constructor(buffer); "__proto__" !== key && (parentObject[parentKey] = resolvedValue); "" === parentKey && null === handler.value && (handler.value = resolvedValue); } catch (x) { reject(x); return; } handler.deps--; 0 === handler.deps && (buffer = handler.chunk, null !== buffer && "blocked" === buffer.status && (resolvedValue = buffer.value, buffer.status = "fulfilled", buffer.value = handler.value, buffer.reason = null, null !== resolvedValue && wakeChunk(response, resolvedValue, handler.value, buffer))); }, reject); return null; } function resolveStream(response, id, stream, controller) { var chunks = response._chunks; stream = new ReactPromise("fulfilled", stream, controller); chunks.set(id, stream); response = response._formData.getAll(response._prefix + id); for (id = 0; id < response.length; id++) chunks = response[id], "string" === typeof chunks && ("C" === chunks[0] ? controller.close("C" === chunks ? '"$undefined"' : chunks.slice(1)) : controller.enqueueModel(chunks)); } function parseReadableStream(response, reference, type) { function enqueue(value) { "bytes" !== type || ArrayBuffer.isView(value) ? controller.enqueue(value) : flightController.error(Error("Invalid data for bytes stream.")); } reference = parseInt(reference.slice(2), 16); if (response._chunks.has(reference)) throw Error("Already initialized stream."); var controller = null, closed = false, stream = new ReadableStream({ type, start: function(c) { controller = c; } }), previousBlockedChunk = null, flightController = { enqueueModel: function(json) { if (null === previousBlockedChunk) { var chunk = createResolvedModelChunk(response, json, -1); initializeModelChunk(chunk); "fulfilled" === chunk.status ? enqueue(chunk.value) : (chunk.then(enqueue, flightController.error), previousBlockedChunk = chunk); } else { chunk = previousBlockedChunk; var chunk$31 = new ReactPromise("pending", null, null); chunk$31.then(enqueue, flightController.error); previousBlockedChunk = chunk$31; chunk.then(function() { previousBlockedChunk === chunk$31 && (previousBlockedChunk = null); resolveModelChunk(response, chunk$31, json, -1); }); } }, close: function() { if (!closed) if (closed = true, null === previousBlockedChunk) controller.close(); else { var blockedChunk = previousBlockedChunk; previousBlockedChunk = null; blockedChunk.then(function() { return controller.close(); }); } }, error: function(error) { if (!closed) if (closed = true, null === previousBlockedChunk) controller.error(error); else { var blockedChunk = previousBlockedChunk; previousBlockedChunk = null; blockedChunk.then(function() { return controller.error(error); }); } } }; resolveStream(response, reference, stream, flightController); return stream; } function FlightIterator(next) { this.next = next; } FlightIterator.prototype = {}; FlightIterator.prototype[ASYNC_ITERATOR] = function() { return this; }; function parseAsyncIterable(response, reference, iterator) { reference = parseInt(reference.slice(2), 16); if (response._chunks.has(reference)) throw Error("Already initialized stream."); var buffer = [], closed = false, nextWriteIndex = 0, $jscomp$compprop5 = {}; $jscomp$compprop5 = ($jscomp$compprop5[ASYNC_ITERATOR] = function() { var nextReadIndex = 0; return new FlightIterator(function(arg) { if (void 0 !== arg) throw Error("Values cannot be passed to next() of AsyncIterables passed to Client Components."); if (nextReadIndex === buffer.length) { if (closed) return new ReactPromise("fulfilled", { done: true, value: void 0 }, null); buffer[nextReadIndex] = new ReactPromise("pending", null, null); } return buffer[nextReadIndex++]; }); }, $jscomp$compprop5); iterator = iterator ? $jscomp$compprop5[ASYNC_ITERATOR]() : $jscomp$compprop5; resolveStream(response, reference, iterator, { enqueueModel: function(value) { nextWriteIndex === buffer.length ? buffer[nextWriteIndex] = createResolvedIteratorResultChunk(response, value, false) : resolveIteratorResultChunk(response, buffer[nextWriteIndex], value, false); nextWriteIndex++; }, close: function(value) { if (!closed) for (closed = true, nextWriteIndex === buffer.length ? buffer[nextWriteIndex] = createResolvedIteratorResultChunk(response, value, true) : resolveIteratorResultChunk(response, buffer[nextWriteIndex], value, true), nextWriteIndex++; nextWriteIndex < buffer.length; ) resolveIteratorResultChunk(response, buffer[nextWriteIndex++], '"$undefined"', true); }, error: function(error) { if (!closed) for (closed = true, nextWriteIndex === buffer.length && (buffer[nextWriteIndex] = new ReactPromise("pending", null, null)); nextWriteIndex < buffer.length; ) triggerErrorOnChunk(response, buffer[nextWriteIndex++], error); } }); return iterator; } function parseModelString(response, obj, key, value, reference, arrayRoot) { if ("$" === value[0]) { switch (value[1]) { case "$": return null !== arrayRoot && bumpArrayCount(arrayRoot, value.length - 1, response), value.slice(1); case "@": return obj = parseInt(value.slice(2), 16), getChunk(response, obj); case "h": return arrayRoot = value.slice(2), getOutlinedModel(response, arrayRoot, obj, key, null, loadServerReference$1); case "T": if (void 0 === reference || void 0 === response._temporaryReferences) throw Error("Could not reference an opaque temporary reference. This is likely due to misconfiguring the temporaryReferences options on the server."); return createTemporaryReference(response._temporaryReferences, reference); case "Q": return arrayRoot = value.slice(2), getOutlinedModel(response, arrayRoot, obj, key, null, createMap); case "W": return arrayRoot = value.slice(2), getOutlinedModel(response, arrayRoot, obj, key, null, createSet); case "K": obj = value.slice(2); obj = response._prefix + obj + "_"; key = new FormData(); response = response._formData; arrayRoot = Array.from(response.keys()); for (value = 0; value < arrayRoot.length; value++) if (reference = arrayRoot[value], reference.startsWith(obj)) { for (var entries = response.getAll(reference), newKey = reference.slice(obj.length), j = 0; j < entries.length; j++) key.append(newKey, entries[j]); response.delete(reference); } return key; case "i": return arrayRoot = value.slice(2), getOutlinedModel(response, arrayRoot, obj, key, null, extractIterator); case "I": return Infinity; case "-": return "$-0" === value ? -0 : -Infinity; case "N": return NaN; case "u": return; case "D": return new Date(Date.parse(value.slice(2))); case "n": obj = value.slice(2); if (300 < obj.length) throw Error("BigInt is too large. Received " + obj.length + " digits but the limit is 300."); null !== arrayRoot && bumpArrayCount(arrayRoot, obj.length, response); return BigInt(obj); case "A": return parseTypedArray(response, value, ArrayBuffer, 1, obj, key, arrayRoot); case "O": return parseTypedArray(response, value, Int8Array, 1, obj, key, arrayRoot); case "o": return parseTypedArray(response, value, Uint8Array, 1, obj, key, arrayRoot); case "U": return parseTypedArray(response, value, Uint8ClampedArray, 1, obj, key, arrayRoot); case "S": return parseTypedArray(response, value, Int16Array, 2, obj, key, arrayRoot); case "s": return parseTypedArray(response, value, Uint16Array, 2, obj, key, arrayRoot); case "L": return parseTypedArray(response, value, Int32Array, 4, obj, key, arrayRoot); case "l": return parseTypedArray(response, value, Uint32Array, 4, obj, key, arrayRoot); case "G": return parseTypedArray(response, value, Float32Array, 4, obj, key, arrayRoot); case "g": return parseTypedArray(response, value, Float64Array, 8, obj, key, arrayRoot); case "M": return parseTypedArray(response, value, BigInt64Array, 8, obj, key, arrayRoot); case "m": return parseTypedArray(response, value, BigUint64Array, 8, obj, key, arrayRoot); case "V": return parseTypedArray(response, value, DataView, 1, obj, key, arrayRoot); case "B": return obj = parseInt(value.slice(2), 16), response._formData.get(response._prefix + obj); case "R": return parseReadableStream(response, value, void 0); case "r": return parseReadableStream(response, value, "bytes"); case "X": return parseAsyncIterable(response, value, false); case "x": return parseAsyncIterable(response, value, true); } value = value.slice(1); return getOutlinedModel(response, value, obj, key, arrayRoot, createModel); } null !== arrayRoot && bumpArrayCount(arrayRoot, value.length, response); return value; } function createResponse(bundlerConfig, formFieldPrefix, temporaryReferences) { var backingFormData = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : new FormData(), arraySizeLimit = 4 < arguments.length && void 0 !== arguments[4] ? arguments[4] : 1e6, chunks = /* @__PURE__ */ new Map(); return { _bundlerConfig: bundlerConfig, _prefix: formFieldPrefix, _formData: backingFormData, _chunks: chunks, _closed: false, _closedReason: null, _temporaryReferences: temporaryReferences, _rootArrayContexts: /* @__PURE__ */ new WeakMap(), _arraySizeLimit: arraySizeLimit }; } function close(response) { reportGlobalError(response, Error("Connection closed.")); } function loadServerReference(bundlerConfig, metaData) { var id = metaData.id; if ("string" !== typeof id) return null; var serverReference = resolveServerReference(bundlerConfig, id); bundlerConfig = preloadModule(serverReference); metaData = metaData.bound; return metaData instanceof Promise ? Promise.all([ metaData, bundlerConfig ]).then(function(_ref) { _ref = _ref[0]; var fn = requireModule2(serverReference); if (1e3 < _ref.length) throw Error("Server Function has too many bound arguments. Received " + _ref.length + " but the limit is 1000."); return fn.bind.apply(fn, [ null ].concat(_ref)); }) : bundlerConfig ? Promise.resolve(bundlerConfig).then(function() { return requireModule2(serverReference); }) : Promise.resolve(requireModule2(serverReference)); } function decodeBoundActionMetaData(body, serverManifest, formFieldPrefix, arraySizeLimit) { body = createResponse(serverManifest, formFieldPrefix, void 0, body, arraySizeLimit); close(body); body = getChunk(body, 0); body.then(function() { }); if ("fulfilled" !== body.status) throw body.reason; return body.value; } reactServerDomWebpackServer_edge_production.createClientModuleProxy = function(moduleId) { moduleId = registerClientReferenceImpl({}, moduleId, false); return new Proxy(moduleId, proxyHandlers$1); }; reactServerDomWebpackServer_edge_production.createTemporaryReferenceSet = function() { return /* @__PURE__ */ new WeakMap(); }; reactServerDomWebpackServer_edge_production.decodeAction = function(body, serverManifest) { var formData = new FormData(), action = null, seenActions = /* @__PURE__ */ new Set(); body.forEach(function(value, key) { key.startsWith("$ACTION_") ? key.startsWith("$ACTION_REF_") ? seenActions.has(key) || (seenActions.add(key), value = "$ACTION_" + key.slice(12) + ":", value = decodeBoundActionMetaData(body, serverManifest, value), action = loadServerReference(serverManifest, value)) : key.startsWith("$ACTION_ID_") && !seenActions.has(key) && (seenActions.add(key), value = key.slice(11), action = loadServerReference(serverManifest, { id: value, bound: null })) : formData.append(key, value); }); return null === action ? null : action.then(function(fn) { return fn.bind(null, formData); }); }; reactServerDomWebpackServer_edge_production.decodeFormState = function(actionResult, body, serverManifest) { var keyPath = body.get("$ACTION_KEY"); if ("string" !== typeof keyPath) return Promise.resolve(null); var metaData = null; body.forEach(function(value, key) { key.startsWith("$ACTION_REF_") && (value = "$ACTION_" + key.slice(12) + ":", metaData = decodeBoundActionMetaData(body, serverManifest, value)); }); if (null === metaData) return Promise.resolve(null); var referenceId = metaData.id; return Promise.resolve(metaData.bound).then(function(bound) { return null === bound ? null : [ actionResult, keyPath, referenceId, bound.length - 1 ]; }); }; reactServerDomWebpackServer_edge_production.decodeReply = function(body, webpackMap, options) { if ("string" === typeof body) { var form = new FormData(); form.append("0", body); body = form; } body = createResponse(webpackMap, "", options ? options.temporaryReferences : void 0, body, options ? options.arraySizeLimit : void 0); webpackMap = getChunk(body, 0); close(body); return webpackMap; }; reactServerDomWebpackServer_edge_production.decodeReplyFromAsyncIterable = function(iterable, webpackMap, options) { function progress(entry) { if (entry.done) close(response); else { entry = entry.value; var name = entry[0]; entry = entry[1]; if ("string" === typeof entry) { response._formData.append(name, entry); var prefix2 = response._prefix; if (name.startsWith(prefix2)) { var chunks = response._chunks; name = +name.slice(prefix2.length); (chunks = chunks.get(name)) && resolveModelChunk(response, chunks, entry, name); } } else response._formData.append(name, entry); iterator.next().then(progress, error); } } function error(reason) { reportGlobalError(response, reason); "function" === typeof iterator.throw && iterator.throw(reason).then(error, error); } var iterator = iterable[ASYNC_ITERATOR](), response = createResponse(webpackMap, "", options ? options.temporaryReferences : void 0, void 0, options ? options.arraySizeLimit : void 0); iterator.next().then(progress, error); return getChunk(response, 0); }; reactServerDomWebpackServer_edge_production.prerender = function(model, webpackMap, options) { return new Promise(function(resolve, reject) { var request = new RequestInstance(21, model, webpackMap, options ? options.onError : void 0, options ? options.onPostpone : void 0, function() { var stream = new ReadableStream({ type: "bytes", pull: function(controller) { startFlowing(request, controller); }, cancel: function(reason) { request.destination = null; abort(request, reason); } }, { highWaterMark: 0 }); resolve({ prelude: stream }); }, reject, options ? options.identifierPrefix : void 0, options ? options.temporaryReferences : void 0); if (options && options.signal) { var signal = options.signal; if (signal.aborted) abort(request, signal.reason); else { var listener = function() { abort(request, signal.reason); signal.removeEventListener("abort", listener); }; signal.addEventListener("abort", listener); } } startWork(request); }); }; reactServerDomWebpackServer_edge_production.registerClientReference = function(proxyImplementation, id, exportName) { return registerClientReferenceImpl(proxyImplementation, id + "#" + exportName, false); }; reactServerDomWebpackServer_edge_production.registerServerReference = function(reference, id, exportName) { return Object.defineProperties(reference, { $$typeof: { value: SERVER_REFERENCE_TAG }, $$id: { value: null === exportName ? id : id + "#" + exportName, configurable: true }, $$bound: { value: null, configurable: true }, bind: { value: bind, configurable: true }, toString: serverReferenceToString }); }; reactServerDomWebpackServer_edge_production.renderToReadableStream = function(model, webpackMap, options) { var request = new RequestInstance(20, model, webpackMap, options ? options.onError : void 0, options ? options.onPostpone : void 0, noop, noop, options ? options.identifierPrefix : void 0, options ? options.temporaryReferences : void 0); if (options && options.signal) { var signal = options.signal; if (signal.aborted) abort(request, signal.reason); else { var listener = function() { abort(request, signal.reason); signal.removeEventListener("abort", listener); }; signal.addEventListener("abort", listener); } } return new ReadableStream({ type: "bytes", start: function() { startWork(request); }, pull: function(controller) { startFlowing(request, controller); }, cancel: function(reason) { request.destination = null; abort(request, reason); } }, { highWaterMark: 0 }); }; return reactServerDomWebpackServer_edge_production; } var hasRequiredServer_edge; function requireServer_edge() { if (hasRequiredServer_edge) return server_edge; hasRequiredServer_edge = 1; var s; { s = requireReactServerDomWebpackServer_edge_production(); } server_edge.renderToReadableStream = s.renderToReadableStream; server_edge.decodeReply = s.decodeReply; server_edge.decodeReplyFromAsyncIterable = s.decodeReplyFromAsyncIterable; server_edge.decodeAction = s.decodeAction; server_edge.decodeFormState = s.decodeFormState; server_edge.registerServerReference = s.registerServerReference; server_edge.registerClientReference = s.registerClientReference; server_edge.createClientModuleProxy = s.createClientModuleProxy; server_edge.createTemporaryReferenceSet = s.createTemporaryReferenceSet; return server_edge; } var server_edgeExports = requireServer_edge(); let init = false; let requireModule; function setRequireModule(options) { if (init) return; init = true; requireModule = (id) => { return options.load(removeReferenceCacheTag(id)); }; globalThis.__vite_rsc_server_require__ = memoize(async (id) => { if (id.startsWith(SERVER_DECODE_CLIENT_PREFIX)) { id = id.slice(SERVER_DECODE_CLIENT_PREFIX.length); id = removeReferenceCacheTag(id); const target = {}; const getOrCreateClientReference = (name) => { return target[name] ?? (target[name] = server_edgeExports.registerClientReference(() => { throw new Error(`Unexpectedly client reference export '${name}' is called on server`); }, id, name)); }; return new Proxy(target, { getOwnPropertyDescriptor(_target, name) { if (typeof name !== "string" || name === "then") return Reflect.getOwnPropertyDescriptor(target, name); getOrCreateClientReference(name); return Reflect.getOwnPropertyDescriptor(target, name); } }); } return requireModule(id); }); setInternalRequire(); } async function loadServerAction(id) { const [file, name] = id.split("#"); return (await requireModule(file))[name]; } function createServerManifest() { const cacheTag = ""; return new Proxy({}, { get(_target, $$id, _receiver) { tinyassert(typeof $$id === "string"); let [id, name] = $$id.split("#"); tinyassert(id); tinyassert(name); return { id: SERVER_REFERENCE_PREFIX + id + cacheTag, name, chunks: [], async: true }; } }); } function createServerDecodeClientManifest() { return new Proxy({}, { get(_target, id) { return new Proxy({}, { get(_target2, name) { return { id: SERVER_REFERENCE_PREFIX + SERVER_DECODE_CLIENT_PREFIX + id, name, chunks: [], async: true }; } }); } }); } function createClientManifest(options) { const cacheTag = ""; return new Proxy({}, { get(_target, $$id, _receiver) { var _a2; tinyassert(typeof $$id === "string"); let [id, name] = $$id.split("#"); tinyassert(id); tinyassert(name); (_a2 = options == null ? void 0 : options.onClientReference) == null ? void 0 : _a2.call(options, { id, name }); return { id: id + cacheTag, name, chunks: [], async: true }; } }); } var client_edge = { exports: {} }; var reactServerDomWebpackClient_edge_production = {}; var hasRequiredReactServerDomWebpackClient_edge_production; function requireReactServerDomWebpackClient_edge_production() { if (hasRequiredReactServerDomWebpackClient_edge_production) return reactServerDomWebpackClient_edge_production; hasRequiredReactServerDomWebpackClient_edge_production = 1; var ReactDOM = requireReactDom_reactServer(), decoderOptions = { stream: true }, hasOwnProperty = Object.prototype.hasOwnProperty; function resolveClientReference(bundlerConfig, metadata) { if (bundlerConfig) { var moduleExports = bundlerConfig[metadata[0]]; if (bundlerConfig = moduleExports && moduleExports[metadata[2]]) moduleExports = bundlerConfig.name; else { bundlerConfig = moduleExports && moduleExports["*"]; if (!bundlerConfig) throw Error('Could not find the module "' + metadata[0] + '" in the React Server Consumer Manifest. This is probably a bug in the React Server Components bundler.'); moduleExports = metadata[2]; } return 4 === metadata.length ? [ bundlerConfig.id, bundlerConfig.chunks, moduleExports, 1 ] : [ bundlerConfig.id, bundlerConfig.chunks, moduleExports ]; } return metadata; } function resolveServerReference(bundlerConfig, id) { var name = "", resolvedModuleData = bundlerConfig[id]; if (resolvedModuleData) name = resolvedModuleData.name; else { var idx = id.lastIndexOf("#"); -1 !== idx && (name = id.slice(idx + 1), resolvedModuleData = bundlerConfig[id.slice(0, idx)]); if (!resolvedModuleData) throw Error('Could not find the module "' + id + '" in the React Server Manifest. This is probably a bug in the React Server Components bundler.'); } return resolvedModuleData.async ? [ resolvedModuleData.id, resolvedModuleData.chunks, name, 1 ] : [ resolvedModuleData.id, resolvedModuleData.chunks, name ]; } var chunkCache = /* @__PURE__ */ new Map(); function requireAsyncModule(id) { var promise = __vite_rsc_require__(id); if ("function" !== typeof promise.then || "fulfilled" === promise.status) return null; promise.then(function(value) { promise.status = "fulfilled"; promise.value = value; }, function(reason) { promise.status = "rejected"; promise.reason = reason; }); return promise; } function ignoreReject() { } function preloadModule(metadata) { for (var chunks = metadata[1], promises = [], i = 0; i < chunks.length; ) { var chunkId = chunks[i++]; chunks[i++]; var entry = chunkCache.get(chunkId); if (void 0 === entry) { entry = __webpack_chunk_load__(chunkId); promises.push(entry); var resolve = chunkCache.set.bind(chunkCache, chunkId, null); entry.then(resolve, ignoreReject); chunkCache.set(chunkId, entry); } else null !== entry && promises.push(entry); } return 4 === metadata.length ? 0 === promises.length ? requireAsyncModule(metadata[0]) : Promise.all(promises).then(function() { return requireAsyncModule(metadata[0]); }) : 0 < promises.length ? Promise.all(promises) : null; } function requireModule2(metadata) { var moduleExports = __vite_rsc_require__(metadata[0]); if (4 === metadata.length && "function" === typeof moduleExports.then) if ("fulfilled" === moduleExports.status) moduleExports = moduleExports.value; else throw moduleExports.reason; if ("*" === metadata[2]) return moduleExports; if ("" === metadata[2]) return moduleExports.__esModule ? moduleExports.default : moduleExports; if (hasOwnProperty.call(moduleExports, metadata[2])) return moduleExports[metadata[2]]; } function prepareDestinationWithChunks(moduleLoading, chunks, nonce$jscomp$0) { if (null !== moduleLoading) for (var i = 1; i < chunks.length; i += 2) { var nonce = nonce$jscomp$0, JSCompiler_temp_const = ReactDOMSharedInternals.d, JSCompiler_temp_const$jscomp$0 = JSCompiler_temp_const.X, JSCompiler_temp_const$jscomp$1 = moduleLoading.prefix + chunks[i]; var JSCompiler_inline_result = moduleLoading.crossOrigin; JSCompiler_inline_result = "string" === typeof JSCompiler_inline_result ? "use-credentials" === JSCompiler_inline_result ? JSCompiler_inline_result : "" : void 0; JSCompiler_temp_const$jscomp$0.call(JSCompiler_temp_const, JSCompiler_temp_const$jscomp$1, { crossOrigin: JSCompiler_inline_result, nonce }); } } var ReactDOMSharedInternals = ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator; function getIteratorFn(maybeIterable) { if (null === maybeIterable || "object" !== typeof maybeIterable) return null; maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"]; return "function" === typeof maybeIterable ? maybeIterable : null; } var ASYNC_ITERATOR = Symbol.asyncIterator, isArrayImpl = Array.isArray, getPrototypeOf = Object.getPrototypeOf, ObjectPrototype = Object.prototype, knownServerReferences = /* @__PURE__ */ new WeakMap(); function serializeNumber(number) { return Number.isFinite(number) ? 0 === number && -Infinity === 1 / number ? "$-0" : number : Infinity === number ? "$Infinity" : -Infinity === number ? "$-Infinity" : "$NaN"; } function processReply(root, formFieldPrefix, temporaryReferences, resolve, reject) { function serializeTypedArray(tag, typedArray) { typedArray = new Blob([ new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength) ]); var blobId = nextPartId++; null === formData && (formData = new FormData()); formData.append(formFieldPrefix + blobId, typedArray); return "$" + tag + blobId.toString(16); } function serializeBinaryReader(reader) { function progress(entry) { entry.done ? (entry = nextPartId++, data.append(formFieldPrefix + entry, new Blob(buffer)), data.append(formFieldPrefix + streamId, '"$o' + entry.toString(16) + '"'), data.append(formFieldPrefix + streamId, "C"), pendingParts--, 0 === pendingParts && resolve(data)) : (buffer.push(entry.value), reader.read(new Uint8Array(1024)).then(progress, reject)); } null === formData && (formData = new FormData()); var data = formData; pendingParts++; var streamId = nextPartId++, buffer = []; reader.read(new Uint8Array(1024)).then(progress, reject); return "$r" + streamId.toString(16); } function serializeReader(reader) { function progress(entry) { if (entry.done) data.append(formFieldPrefix + streamId, "C"), pendingParts--, 0 === pendingParts && resolve(data); else try { var partJSON = JSON.stringify(entry.value, resolveToJSON); data.append(formFieldPrefix + streamId, partJSON); reader.read().then(progress, reject); } catch (x) { reject(x); } } null === formData && (formData = new FormData()); var data = formData; pendingParts++; var streamId = nextPartId++; reader.read().then(progress, reject); return "$R" + streamId.toString(16); } function serializeReadableStream(stream) { try { var binaryReader = stream.getReader({ mode: "byob" }); } catch (x) { return serializeReader(stream.getReader()); } return serializeBinaryReader(binaryReader); } function serializeAsyncIterable(iterable, iterator) { function progress(entry) { if (entry.done) { if (void 0 === entry.value) data.append(formFieldPrefix + streamId, "C"); else try { var partJSON = JSON.stringify(entry.value, resolveToJSON); data.append(formFieldPrefix + streamId, "C" + partJSON); } catch (x) { reject(x); return; } pendingParts--; 0 === pendingParts && resolve(data); } else try { var partJSON$21 = JSON.stringify(entry.value, resolveToJSON); data.append(formFieldPrefix + streamId, partJSON$21); iterator.next().then(progress, reject); } catch (x$22) { reject(x$22); } } null === formData && (formData = new FormData()); var data = formData; pendingParts++; var streamId = nextPartId++; iterable = iterable === iterator; iterator.next().then(progress, reject); return "$" + (iterable ? "x" : "X") + streamId.toString(16); } function resolveToJSON(key, value) { if (null === value) return null; if ("object" === typeof value) { switch (value.$$typeof) { case REACT_ELEMENT_TYPE: if (void 0 !== temporaryReferences && -1 === key.indexOf(":")) { var parentReference = writtenObjects.get(this); if (void 0 !== parentReference) return temporaryReferences.set(parentReference + ":" + key, value), "$T"; } throw Error("React Element cannot be passed to Server Functions from the Client without a temporary reference set. Pass a TemporaryReferenceSet to the options."); case REACT_LAZY_TYPE: parentReference = value._payload; var init2 = value._init; null === formData && (formData = new FormData()); pendingParts++; try { var resolvedModel = init2(parentReference), lazyId = nextPartId++, partJSON = serializeModel(resolvedModel, lazyId); formData.append(formFieldPrefix + lazyId, partJSON); return "$" + lazyId.toString(16); } catch (x) { if ("object" === typeof x && null !== x && "function" === typeof x.then) { pendingParts++; var lazyId$23 = nextPartId++; parentReference = function() { try { var partJSON$24 = serializeModel(value, lazyId$23), data$25 = formData; data$25.append(formFieldPrefix + lazyId$23, partJSON$24); pendingParts--; 0 === pendingParts && resolve(data$25); } catch (reason) { reject(reason); } }; x.then(parentReference, parentReference); return "$" + lazyId$23.toString(16); } reject(x); return null; } finally { pendingParts--; } } parentReference = writtenObjects.get(value); if ("function" === typeof value.then) { if (void 0 !== parentReference) if (modelRoot === value) modelRoot = null; else return parentReference; null === formData && (formData = new FormData()); pendingParts++; var promiseId = nextPartId++; key = "$@" + promiseId.toString(16); writtenObjects.set(value, key); value.then(function(partValue) { try { var previousReference = writtenObjects.get(partValue); var partJSON$27 = void 0 !== previousReference ? JSON.stringify(previousReference) : serializeModel(partValue, promiseId); partValue = formData; partValue.append(formFieldPrefix + promiseId, partJSON$27); pendingParts--; 0 === pendingParts && resolve(partValue); } catch (reason) { reject(reason); } }, reject); return key; } if (void 0 !== parentReference) if (modelRoot === value) modelRoot = null; else return parentReference; else -1 === key.indexOf(":") && (parentReference = writtenObjects.get(this), void 0 !== parentReference && (key = parentReference + ":" + key, writtenObjects.set(value, key), void 0 !== temporaryReferences && temporaryReferences.set(key, value))); if (isArrayImpl(value)) return value; if (value instanceof FormData) { null === formData && (formData = new FormData()); var data$31 = formData; key = nextPartId++; var prefix2 = formFieldPrefix + key + "_"; value.forEach(function(originalValue, originalKey) { data$31.append(prefix2 + originalKey, originalValue); }); return "$K" + key.toString(16); } if (value instanceof Map) return key = nextPartId++, parentReference = serializeModel(Array.from(value), key), null === formData && (formData = new FormData()), formData.append(formFieldPrefix + key, parentReference), "$Q" + key.toString(16); if (value instanceof Set) return key = nextPartId++, parentReference = serializeModel(Array.from(value), key), null === formData && (formData = new FormData()), formData.append(formFieldPrefix + key, parentReference), "$W" + key.toString(16); if (value instanceof ArrayBuffer) return key = new Blob([ value ]), parentReference = nextPartId++, null === formData && (formData = new FormData()), formData.append(formFieldPrefix + parentReference, key), "$A" + parentReference.toString(16); if (value instanceof Int8Array) return serializeTypedArray("O", value); if (value instanceof Uint8Array) return serializeTypedArray("o", value); if (value instanceof Uint8ClampedArray) return serializeTypedArray("U", value); if (value instanceof Int16Array) return serializeTypedArray("S", value); if (value instanceof Uint16Array) return serializeTypedArray("s", value); if (value instanceof Int32Array) return serializeTypedArray("L", value); if (value instanceof Uint32Array) return serializeTypedArray("l", value); if (value instanceof Float32Array) return serializeTypedArray("G", value); if (value instanceof Float64Array) return serializeTypedArray("g", value); if (value instanceof BigInt64Array) return serializeTypedArray("M", value); if (value instanceof BigUint64Array) return serializeTypedArray("m", value); if (value instanceof DataView) return serializeTypedArray("V", value); if ("function" === typeof Blob && value instanceof Blob) return null === formData && (formData = new FormData()), key = nextPartId++, formData.append(formFieldPrefix + key, value), "$B" + key.toString(16); if (key = getIteratorFn(value)) return parentReference = key.call(value), parentReference === value ? (key = nextPartId++, parentReference = serializeModel(Array.from(parentReference), key), null === formData && (formData = new FormData()), formData.append(formFieldPrefix + key, parentReference), "$i" + key.toString(16)) : Array.from(parentReference); if ("function" === typeof ReadableStream && value instanceof ReadableStream) return serializeReadableStream(value); key = value[ASYNC_ITERATOR]; if ("function" === typeof key) return serializeAsyncIterable(value, key.call(value)); key = getPrototypeOf(value); if (key !== ObjectPrototype && (null === key || null !== getPrototypeOf(key))) { if (void 0 === temporaryReferences) throw Error("Only plain objects, and a few built-ins, can be passed to Server Functions. Classes or null prototypes are not supported."); return "$T"; } return value; } if ("string" === typeof value) { if ("Z" === value[value.length - 1] && this[key] instanceof Date) return "$D" + value; key = "$" === value[0] ? "$" + value : value; return key; } if ("boolean" === typeof value) return value; if ("number" === typeof value) return serializeNumber(value); if ("undefined" === typeof value) return "$undefined"; if ("function" === typeof value) { parentReference = knownServerReferences.get(value); if (void 0 !== parentReference) { key = writtenObjects.get(value); if (void 0 !== key) return key; key = JSON.stringify({ id: parentReference.id, bound: parentReference.bound }, resolveToJSON); null === formData && (formData = new FormData()); parentReference = nextPartId++; formData.set(formFieldPrefix + parentReference, key); key = "$h" + parentReference.toString(16); writtenObjects.set(value, key); return key; } if (void 0 !== temporaryReferences && -1 === key.indexOf(":") && (parentReference = writtenObjects.get(this), void 0 !== parentReference)) return temporaryReferences.set(parentReference + ":" + key, value), "$T"; throw Error("Client Functions cannot be passed directly to Server Functions. Only Functions passed from the Server can be passed back again."); } if ("symbol" === typeof value) { if (void 0 !== temporaryReferences && -1 === key.indexOf(":") && (parentReference = writtenObjects.get(this), void 0 !== parentReference)) return temporaryReferences.set(parentReference + ":" + key, value), "$T"; throw Error("Symbols cannot be passed to a Server Function without a temporary reference set. Pass a TemporaryReferenceSet to the options."); } if ("bigint" === typeof value) return "$n" + value.toString(10); throw Error("Type " + typeof value + " is not supported as an argument to a Server Function."); } function serializeModel(model, id) { "object" === typeof model && null !== model && (id = "$" + id.toString(16), writtenObjects.set(model, id), void 0 !== temporaryReferences && temporaryReferences.set(id, model)); modelRoot = model; return JSON.stringify(model, resolveToJSON); } var nextPartId = 1, pendingParts = 0, formData = null, writtenObjects = /* @__PURE__ */ new WeakMap(), modelRoot = root, json = serializeModel(root, 0); null === formData ? resolve(json) : (formData.set(formFieldPrefix + "0", json), 0 === pendingParts && resolve(formData)); return function() { 0 < pendingParts && (pendingParts = 0, null === formData ? resolve(json) : resolve(formData)); }; } var boundCache = /* @__PURE__ */ new WeakMap(); function encodeFormData(reference) { var resolve, reject, thenable = new Promise(function(res, rej) { resolve = res; reject = rej; }); processReply(reference, "", void 0, function(body) { if ("string" === typeof body) { var data = new FormData(); data.append("0", body); body = data; } thenable.status = "fulfilled"; thenable.value = body; resolve(body); }, function(e) { thenable.status = "rejected"; thenable.reason = e; reject(e); }); return thenable; } function defaultEncodeFormAction(identifierPrefix) { var referenceClosure = knownServerReferences.get(this); if (!referenceClosure) throw Error("Tried to encode a Server Action from a different instance than the encoder is from. This is a bug in React."); var data = null; if (null !== referenceClosure.bound) { data = boundCache.get(referenceClosure); data || (data = encodeFormData({ id: referenceClosure.id, bound: referenceClosure.bound }), boundCache.set(referenceClosure, data)); if ("rejected" === data.status) throw data.reason; if ("fulfilled" !== data.status) throw data; referenceClosure = data.value; var prefixedData = new FormData(); referenceClosure.forEach(function(value, key) { prefixedData.append("$ACTION_" + identifierPrefix + ":" + key, value); }); data = prefixedData; referenceClosure = "$ACTION_REF_" + identifierPrefix; } else referenceClosure = "$ACTION_ID_" + referenceClosure.id; return { name: referenceClosure, method: "POST", encType: "multipart/form-data", data }; } function isSignatureEqual(referenceId, numberOfBoundArgs) { var referenceClosure = knownServerReferences.get(this); if (!referenceClosure) throw Error("Tried to encode a Server Action from a different instance than the encoder is from. This is a bug in React."); if (referenceClosure.id !== referenceId) return false; var boundPromise = referenceClosure.bound; if (null === boundPromise) return 0 === numberOfBoundArgs; switch (boundPromise.status) { case "fulfilled": return boundPromise.value.length === numberOfBoundArgs; case "pending": throw boundPromise; case "rejected": throw boundPromise.reason; default: throw "string" !== typeof boundPromise.status && (boundPromise.status = "pending", boundPromise.then(function(boundArgs) { boundPromise.status = "fulfilled"; boundPromise.value = boundArgs; }, function(error) { boundPromise.status = "rejected"; boundPromise.reason = error; })), boundPromise; } } function registerBoundServerReference(reference, id, bound, encodeFormAction) { knownServerReferences.has(reference) || (knownServerReferences.set(reference, { id, originalBind: reference.bind, bound }), Object.defineProperties(reference, { $$FORM_ACTION: { value: void 0 === encodeFormAction ? defaultEncodeFormAction : function() { var referenceClosure = knownServerReferences.get(this); if (!referenceClosure) throw Error("Tried to encode a Server Action from a different instance than the encoder is from. This is a bug in React."); var boundPromise = referenceClosure.bound; null === boundPromise && (boundPromise = Promise.resolve([])); return encodeFormAction(referenceClosure.id, boundPromise); } }, $$IS_SIGNATURE_EQUAL: { value: isSignatureEqual }, bind: { value: bind } })); } var FunctionBind = Function.prototype.bind, ArraySlice = Array.prototype.slice; function bind() { var referenceClosure = knownServerReferences.get(this); if (!referenceClosure) return FunctionBind.apply(this, arguments); var newFn = referenceClosure.originalBind.apply(this, arguments), args = ArraySlice.call(arguments, 1), boundPromise = null; boundPromise = null !== referenceClosure.bound ? Promise.resolve(referenceClosure.bound).then(function(boundArgs) { return boundArgs.concat(args); }) : Promise.resolve(args); knownServerReferences.set(newFn, { id: referenceClosure.id, originalBind: newFn.bind, bound: boundPromise }); Object.defineProperties(newFn, { $$FORM_ACTION: { value: this.$$FORM_ACTION }, $$IS_SIGNATURE_EQUAL: { value: isSignatureEqual }, bind: { value: bind } }); return newFn; } function createBoundServerReference(metaData, callServer, encodeFormAction) { function action() { var args = Array.prototype.slice.call(arguments); return bound ? "fulfilled" === bound.status ? callServer(id, bound.value.concat(args)) : Promise.resolve(bound).then(function(boundArgs) { return callServer(id, boundArgs.concat(args)); }) : callServer(id, args); } var id = metaData.id, bound = metaData.bound; registerBoundServerReference(action, id, bound, encodeFormAction); return action; } function createServerReference$1(id, callServer, encodeFormAction) { function action() { var args = Array.prototype.slice.call(arguments); return callServer(id, args); } registerBoundServerReference(action, id, null, encodeFormAction); return action; } function ReactPromise(status, value, reason) { this.status = status; this.value = value; this.reason = reason; } ReactPromise.prototype = Object.create(Promise.prototype); ReactPromise.prototype.then = function(resolve, reject) { switch (this.status) { case "resolved_model": initializeModelChunk(this); break; case "resolved_module": initializeModuleChunk(this); } switch (this.status) { case "fulfilled": "function" === typeof resolve && resolve(this.value); break; case "pending": case "blocked": "function" === typeof resolve && (null === this.value && (this.value = []), this.value.push(resolve)); "function" === typeof reject && (null === this.reason && (this.reason = []), this.reason.push(reject)); break; case "halted": break; default: "function" === typeof reject && reject(this.reason); } }; function readChunk(chunk) { switch (chunk.status) { case "resolved_model": initializeModelChunk(chunk); break; case "resolved_module": initializeModuleChunk(chunk); } switch (chunk.status) { case "fulfilled": return chunk.value; case "pending": case "blocked": case "halted": throw chunk; default: throw chunk.reason; } } function wakeChunk(listeners, value, chunk) { for (var i = 0; i < listeners.length; i++) { var listener = listeners[i]; "function" === typeof listener ? listener(value) : fulfillReference(listener, value); } } function rejectChunk(listeners, error) { for (var i = 0; i < listeners.length; i++) { var listener = listeners[i]; "function" === typeof listener ? listener(error) : rejectReference(listener, error); } } function resolveBlockedCycle(resolvedChunk, reference) { var referencedChunk = reference.handler.chunk; if (null === referencedChunk) return null; if (referencedChunk === resolvedChunk) return reference.handler; reference = referencedChunk.value; if (null !== reference) for (referencedChunk = 0; referencedChunk < reference.length; referencedChunk++) { var listener = reference[referencedChunk]; if ("function" !== typeof listener && (listener = resolveBlockedCycle(resolvedChunk, listener), null !== listener)) return listener; } return null; } function wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners) { switch (chunk.status) { case "fulfilled": wakeChunk(resolveListeners, chunk.value); break; case "blocked": for (var i = 0; i < resolveListeners.length; i++) { var listener = resolveListeners[i]; if ("function" !== typeof listener) { var cyclicHandler = resolveBlockedCycle(chunk, listener); if (null !== cyclicHandler) switch (fulfillReference(listener, cyclicHandler.value), resolveListeners.splice(i, 1), i--, null !== rejectListeners && (listener = rejectListeners.indexOf(listener), -1 !== listener && rejectListeners.splice(listener, 1)), chunk.status) { case "fulfilled": wakeChunk(resolveListeners, chunk.value); return; case "rejected": null !== rejectListeners && rejectChunk(rejectListeners, chunk.reason); return; } } } case "pending": if (chunk.value) for (i = 0; i < resolveListeners.length; i++) chunk.value.push(resolveListeners[i]); else chunk.value = resolveListeners; if (chunk.reason) { if (rejectListeners) for (resolveListeners = 0; resolveListeners < rejectListeners.length; resolveListeners++) chunk.reason.push(rejectListeners[resolveListeners]); } else chunk.reason = rejectListeners; break; case "rejected": rejectListeners && rejectChunk(rejectListeners, chunk.reason); } } function triggerErrorOnChunk(response, chunk, error) { "pending" !== chunk.status && "blocked" !== chunk.status ? chunk.reason.error(error) : (response = chunk.reason, chunk.status = "rejected", chunk.reason = error, null !== response && rejectChunk(response, error)); } function createResolvedIteratorResultChunk(response, value, done) { return new ReactPromise("resolved_model", (done ? '{"done":true,"value":' : '{"done":false,"value":') + value + "}", response); } function resolveIteratorResultChunk(response, chunk, value, done) { resolveModelChunk(response, chunk, (done ? '{"done":true,"value":' : '{"done":false,"value":') + value + "}"); } function resolveModelChunk(response, chunk, value) { if ("pending" !== chunk.status) chunk.reason.enqueueModel(value); else { var resolveListeners = chunk.value, rejectListeners = chunk.reason; chunk.status = "resolved_model"; chunk.value = value; chunk.reason = response; null !== resolveListeners && (initializeModelChunk(chunk), wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners)); } } function resolveModuleChunk(response, chunk, value) { if ("pending" === chunk.status || "blocked" === chunk.status) { response = chunk.value; var rejectListeners = chunk.reason; chunk.status = "resolved_module"; chunk.value = value; chunk.reason = null; null !== response && (initializeModuleChunk(chunk), wakeChunkIfInitialized(chunk, response, rejectListeners)); } } var initializingHandler = null; function initializeModelChunk(chunk) { var prevHandler = initializingHandler; initializingHandler = null; var resolvedModel = chunk.value, response = chunk.reason; chunk.status = "blocked"; chunk.value = null; chunk.reason = null; try { var value = JSON.parse(resolvedModel, response._fromJSON), resolveListeners = chunk.value; if (null !== resolveListeners) for (chunk.value = null, chunk.reason = null, resolvedModel = 0; resolvedModel < resolveListeners.length; resolvedModel++) { var listener = resolveListeners[resolvedModel]; "function" === typeof listener ? listener(value) : fulfillReference(listener, value, chunk); } if (null !== initializingHandler) { if (initializingHandler.errored) throw initializingHandler.reason; if (0 < initializingHandler.deps) { initializingHandler.value = value; initializingHandler.chunk = chunk; return; } } chunk.status = "fulfilled"; chunk.value = value; } catch (error) { chunk.status = "rejected", chunk.reason = error; } finally { initializingHandler = prevHandler; } } function initializeModuleChunk(chunk) { try { var value = requireModule2(chunk.value); chunk.status = "fulfilled"; chunk.value = value; } catch (error) { chunk.status = "rejected", chunk.reason = error; } } function reportGlobalError(weakResponse, error) { weakResponse._closed = true; weakResponse._closedReason = error; weakResponse._chunks.forEach(function(chunk) { "pending" === chunk.status ? triggerErrorOnChunk(weakResponse, chunk, error) : "fulfilled" === chunk.status && null !== chunk.reason && chunk.reason.error(error); }); } function createLazyChunkWrapper(chunk) { return { $$typeof: REACT_LAZY_TYPE, _payload: chunk, _init: readChunk }; } function getChunk(response, id) { var chunks = response._chunks, chunk = chunks.get(id); chunk || (chunk = response._closed ? new ReactPromise("rejected", null, response._closedReason) : new ReactPromise("pending", null, null), chunks.set(id, chunk)); return chunk; } function fulfillReference(reference, value) { var response = reference.response, handler = reference.handler, parentObject = reference.parentObject, key = reference.key, map = reference.map, path2 = reference.path; try { for (var i = 1; i < path2.length; i++) { for (; "object" === typeof value && null !== value && value.$$typeof === REACT_LAZY_TYPE; ) { var referencedChunk = value._payload; if (referencedChunk === handler.chunk) value = handler.value; else { switch (referencedChunk.status) { case "resolved_model": initializeModelChunk(referencedChunk); break; case "resolved_module": initializeModuleChunk(referencedChunk); } switch (referencedChunk.status) { case "fulfilled": value = referencedChunk.value; continue; case "blocked": var cyclicHandler = resolveBlockedCycle(referencedChunk, reference); if (null !== cyclicHandler) { value = cyclicHandler.value; continue; } case "pending": path2.splice(0, i - 1); null === referencedChunk.value ? referencedChunk.value = [ reference ] : referencedChunk.value.push(reference); null === referencedChunk.reason ? referencedChunk.reason = [ reference ] : referencedChunk.reason.push(reference); return; case "halted": return; default: rejectReference(reference, referencedChunk.reason); return; } } } var name = path2[i]; if ("object" === typeof value && null !== value && hasOwnProperty.call(value, name)) value = value[name]; else throw Error("Invalid reference."); } for (; "object" === typeof value && null !== value && value.$$typeof === REACT_LAZY_TYPE; ) { var referencedChunk$44 = value._payload; if (referencedChunk$44 === handler.chunk) value = handler.value; else { switch (referencedChunk$44.status) { case "resolved_model": initializeModelChunk(referencedChunk$44); break; case "resolved_module": initializeModuleChunk(referencedChunk$44); } switch (referencedChunk$44.status) { case "fulfilled": value = referencedChunk$44.value; continue; } break; } } var mappedValue = map(response, value, parentObject, key); "__proto__" !== key && (parentObject[key] = mappedValue); "" === key && null === handler.value && (handler.value = mappedValue); if (parentObject[0] === REACT_ELEMENT_TYPE && "object" === typeof handler.value && null !== handler.value && handler.value.$$typeof === REACT_ELEMENT_TYPE) { var element = handler.value; switch (key) { case "3": element.props = mappedValue; } } } catch (error) { rejectReference(reference, error); return; } handler.deps--; 0 === handler.deps && (reference = handler.chunk, null !== reference && "blocked" === reference.status && (value = reference.value, reference.status = "fulfilled", reference.value = handler.value, reference.reason = handler.reason, null !== value && wakeChunk(value, handler.value))); } function rejectReference(reference, error) { var handler = reference.handler; reference = reference.response; handler.errored || (handler.errored = true, handler.value = null, handler.reason = error, handler = handler.chunk, null !== handler && "blocked" === handler.status && triggerErrorOnChunk(reference, handler, error)); } function waitForReference(referencedChunk, parentObject, key, response, map, path2) { if (initializingHandler) { var handler = initializingHandler; handler.deps++; } else handler = initializingHandler = { parent: null, chunk: null, value: null, reason: null, deps: 1, errored: false }; parentObject = { response, handler, parentObject, key, map, path: path2 }; null === referencedChunk.value ? referencedChunk.value = [ parentObject ] : referencedChunk.value.push(parentObject); null === referencedChunk.reason ? referencedChunk.reason = [ parentObject ] : referencedChunk.reason.push(parentObject); return null; } function loadServerReference(response, metaData, parentObject, key) { if (!response._serverReferenceConfig) return createBoundServerReference(metaData, response._callServer, response._encodeFormAction); var serverReference = resolveServerReference(response._serverReferenceConfig, metaData.id), promise = preloadModule(serverReference); if (promise) metaData.bound && (promise = Promise.all([ promise, metaData.bound ])); else if (metaData.bound) promise = Promise.resolve(metaData.bound); else return promise = requireModule2(serverReference), registerBoundServerReference(promise, metaData.id, metaData.bound, response._encodeFormAction), promise; if (initializingHandler) { var handler = initializingHandler; handler.deps++; } else handler = initializingHandler = { parent: null, chunk: null, value: null, reason: null, deps: 1, errored: false }; promise.then(function() { var resolvedValue = requireModule2(serverReference); if (metaData.bound) { var boundArgs = metaData.bound.value.slice(0); boundArgs.unshift(null); resolvedValue = resolvedValue.bind.apply(resolvedValue, boundArgs); } registerBoundServerReference(resolvedValue, metaData.id, metaData.bound, response._encodeFormAction); "__proto__" !== key && (parentObject[key] = resolvedValue); "" === key && null === handler.value && (handler.value = resolvedValue); if (parentObject[0] === REACT_ELEMENT_TYPE && "object" === typeof handler.value && null !== handler.value && handler.value.$$typeof === REACT_ELEMENT_TYPE) switch (boundArgs = handler.value, key) { case "3": boundArgs.props = resolvedValue; } handler.deps--; 0 === handler.deps && (resolvedValue = handler.chunk, null !== resolvedValue && "blocked" === resolvedValue.status && (boundArgs = resolvedValue.value, resolvedValue.status = "fulfilled", resolvedValue.value = handler.value, resolvedValue.reason = null, null !== boundArgs && wakeChunk(boundArgs, handler.value))); }, function(error) { if (!handler.errored) { handler.errored = true; handler.value = null; handler.reason = error; var chunk = handler.chunk; null !== chunk && "blocked" === chunk.status && triggerErrorOnChunk(response, chunk, error); } }); return null; } function getOutlinedModel(response, reference, parentObject, key, map) { reference = reference.split(":"); var id = parseInt(reference[0], 16); id = getChunk(response, id); switch (id.status) { case "resolved_model": initializeModelChunk(id); break; case "resolved_module": initializeModuleChunk(id); } switch (id.status) { case "fulfilled": id = id.value; for (var i = 1; i < reference.length; i++) { for (; "object" === typeof id && null !== id && id.$$typeof === REACT_LAZY_TYPE; ) { id = id._payload; switch (id.status) { case "resolved_model": initializeModelChunk(id); break; case "resolved_module": initializeModuleChunk(id); } switch (id.status) { case "fulfilled": id = id.value; break; case "blocked": case "pending": return waitForReference(id, parentObject, key, response, map, reference.slice(i - 1)); case "halted": return initializingHandler ? (response = initializingHandler, response.deps++) : initializingHandler = { parent: null, chunk: null, value: null, reason: null, deps: 1, errored: false }, null; default: return initializingHandler ? (initializingHandler.errored = true, initializingHandler.value = null, initializingHandler.reason = id.reason) : initializingHandler = { parent: null, chunk: null, value: null, reason: id.reason, deps: 0, errored: true }, null; } } id = id[reference[i]]; } for (; "object" === typeof id && null !== id && id.$$typeof === REACT_LAZY_TYPE; ) { reference = id._payload; switch (reference.status) { case "resolved_model": initializeModelChunk(reference); break; case "resolved_module": initializeModuleChunk(reference); } switch (reference.status) { case "fulfilled": id = reference.value; continue; } break; } return map(response, id, parentObject, key); case "pending": case "blocked": return waitForReference(id, parentObject, key, response, map, reference); case "halted": return initializingHandler ? (response = initializingHandler, response.deps++) : initializingHandler = { parent: null, chunk: null, value: null, reason: null, deps: 1, errored: false }, null; default: return initializingHandler ? (initializingHandler.errored = true, initializingHandler.value = null, initializingHandler.reason = id.reason) : initializingHandler = { parent: null, chunk: null, value: null, reason: id.reason, deps: 0, errored: true }, null; } } function createMap(response, model) { return new Map(model); } function createSet(response, model) { return new Set(model); } function createBlob(response, model) { return new Blob(model.slice(1), { type: model[0] }); } function createFormData(response, model) { response = new FormData(); for (var i = 0; i < model.length; i++) response.append(model[i][0], model[i][1]); return response; } function extractIterator(response, model) { return model[Symbol.iterator](); } function createModel(response, model) { return model; } function parseModelString(response, parentObject, key, value) { if ("$" === value[0]) { if ("$" === value) return null !== initializingHandler && "0" === key && (initializingHandler = { parent: initializingHandler, chunk: null, value: null, reason: null, deps: 0, errored: false }), REACT_ELEMENT_TYPE; switch (value[1]) { case "$": return value.slice(1); case "L": return parentObject = parseInt(value.slice(2), 16), response = getChunk(response, parentObject), createLazyChunkWrapper(response); case "@": return parentObject = parseInt(value.slice(2), 16), getChunk(response, parentObject); case "S": return Symbol.for(value.slice(2)); case "h": return value = value.slice(2), getOutlinedModel(response, value, parentObject, key, loadServerReference); case "T": parentObject = "$" + value.slice(2); response = response._tempRefs; if (null == response) throw Error("Missing a temporary reference set but the RSC response returned a temporary reference. Pass a temporaryReference option with the set that was used with the reply."); return response.get(parentObject); case "Q": return value = value.slice(2), getOutlinedModel(response, value, parentObject, key, createMap); case "W": return value = value.slice(2), getOutlinedModel(response, value, parentObject, key, createSet); case "B": return value = value.slice(2), getOutlinedModel(response, value, parentObject, key, createBlob); case "K": return value = value.slice(2), getOutlinedModel(response, value, parentObject, key, createFormData); case "Z": return resolveErrorProd(); case "i": return value = value.slice(2), getOutlinedModel(response, value, parentObject, key, extractIterator); case "I": return Infinity; case "-": return "$-0" === value ? -0 : -Infinity; case "N": return NaN; case "u": return; case "D": return new Date(Date.parse(value.slice(2))); case "n": return BigInt(value.slice(2)); default: return value = value.slice(1), getOutlinedModel(response, value, parentObject, key, createModel); } } return value; } function missingCall() { throw Error('Trying to call a function from "use server" but the callServer option was not implemented in your router runtime.'); } function ResponseInstance(bundlerConfig, serverReferenceConfig, moduleLoading, callServer, encodeFormAction, nonce, temporaryReferences) { var chunks = /* @__PURE__ */ new Map(); this._bundlerConfig = bundlerConfig; this._serverReferenceConfig = serverReferenceConfig; this._moduleLoading = moduleLoading; this._callServer = void 0 !== callServer ? callServer : missingCall; this._encodeFormAction = encodeFormAction; this._nonce = nonce; this._chunks = chunks; this._stringDecoder = new TextDecoder(); this._fromJSON = null; this._closed = false; this._closedReason = null; this._tempRefs = temporaryReferences; this._fromJSON = createFromJSONCallback(this); } function resolveBuffer(response, id, buffer) { response = response._chunks; var chunk = response.get(id); chunk && "pending" !== chunk.status ? chunk.reason.enqueueValue(buffer) : (buffer = new ReactPromise("fulfilled", buffer, null), response.set(id, buffer)); } function resolveModule(response, id, model) { var chunks = response._chunks, chunk = chunks.get(id); model = JSON.parse(model, response._fromJSON); var clientReference = resolveClientReference(response._bundlerConfig, model); prepareDestinationWithChunks(response._moduleLoading, model[1], response._nonce); if (model = preloadModule(clientReference)) { if (chunk) { var blockedChunk = chunk; blockedChunk.status = "blocked"; } else blockedChunk = new ReactPromise("blocked", null, null), chunks.set(id, blockedChunk); model.then(function() { return resolveModuleChunk(response, blockedChunk, clientReference); }, function(error) { return triggerErrorOnChunk(response, blockedChunk, error); }); } else chunk ? resolveModuleChunk(response, chunk, clientReference) : (chunk = new ReactPromise("resolved_module", clientReference, null), chunks.set(id, chunk)); } function resolveStream(response, id, stream, controller) { response = response._chunks; var chunk = response.get(id); chunk ? "pending" === chunk.status && (id = chunk.value, chunk.status = "fulfilled", chunk.value = stream, chunk.reason = controller, null !== id && wakeChunk(id, chunk.value)) : (stream = new ReactPromise("fulfilled", stream, controller), response.set(id, stream)); } function startReadableStream(response, id, type) { var controller = null, closed = false; type = new ReadableStream({ type, start: function(c) { controller = c; } }); var previousBlockedChunk = null; resolveStream(response, id, type, { enqueueValue: function(value) { null === previousBlockedChunk ? controller.enqueue(value) : previousBlockedChunk.then(function() { controller.enqueue(value); }); }, enqueueModel: function(json) { if (null === previousBlockedChunk) { var chunk = new ReactPromise("resolved_model", json, response); initializeModelChunk(chunk); "fulfilled" === chunk.status ? controller.enqueue(chunk.value) : (chunk.then(function(v) { return controller.enqueue(v); }, function(e) { return controller.error(e); }), previousBlockedChunk = chunk); } else { chunk = previousBlockedChunk; var chunk$55 = new ReactPromise("pending", null, null); chunk$55.then(function(v) { return controller.enqueue(v); }, function(e) { return controller.error(e); }); previousBlockedChunk = chunk$55; chunk.then(function() { previousBlockedChunk === chunk$55 && (previousBlockedChunk = null); resolveModelChunk(response, chunk$55, json); }); } }, close: function() { if (!closed) if (closed = true, null === previousBlockedChunk) controller.close(); else { var blockedChunk = previousBlockedChunk; previousBlockedChunk = null; blockedChunk.then(function() { return controller.close(); }); } }, error: function(error) { if (!closed) if (closed = true, null === previousBlockedChunk) controller.error(error); else { var blockedChunk = previousBlockedChunk; previousBlockedChunk = null; blockedChunk.then(function() { return controller.error(error); }); } } }); } function asyncIterator() { return this; } function createIterator(next) { next = { next }; next[ASYNC_ITERATOR] = asyncIterator; return next; } function startAsyncIterable(response, id, iterator) { var buffer = [], closed = false, nextWriteIndex = 0, iterable = {}; iterable[ASYNC_ITERATOR] = function() { var nextReadIndex = 0; return createIterator(function(arg) { if (void 0 !== arg) throw Error("Values cannot be passed to next() of AsyncIterables passed to Client Components."); if (nextReadIndex === buffer.length) { if (closed) return new ReactPromise("fulfilled", { done: true, value: void 0 }, null); buffer[nextReadIndex] = new ReactPromise("pending", null, null); } return buffer[nextReadIndex++]; }); }; resolveStream(response, id, iterator ? iterable[ASYNC_ITERATOR]() : iterable, { enqueueValue: function(value) { if (nextWriteIndex === buffer.length) buffer[nextWriteIndex] = new ReactPromise("fulfilled", { done: false, value }, null); else { var chunk = buffer[nextWriteIndex], resolveListeners = chunk.value, rejectListeners = chunk.reason; chunk.status = "fulfilled"; chunk.value = { done: false, value }; chunk.reason = null; null !== resolveListeners && wakeChunkIfInitialized(chunk, resolveListeners, rejectListeners); } nextWriteIndex++; }, enqueueModel: function(value) { nextWriteIndex === buffer.length ? buffer[nextWriteIndex] = createResolvedIteratorResultChunk(response, value, false) : resolveIteratorResultChunk(response, buffer[nextWriteIndex], value, false); nextWriteIndex++; }, close: function(value) { if (!closed) for (closed = true, nextWriteIndex === buffer.length ? buffer[nextWriteIndex] = createResolvedIteratorResultChunk(response, value, true) : resolveIteratorResultChunk(response, buffer[nextWriteIndex], value, true), nextWriteIndex++; nextWriteIndex < buffer.length; ) resolveIteratorResultChunk(response, buffer[nextWriteIndex++], '"$undefined"', true); }, error: function(error) { if (!closed) for (closed = true, nextWriteIndex === buffer.length && (buffer[nextWriteIndex] = new ReactPromise("pending", null, null)); nextWriteIndex < buffer.length; ) triggerErrorOnChunk(response, buffer[nextWriteIndex++], error); } }); } function resolveErrorProd() { var error = Error("An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error."); error.stack = "Error: " + error.message; return error; } function mergeBuffer(buffer, lastChunk) { for (var l = buffer.length, byteLength = lastChunk.length, i = 0; i < l; i++) byteLength += buffer[i].byteLength; byteLength = new Uint8Array(byteLength); for (var i$56 = i = 0; i$56 < l; i$56++) { var chunk = buffer[i$56]; byteLength.set(chunk, i); i += chunk.byteLength; } byteLength.set(lastChunk, i); return byteLength; } function resolveTypedArray(response, id, buffer, lastChunk, constructor, bytesPerElement) { buffer = 0 === buffer.length && 0 === lastChunk.byteOffset % bytesPerElement ? lastChunk : mergeBuffer(buffer, lastChunk); constructor = new constructor(buffer.buffer, buffer.byteOffset, buffer.byteLength / bytesPerElement); resolveBuffer(response, id, constructor); } function processFullBinaryRow(response, streamState, id, tag, buffer, chunk) { switch (tag) { case 65: resolveBuffer(response, id, mergeBuffer(buffer, chunk).buffer); return; case 79: resolveTypedArray(response, id, buffer, chunk, Int8Array, 1); return; case 111: resolveBuffer(response, id, 0 === buffer.length ? chunk : mergeBuffer(buffer, chunk)); return; case 85: resolveTypedArray(response, id, buffer, chunk, Uint8ClampedArray, 1); return; case 83: resolveTypedArray(response, id, buffer, chunk, Int16Array, 2); return; case 115: resolveTypedArray(response, id, buffer, chunk, Uint16Array, 2); return; case 76: resolveTypedArray(response, id, buffer, chunk, Int32Array, 4); return; case 108: resolveTypedArray(response, id, buffer, chunk, Uint32Array, 4); return; case 71: resolveTypedArray(response, id, buffer, chunk, Float32Array, 4); return; case 103: resolveTypedArray(response, id, buffer, chunk, Float64Array, 8); return; case 77: resolveTypedArray(response, id, buffer, chunk, BigInt64Array, 8); return; case 109: resolveTypedArray(response, id, buffer, chunk, BigUint64Array, 8); return; case 86: resolveTypedArray(response, id, buffer, chunk, DataView, 1); return; } streamState = response._stringDecoder; for (var row = "", i = 0; i < buffer.length; i++) row += streamState.decode(buffer[i], decoderOptions); buffer = row += streamState.decode(chunk); switch (tag) { case 73: resolveModule(response, id, buffer); break; case 72: id = buffer[0]; buffer = buffer.slice(1); response = JSON.parse(buffer, response._fromJSON); buffer = ReactDOMSharedInternals.d; switch (id) { case "D": buffer.D(response); break; case "C": "string" === typeof response ? buffer.C(response) : buffer.C(response[0], response[1]); break; case "L": id = response[0]; tag = response[1]; 3 === response.length ? buffer.L(id, tag, response[2]) : buffer.L(id, tag); break; case "m": "string" === typeof response ? buffer.m(response) : buffer.m(response[0], response[1]); break; case "X": "string" === typeof response ? buffer.X(response) : buffer.X(response[0], response[1]); break; case "S": "string" === typeof response ? buffer.S(response) : buffer.S(response[0], 0 === response[1] ? void 0 : response[1], 3 === response.length ? response[2] : void 0); break; case "M": "string" === typeof response ? buffer.M(response) : buffer.M(response[0], response[1]); } break; case 69: tag = response._chunks; chunk = tag.get(id); buffer = JSON.parse(buffer); streamState = resolveErrorProd(); streamState.digest = buffer.digest; chunk ? triggerErrorOnChunk(response, chunk, streamState) : (response = new ReactPromise("rejected", null, streamState), tag.set(id, response)); break; case 84: response = response._chunks; (tag = response.get(id)) && "pending" !== tag.status ? tag.reason.enqueueValue(buffer) : (buffer = new ReactPromise("fulfilled", buffer, null), response.set(id, buffer)); break; case 78: case 68: case 74: case 87: throw Error("Failed to read a RSC payload created by a development version of React on the server while using a production version on the client. Always use matching versions on the server and the client."); case 82: startReadableStream(response, id, void 0); break; case 114: startReadableStream(response, id, "bytes"); break; case 88: startAsyncIterable(response, id, false); break; case 120: startAsyncIterable(response, id, true); break; case 67: (id = response._chunks.get(id)) && "fulfilled" === id.status && id.reason.close("" === buffer ? '"$undefined"' : buffer); break; default: tag = response._chunks, (chunk = tag.get(id)) ? resolveModelChunk(response, chunk, buffer) : (response = new ReactPromise("resolved_model", buffer, response), tag.set(id, response)); } } function createFromJSONCallback(response) { return function(key, value) { if ("__proto__" !== key) { if ("string" === typeof value) return parseModelString(response, this, key, value); if ("object" === typeof value && null !== value) { if (value[0] === REACT_ELEMENT_TYPE) { if (key = { $$typeof: REACT_ELEMENT_TYPE, type: value[1], key: value[2], ref: null, props: value[3] }, null !== initializingHandler) { if (value = initializingHandler, initializingHandler = value.parent, value.errored) key = new ReactPromise("rejected", null, value.reason), key = createLazyChunkWrapper(key); else if (0 < value.deps) { var blockedChunk = new ReactPromise("blocked", null, null); value.value = key; value.chunk = blockedChunk; key = createLazyChunkWrapper(blockedChunk); } } } else key = value; return key; } return value; } }; } function close(weakResponse) { reportGlobalError(weakResponse, Error("Connection closed.")); } function noServerCall() { throw Error("Server Functions cannot be called during initial render. This would create a fetch waterfall. Try to use a Server Component to pass data to Client Components instead."); } function createResponseFromOptions(options) { return new ResponseInstance(options.serverConsumerManifest.moduleMap, options.serverConsumerManifest.serverModuleMap, options.serverConsumerManifest.moduleLoading, noServerCall, options.encodeFormAction, "string" === typeof options.nonce ? options.nonce : void 0, options && options.temporaryReferences ? options.temporaryReferences : void 0); } function startReadingFromStream(response, stream, onDone) { function progress(_ref) { var value = _ref.value; if (_ref.done) return onDone(); var i = 0, rowState = streamState._rowState; _ref = streamState._rowID; for (var rowTag = streamState._rowTag, rowLength = streamState._rowLength, buffer = streamState._buffer, chunkLength = value.length; i < chunkLength; ) { var lastIdx = -1; switch (rowState) { case 0: lastIdx = value[i++]; 58 === lastIdx ? rowState = 1 : _ref = _ref << 4 | (96 < lastIdx ? lastIdx - 87 : lastIdx - 48); continue; case 1: rowState = value[i]; 84 === rowState || 65 === rowState || 79 === rowState || 111 === rowState || 85 === rowState || 83 === rowState || 115 === rowState || 76 === rowState || 108 === rowState || 71 === rowState || 103 === rowState || 77 === rowState || 109 === rowState || 86 === rowState ? (rowTag = rowState, rowState = 2, i++) : 64 < rowState && 91 > rowState || 35 === rowState || 114 === rowState || 120 === rowState ? (rowTag = rowState, rowState = 3, i++) : (rowTag = 0, rowState = 3); continue; case 2: lastIdx = value[i++]; 44 === lastIdx ? rowState = 4 : rowLength = rowLength << 4 | (96 < lastIdx ? lastIdx - 87 : lastIdx - 48); continue; case 3: lastIdx = value.indexOf(10, i); break; case 4: lastIdx = i + rowLength, lastIdx > value.length && (lastIdx = -1); } var offset = value.byteOffset + i; if (-1 < lastIdx) rowLength = new Uint8Array(value.buffer, offset, lastIdx - i), processFullBinaryRow(response, streamState, _ref, rowTag, buffer, rowLength), i = lastIdx, 3 === rowState && i++, rowLength = _ref = rowTag = rowState = 0, buffer.length = 0; else { value = new Uint8Array(value.buffer, offset, value.byteLength - i); buffer.push(value); rowLength -= value.byteLength; break; } } streamState._rowState = rowState; streamState._rowID = _ref; streamState._rowTag = rowTag; streamState._rowLength = rowLength; return reader.read().then(progress).catch(error); } function error(e) { reportGlobalError(response, e); } var streamState = { _rowState: 0, _rowID: 0, _rowTag: 0, _rowLength: 0, _buffer: [] }, reader = stream.getReader(); reader.read().then(progress).catch(error); } reactServerDomWebpackClient_edge_production.createFromFetch = function(promiseForResponse, options) { var response = createResponseFromOptions(options); promiseForResponse.then(function(r) { startReadingFromStream(response, r.body, close.bind(null, response)); }, function(e) { reportGlobalError(response, e); }); return getChunk(response, 0); }; reactServerDomWebpackClient_edge_production.createFromReadableStream = function(stream, options) { options = createResponseFromOptions(options); startReadingFromStream(options, stream, close.bind(null, options)); return getChunk(options, 0); }; reactServerDomWebpackClient_edge_production.createServerReference = function(id) { return createServerReference$1(id, noServerCall); }; reactServerDomWebpackClient_edge_production.createTemporaryReferenceSet = function() { return /* @__PURE__ */ new Map(); }; reactServerDomWebpackClient_edge_production.encodeReply = function(value, options) { return new Promise(function(resolve, reject) { var abort = processReply(value, "", options && options.temporaryReferences ? options.temporaryReferences : void 0, resolve, reject); if (options && options.signal) { var signal = options.signal; if (signal.aborted) abort(signal.reason); else { var listener = function() { abort(signal.reason); signal.removeEventListener("abort", listener); }; signal.addEventListener("abort", listener); } } }); }; reactServerDomWebpackClient_edge_production.registerServerReference = function(reference, id, encodeFormAction) { registerBoundServerReference(reference, id, null, encodeFormAction); return reference; }; return reactServerDomWebpackClient_edge_production; } var hasRequiredClient_edge; function requireClient_edge() { if (hasRequiredClient_edge) return client_edge.exports; hasRequiredClient_edge = 1; { client_edge.exports = requireReactServerDomWebpackClient_edge_production(); } return client_edge.exports; } var client_edgeExports = requireClient_edge(); function renderToReadableStream$1(data, options, extraOptions) { return server_edgeExports.renderToReadableStream(data, createClientManifest({ onClientReference: extraOptions == null ? void 0 : extraOptions.onClientReference }), options); } function createFromReadableStream(stream, options = {}) { return client_edgeExports.createFromReadableStream(stream, { serverConsumerManifest: { serverModuleMap: createServerManifest(), moduleMap: createServerDecodeClientManifest() }, ...options }); } registerClientReference = function(proxy, id, name) { return server_edgeExports.registerClientReference(proxy, id, name); }; function decodeReply(body, options) { return server_edgeExports.decodeReply(body, createServerManifest(), options); } function decodeAction(body) { return server_edgeExports.decodeAction(body, createServerManifest()); } function decodeFormState(actionResult, body) { return server_edgeExports.decodeFormState(actionResult, body, createServerManifest()); } const createTemporaryReferenceSet = server_edgeExports.createTemporaryReferenceSet; const ErrorBoundary = registerClientReference((() => { throw new Error('It is not possible to invoke a client function from the server: "ErrorBoundary"'); }), "6d786e16fc6b", "ErrorBoundary"); const INTERNAL_ServerRouter = registerClientReference((() => { throw new Error('It is not possible to invoke a client function from the server: "INTERNAL_ServerRouter"'); }), "6d786e16fc6b", "INTERNAL_ServerRouter"); var jsxRuntime_reactServer = { exports: {} }; var reactJsxRuntime_reactServer_production = {}; var hasRequiredReactJsxRuntime_reactServer_production; function requireReactJsxRuntime_reactServer_production() { if (hasRequiredReactJsxRuntime_reactServer_production) return reactJsxRuntime_reactServer_production; hasRequiredReactJsxRuntime_reactServer_production = 1; var React = requireReact_reactServer(), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"); if (!React.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE) throw Error('The "react" package in this environment is not configured correctly. The "react-server" condition must be enabled in any environment that runs React Server Components.'); function jsxProd(type, config2, maybeKey) { var key = null; void 0 !== maybeKey && (key = "" + maybeKey); void 0 !== config2.key && (key = "" + config2.key); if ("key" in config2) { maybeKey = {}; for (var propName in config2) "key" !== propName && (maybeKey[propName] = config2[propName]); } else maybeKey = config2; config2 = maybeKey.ref; return { $$typeof: REACT_ELEMENT_TYPE, type, key, ref: void 0 !== config2 ? config2 : null, props: maybeKey }; } reactJsxRuntime_reactServer_production.Fragment = REACT_FRAGMENT_TYPE; reactJsxRuntime_reactServer_production.jsx = jsxProd; reactJsxRuntime_reactServer_production.jsxDEV = void 0; reactJsxRuntime_reactServer_production.jsxs = jsxProd; return reactJsxRuntime_reactServer_production; } var hasRequiredJsxRuntime_reactServer; function requireJsxRuntime_reactServer() { if (hasRequiredJsxRuntime_reactServer) return jsxRuntime_reactServer.exports; hasRequiredJsxRuntime_reactServer = 1; { jsxRuntime_reactServer.exports = requireReactJsxRuntime_reactServer_production(); } return jsxRuntime_reactServer.exports; } jsxRuntime_reactServerExports = requireJsxRuntime_reactServer(); const isErrorInfo = (x) => { if (typeof x !== "object" || x === null) { return false; } if ("status" in x && typeof x.status !== "number") { return false; } if ("location" in x && typeof x.location !== "string") { return false; } return true; }; const prefix = "__WAKU_CUSTOM_ERROR__;"; const createCustomError = (message, errorInfo) => { const err = new Error(message); err.digest = prefix + JSON.stringify(errorInfo); return err; }; const getErrorInfo = (err) => { const digest = err == null ? void 0 : err.digest; if (typeof digest !== "string" || !digest.startsWith(prefix)) { return null; } try { const info = JSON.parse(digest.slice(prefix.length)); if (isErrorInfo(info)) { return info; } } catch { } return null; }; joinPath = (...paths) => { var _a2; const isAbsolute = (_a2 = paths[0]) == null ? void 0 : _a2.startsWith("/"); const items = [].concat(...paths.map((path2) => path2.split("/"))); const stack = []; for (const item of items) { if (item === "..") { if (stack.length && stack[stack.length - 1] !== "..") { stack.pop(); } else if (!isAbsolute) { stack.push(".."); } } else if (item && item !== ".") { stack.push(item); } } return (isAbsolute ? "/" : "") + stack.join("/") || "."; }; const parsePathWithSlug = (path2) => path2.split("/").filter(Boolean).map((name) => { let type = "literal"; const isSlug = name.startsWith("[") && name.endsWith("]"); if (isSlug) { type = "group"; name = name.slice(1, -1); } const isWildcard = name.startsWith("..."); if (isWildcard) { type = "wildcard"; name = name.slice(3); } return { type, name }; }); const parseExactPath = (path2) => path2.split("/").filter(Boolean).map((name) => ({ type: "literal", name })); const path2regexp = (path2) => { const parts = path2.map(({ type, name }) => { if (type === "literal") { return name; } else if (type === "group") { return `([^/]+)`; } else { return `(.*)`; } }); return `^/${parts.join("/")}$`; }; const pathSpecAsString = (path2) => { return "/" + path2.map(({ type, name }) => { if (type === "literal") { return name; } else if (type === "group") { return `[${name}]`; } else { return `[...${name}]`; } }).join("/"); }; const getPathMapping = (pathSpec, pathname) => { const actual = pathname.split("/").filter(Boolean); if (pathSpec.length > actual.length) { const hasWildcard = pathSpec.some((spec) => spec.type === "wildcard"); if (!hasWildcard || actual.length > 0) { return null; } } const mapping = {}; let wildcardStartIndex = -1; for (let i = 0; i < pathSpec.length; i++) { const { type, name } = pathSpec[i]; if (type === "literal") { if (name !== actual[i]) { return null; } } else if (type === "wildcard") { wildcardStartIndex = i; break; } else if (name) { mapping[name] = actual[i]; } } if (wildcardStartIndex === -1) { if (pathSpec.length !== actual.length) { return null; } return mapping; } if (wildcardStartIndex === 0 && actual.length === 0) { const wildcardName2 = pathSpec[wildcardStartIndex].name; if (wildcardName2) { mapping[wildcardName2] = []; } return mapping; } let wildcardEndIndex = -1; for (let i = 0; i < pathSpec.length; i++) { const { type, name } = pathSpec[pathSpec.length - i - 1]; if (type === "literal") { if (name !== actual[actual.length - i - 1]) { return null; } } else if (type === "wildcard") { wildcardEndIndex = actual.length - i - 1; break; } else if (name) { mapping[name] = actual[actual.length - i - 1]; } } if (wildcardStartIndex === -1 || wildcardEndIndex === -1) { throw new Error("Invalid wildcard path"); } const wildcardName = pathSpec[wildcardStartIndex].name; if (wildcardName) { mapping[wildcardName] = actual.slice(wildcardStartIndex, wildcardEndIndex + 1); } return mapping; }; function removeBase(url, base) { if (base !== "/") { if (!url.startsWith(base)) { throw new Error("pathname must start with basePath: " + url); } return url.slice(base.length - 1); } return url; } const encoder = new TextEncoder(); new TextDecoder(); const stringToStream = (str) => { return new ReadableStream({ start(controller) { controller.enqueue(encoder.encode(str)); controller.close(); } }); }; const streamToBase64 = async (stream) => { const reader = stream.getReader(); let binary = ""; while (true) { const { value, done } = await reader.read(); if (done) { break; } if (!(value instanceof Uint8Array)) { throw new Error("Unexpected buffer type"); } for (let i = 0; i < value.length; i++) { binary += String.fromCharCode(value[i]); } } return btoa(binary); }; const base64ToStream = (base64) => { const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)); return new Blob([ bytes ]).stream(); }; const createTaskRunner = (limit) => { let running = 0; const waiting = []; const scheduleTask = async (task) => { var _a2; while (running >= limit) { await new Promise((resolve) => waiting.push(resolve)); } running++; try { await task(); } finally { running--; (_a2 = waiting.shift()) == null ? void 0 : _a2(); } }; const tasks = []; const runTask = (task) => { tasks.push(scheduleTask(task)); }; const waitForTasks = async () => { await Promise.all(tasks); }; return { runTask, waitForTasks }; }; function unstable_defineHandlers(handlers) { return handlers; } const contextStorage = new AsyncLocalStorage$1(); function INTERNAL_runWithContext(req, next) { const context = { req, nonce: void 0, data: {} }; return contextStorage.run(context, next); } function getContext() { const context = contextStorage.getStore(); if (!context) { throw new Error("Context is not available. Make sure to use the context middleware."); } return context; } INTERNAL_setAllEnv = function(newEnv) { globalThis.__WAKU_SERVER_ENV__ = newEnv; }; const ROUTE_PREFIX = "R"; const SLICE_PREFIX = "S/"; function encodeRoutePath(path2) { if (!path2.startsWith("/")) { throw new Error("Path must start with `/`: " + path2); } if (path2.length > 1 && path2.endsWith("/")) { throw new Error("Path must not end with `/`: " + path2); } if (path2 === "/") { return ROUTE_PREFIX + "/_root"; } if (path2.startsWith("/_")) { return ROUTE_PREFIX + "/__" + path2.slice(2); } return ROUTE_PREFIX + path2; } function decodeRoutePath(rscPath) { if (!rscPath.startsWith(ROUTE_PREFIX)) { throw new Error("rscPath should start with: " + ROUTE_PREFIX); } if (rscPath === ROUTE_PREFIX + "/_root") { return "/"; } if (rscPath.startsWith(ROUTE_PREFIX + "/__")) { return "/_" + rscPath.slice(ROUTE_PREFIX.length + 3); } return rscPath.slice(ROUTE_PREFIX.length); } function encodeSliceId(sliceId) { if (sliceId.startsWith("/")) { throw new Error("Slice id must not start with `/`: " + sliceId); } return SLICE_PREFIX + sliceId; } function decodeSliceId(rscPath) { if (!rscPath.startsWith(SLICE_PREFIX)) { return null; } return rscPath.slice(SLICE_PREFIX.length); } const ROUTE_ID = "ROUTE"; const IS_STATIC_ID = "IS_STATIC"; const HAS404_ID = "HAS404"; const SKIP_HEADER = "X-Waku-Router-Skip"; const isStringArray = (x) => Array.isArray(x) && x.every((y) => typeof y === "string"); const parseRscParams = (rscParams) => { if (rscParams instanceof URLSearchParams) { return { query: rscParams.get("query") || "" }; } if (typeof (rscParams == null ? void 0 : rscParams.query) === "string") { return { query: rscParams.query }; } return { query: "" }; }; const RSC_PATH_SYMBOL = /* @__PURE__ */ Symbol("RSC_PATH"); const RSC_PARAMS_SYMBOL = /* @__PURE__ */ Symbol("RSC_PARAMS"); const setRscPath = (rscPath) => { try { const context = getContext(); context[RSC_PATH_SYMBOL] = rscPath; } catch { } }; const setRscParams = (rscParams) => { try { const context = getContext(); context[RSC_PARAMS_SYMBOL] = rscParams; } catch { } }; const getNonce = () => { try { const context = getContext(); return context.nonce; } catch { return void 0; } }; const RERENDER_SYMBOL = /* @__PURE__ */ Symbol("RERENDER"); const setRerender = (rerender) => { try { const context = getContext(); context[RERENDER_SYMBOL] = rerender; } catch { } }; const is404 = (pathSpec) => pathSpec.length === 1 && pathSpec[0].type === "literal" && pathSpec[0].name === "404"; const pathSpec2pathname = (pathSpec) => { if (pathSpec.some(({ type }) => type !== "literal")) { return void 0; } return "/" + pathSpec.map(({ name }) => name).join("/"); }; const htmlPath2pathname = (htmlPath) => htmlPath === "/404" ? "404.html" : htmlPath + "/index.html"; function unstable_notFound() { throw createCustomError("Not Found", { status: 404 }); } const ROOT_SLOT_ID = "root"; const ROUTE_SLOT_ID_PREFIX = "route:"; const SLICE_SLOT_ID_PREFIX = "slice:"; const assertNonReservedSlotId = (slotId) => { if (slotId === ROOT_SLOT_ID || slotId.startsWith(ROUTE_SLOT_ID_PREFIX) || slotId.startsWith(SLICE_SLOT_ID_PREFIX)) { throw new Error('Element ID cannot be "root", "route:*" or "slice:*"'); } }; const getRouterPrefetchCode = (path2moduleIds) => { const moduleIdSet = /* @__PURE__ */ new Set(); Object.values(path2moduleIds).forEach((ids2) => ids2.forEach((id) => moduleIdSet.add(id))); const ids = Array.from(moduleIdSet); const path2idxs = {}; Object.entries(path2moduleIds).forEach(([path2, ids2]) => { path2idxs[path2] = ids2.map((id) => ids2.indexOf(id)); }); return ` globalThis.__WAKU_ROUTER_PREFETCH__ = (path, callback) => { const ids = ${JSON.stringify(ids)}; const path2idxs = ${JSON.stringify(path2idxs)}; const key = Object.keys(path2idxs).find((key) => new RegExp(key).test(path)); for (const idx of path2idxs[key] || []) { callback(ids[idx]); } }; `; }; function unstable_defineRouter(fns) { let cachedMyConfig; const getMyConfig = async () => { if (!cachedMyConfig) { const configs = Array.from(await fns.getConfigs()); let has404 = false; configs.forEach((item) => { if (item.type === "route") { Object.keys(item.elements).forEach(assertNonReservedSlotId); if (!has404 && is404(item.path)) { has404 = true; } } }); cachedMyConfig = { configs, has404 }; } return cachedMyConfig; }; const getPathConfigItem = async (pathname) => { const myConfig = await getMyConfig(); const found = myConfig.configs.find((item) => (item.type === "route" || item.type === "api") && !!getPathMapping(item.path, pathname)); return found; }; const getSliceElement = async (sliceConfig, getCachedElement, setCachedElement) => { const id = SLICE_SLOT_ID_PREFIX + sliceConfig.id; const cached = getCachedElement(id); if (cached) { return cached; } let element = await sliceConfig.renderer(); if (sliceConfig.isStatic) { element = await setCachedElement(id, element); } return element; }; const getEntriesForRoute = async (rscPath, rscParams, headers, getCachedElement, setCachedElement) => { setRscPath(rscPath); setRscParams(rscParams); const pathname = decodeRoutePath(rscPath); const pathConfigItem = await getPathConfigItem(pathname); if ((pathConfigItem == null ? void 0 : pathConfigItem.type) !== "route") { return null; } let skipParam; try { skipParam = JSON.parse(headers[SKIP_HEADER.toLowerCase()] || ""); } catch { } const skipIdSet = new Set(isStringArray(skipParam) ? skipParam : []); const { query } = parseRscParams(rscParams); const routeId = ROUTE_SLOT_ID_PREFIX + pathname; const option = { pathname, query: pathConfigItem.isStatic ? void 0 : query }; const myConfig = await getMyConfig(); const slices = pathConfigItem.slices || []; const sliceConfigMap = /* @__PURE__ */ new Map(); slices.forEach((sliceId) => { const sliceConfig = myConfig.configs.find((item) => item.type === "slice" && item.id === sliceId); if (sliceConfig) { sliceConfigMap.set(sliceId, sliceConfig); } }); const entries = {}; await Promise.all([ (async () => { if (!pathConfigItem.rootElement.isStatic) { entries[ROOT_SLOT_ID] = pathConfigItem.rootElement.renderer(option); } else if (!skipIdSet.has(ROOT_SLOT_ID)) { const cached = getCachedElement(ROOT_SLOT_ID); entries[ROOT_SLOT_ID] = cached ? await cached : await setCachedElement(ROOT_SLOT_ID, pathConfigItem.rootElement.renderer(option)); } })(), (async () => { if (!pathConfigItem.routeElement.isStatic) { entries[routeId] = pathConfigItem.routeElement.renderer(option); } else if (!skipIdSet.has(routeId)) { const cached = getCachedElement(routeId); entries[routeId] = cached ? await cached : await setCachedElement(routeId, pathConfigItem.routeElement.renderer(option)); } })(), ...Object.entries(pathConfigItem.elements).map(async ([id, { isStatic }]) => { var _a2; const renderer = (_a2 = pathConfigItem.elements[id]) == null ? void 0 : _a2.renderer; if (!isStatic) { entries[id] = renderer == null ? void 0 : renderer(option); } else if (!skipIdSet.has(id)) { const cached = getCachedElement(id); entries[id] = cached ? await cached : await setCachedElement(id, renderer == null ? void 0 : renderer(option)); } }), ...slices.map(async (sliceId) => { const id = SLICE_SLOT_ID_PREFIX + sliceId; const sliceConfig = sliceConfigMap.get(sliceId); if (!sliceConfig) { throw new Error(`Slice not found: ${sliceId}`); } if (sliceConfig.isStatic && skipIdSet.has(id)) { return null; } const sliceElement = await getSliceElement(sliceConfig, getCachedElement, setCachedElement); entries[id] = sliceElement; }) ]); entries[ROUTE_ID] = [ pathname, query ]; entries[IS_STATIC_ID] = pathConfigItem.isStatic; sliceConfigMap.forEach((sliceConfig, sliceId) => { if (sliceConfig.isStatic) { entries[IS_STATIC_ID + ":" + SLICE_SLOT_ID_PREFIX + sliceId] = true; } }); if (myConfig.has404) { entries[HAS404_ID] = true; } return entries; }; const cachedElementsForRequest = /* @__PURE__ */ new Map(); let cachedElementsForRequestInitialized = false; let cachedPath2moduleIds; const handleRequest = async (input, { renderRsc, parseRsc, renderHtml, loadBuildMetadata }) => { const getCachedElement = (id) => cachedElementsForRequest.get(id); const setCachedElement = (id, element) => { const cached = cachedElementsForRequest.get(id); if (cached) { return cached; } const copied = renderRsc({ [id]: element }).then((rscStream) => parseRsc(rscStream).then((parsed) => parsed[id])); cachedElementsForRequest.set(id, copied); return copied; }; if (!cachedElementsForRequestInitialized) { cachedElementsForRequestInitialized = true; const cachedElementsMetadata = await loadBuildMetadata("defineRouter:cachedElements"); if (cachedElementsMetadata) { Object.entries(JSON.parse(cachedElementsMetadata)).forEach(([id, str]) => { cachedElementsForRequest.set(id, parseRsc(base64ToStream(str)).then((parsed) => parsed[id])); }); } } const getPath2moduleIds = async () => { if (!cachedPath2moduleIds) { cachedPath2moduleIds = JSON.parse(await loadBuildMetadata("defineRouter:path2moduleIds") || "{}"); } return cachedPath2moduleIds; }; const pathConfigItem = await getPathConfigItem(input.pathname); if ((pathConfigItem == null ? void 0 : pathConfigItem.type) === "api") { const url2 = new URL(input.req.url); url2.pathname = input.pathname; const req = new Request(url2, input.req); const params = getPathMapping(pathConfigItem.path, input.pathname) ?? {}; return pathConfigItem.handler(req, { params }); } const url = new URL(input.req.url); const headers = Object.fromEntries(input.req.headers.entries()); if (input.type === "component") { const sliceId = decodeSliceId(input.rscPath); if (sliceId !== null) { const sliceConfig = await getMyConfig().then((myConfig) => myConfig.configs.find((item) => item.type === "slice" && item.id === sliceId)); if (!sliceConfig) { return null; } const sliceElement = await getSliceElement(sliceConfig, getCachedElement, setCachedElement); return renderRsc({ [SLICE_SLOT_ID_PREFIX + sliceId]: sliceElement, ...sliceConfig.isStatic ? { [IS_STATIC_ID + ":" + SLICE_SLOT_ID_PREFIX + sliceId]: true } : {} }); } const entries = await getEntriesForRoute(input.rscPath, input.rscParams, headers, getCachedElement, setCachedElement); if (!entries) { return null; } return renderRsc(entries); } if (input.type === "function") { let elementsPromise = Promise.resolve({}); let rendered = false; const rerender = (rscPath, rscParams) => { if (rendered) { throw new Error("already rendered"); } elementsPromise = Promise.all([ elementsPromise, getEntriesForRoute(rscPath, rscParams, headers, getCachedElement, setCachedElement) ]).then(([oldElements, newElements]) => { if (newElements === null) { console.warn("getEntries returned null"); } return { ...oldElements, ...newElements }; }); }; setRerender(rerender); try { const value = await input.fn(...input.args); return renderRsc({ ...await elementsPromise, _value: value }); } catch (e) { const info = getErrorInfo(e); if (info == null ? void 0 : info.location) { const rscPath = encodeRoutePath(info.location); const entries = await getEntriesForRoute(rscPath, void 0, headers, getCachedElement, setCachedElement); if (!entries) { unstable_notFound(); } return renderRsc(entries); } throw e; } finally { rendered = true; } } if (input.type === "action" || input.type === "custom") { const renderIt = async (pathname, query2, httpstatus = 200) => { const rscPath = encodeRoutePath(pathname); const rscParams = new URLSearchParams({ query: query2 }); const entries = await getEntriesForRoute(rscPath, rscParams, headers, getCachedElement, setCachedElement); if (!entries) { return null; } const path2moduleIds = await getPath2moduleIds(); const html = jsxRuntime_reactServerExports.jsx(INTERNAL_ServerRouter, { route: { path: pathname, query: query2, hash: "" }, httpstatus }); const formState = input.type === "action" ? await input.fn() : void 0; const nonce = getNonce(); return renderHtml(await renderRsc(entries), html, { rscPath, formState, status: httpstatus, ...nonce ? { nonce } : {}, unstable_extraScriptContent: getRouterPrefetchCode(path2moduleIds) }); }; const query = url.searchParams.toString(); if ((pathConfigItem == null ? void 0 : pathConfigItem.type) === "route" && pathConfigItem.noSsr) { return "fallback"; } try { if (pathConfigItem) { return await renderIt(input.pathname, query); } } catch (e) { const info = getErrorInfo(e); if ((info == null ? void 0 : info.status) !== 404) { throw e; } } if ((await getMyConfig()).has404) { return renderIt("/404", "", 404); } else { return null; } } }; const handleBuild = async ({ renderRsc, parseRsc, renderHtml, rscPath2pathname, saveBuildMetadata, withRequest, generateFile, generateDefaultHtml }) => { const myConfig = await getMyConfig(); const cachedElementsForBuild = /* @__PURE__ */ new Map(); const serializedCachedElements = /* @__PURE__ */ new Map(); const getCachedElement = (id) => cachedElementsForBuild.get(id); const setCachedElement = async (id, element) => { const cached = cachedElementsForBuild.get(id); if (cached) { return cached; } const teedStream = renderRsc({ [id]: element }).then((rscStream) => rscStream.tee()); const stream1 = teedStream.then(([s1]) => s1); const stream2 = teedStream.then(([, s2]) => s2); const copied = stream1.then((rscStream) => parseRsc(rscStream).then((parsed) => parsed[id])); cachedElementsForBuild.set(id, copied); serializedCachedElements.set(id, await streamToBase64(await stream2)); return copied; }; const { runTask, waitForTasks } = createTaskRunner(500); for (const item of myConfig.configs) { if (item.type !== "api") { continue; } if (!item.isStatic) { continue; } const pathname = pathSpec2pathname(item.path); if (!pathname) { continue; } const req = new Request(new URL(pathname, "http://localhost:3000")); runTask(async () => { await withRequest(req, async () => { const res = await item.handler(req, { params: {} }); await generateFile(pathname, res.body || ""); }); }); } const path2moduleIds = {}; const htmlRenderTasks = /* @__PURE__ */ new Set(); for (const item of myConfig.configs) { if (item.type !== "route") { continue; } if (!item.isStatic) { continue; } const pathname = pathSpec2pathname(item.path); if (!pathname) { continue; } const rscPath = encodeRoutePath(pathname); const req = new Request(new URL(pathname, "http://localhost:3000")); runTask(async () => { await withRequest(req, async () => { const entries = await getEntriesForRoute(rscPath, void 0, {}, getCachedElement, setCachedElement); if (!entries) { return; } for (const id of Object.keys(entries)) { const cached = getCachedElement(id); entries[id] = cached ? await cached : entries[id]; } const moduleIds = /* @__PURE__ */ new Set(); const stream = await renderRsc(entries, { unstable_clientModuleCallback: (ids) => ids.forEach((id) => moduleIds.add(id)) }); const [stream1, stream2] = stream.tee(); await generateFile(rscPath2pathname(rscPath), stream1); path2moduleIds[path2regexp(item.pathPattern || item.path)] = Array.from(moduleIds); htmlRenderTasks.add(async () => { const html = jsxRuntime_reactServerExports.jsx(INTERNAL_ServerRouter, { route: { path: pathname, query: "", hash: "" }, httpstatus: is404(item.path) ? 404 : 200 }); const res = await renderHtml(stream2, html, { rscPath, unstable_extraScriptContent: getRouterPrefetchCode(path2moduleIds) }); await generateFile(htmlPath2pathname(pathname), res.body || ""); }); }); }); } await waitForTasks(); htmlRenderTasks.forEach(runTask); for (const item of myConfig.configs) { if (item.type !== "route") { continue; } if (item.noSsr) { const pathname = pathSpec2pathname(item.path); if (!pathname) { throw new Error("Pathname is required for noSsr routes on build"); } runTask(async () => { await generateDefaultHtml(htmlPath2pathname(pathname)); }); } } for (const item of myConfig.configs) { if (item.type !== "slice") { continue; } if (!item.isStatic) { continue; } const rscPath = encodeSliceId(item.id); const req = new Request(new URL("http://localhost:3000")); runTask(async () => { await withRequest(req, async () => { const sliceElement = await getSliceElement(item, getCachedElement, setCachedElement); const body = await renderRsc({ [SLICE_SLOT_ID_PREFIX + item.id]: sliceElement, [IS_STATIC_ID + ":" + SLICE_SLOT_ID_PREFIX + item.id]: true }); await generateFile(rscPath2pathname(rscPath), body); }); }); } await waitForTasks(); await saveBuildMetadata("defineRouter:cachedElements", JSON.stringify(Object.fromEntries(serializedCachedElements))); await saveBuildMetadata("defineRouter:path2moduleIds", JSON.stringify(path2moduleIds)); }; return Object.assign(unstable_defineHandlers({ handleRequest, handleBuild }), { unstable_getRouterConfigs: () => getMyConfig().then((c) => c.configs) }); } var react_reactServerExports = requireReact_reactServer(); __vite_rsc_react__ = getDefaultExportFromCjs(react_reactServerExports); const getGrouplessPath = (path2) => { if (path2.includes("(")) { const withoutGroups = path2.split("/").filter((part) => !part.startsWith("(")); path2 = withoutGroups.length > 1 ? withoutGroups.join("/") : "/"; } return path2; }; const Children = registerClientReference((() => { throw new Error('It is not possible to invoke a client function from the server: "Children"'); }), "847a2b1045ef", "Children"); const Slot = registerClientReference((() => { throw new Error('It is not possible to invoke a client function from the server: "Slot"'); }), "847a2b1045ef", "Slot"); const METHODS$1 = [ "GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH" ]; const pathMappingWithoutGroups = (pathSpec, pathname) => { const cleanPathSpec = pathSpec.filter((spec) => !(spec.type === "literal" && spec.name.startsWith("("))); return getPathMapping(cleanPathSpec, pathname); }; const sanitizeSlug = (slug) => slug.replace(/ /g, "-"); const DefaultRoot = ({ children }) => jsxRuntime_reactServerExports.jsx(ErrorBoundary, { children: jsxRuntime_reactServerExports.jsxs("html", { children: [ jsxRuntime_reactServerExports.jsx("head", {}), jsxRuntime_reactServerExports.jsx("body", { children }) ] }) }); const createNestedElements = (elements, children) => elements.reduceRight((result, element) => react_reactServerExports.createElement(element.component, element.props, result), children); const routePriorityComparator = (a, b) => { var _a2, _b2, _c2, _d2; const aPath = a.path; const bPath = b.path; const aPathLength = aPath.length; const bPathLength = bPath.length; const aHasWildcard = ((_a2 = aPath.at(-1)) == null ? void 0 : _a2.type) === "wildcard"; const bHasWildcard = ((_b2 = bPath.at(-1)) == null ? void 0 : _b2.type) === "wildcard"; if (aPathLength === 0 && bHasWildcard) { return -1; } if (bPathLength === 0 && aHasWildcard) { return 1; } if (aPathLength !== bPathLength) { return aPathLength > bPathLength ? -1 : 1; } const minLength = Math.min(aPathLength, bPathLength); for (let i = 0; i < minLength; i++) { const aIsLiteral = ((_c2 = aPath[i]) == null ? void 0 : _c2.type) === "literal"; const bIsLiteral = ((_d2 = bPath[i]) == null ? void 0 : _d2.type) === "literal"; if (aIsLiteral !== bIsLiteral) { return aIsLiteral ? -1 : 1; } } if (aHasWildcard !== bHasWildcard) { return aHasWildcard ? 1 : -1; } return 0; }; const createPages = (fn) => { let configured = false; const groupPathLookup = /* @__PURE__ */ new Map(); const staticPathMap = /* @__PURE__ */ new Map(); const dynamicPagePathMap = /* @__PURE__ */ new Map(); const wildcardPagePathMap = /* @__PURE__ */ new Map(); const dynamicLayoutPathMap = /* @__PURE__ */ new Map(); const apiPathMap = /* @__PURE__ */ new Map(); const staticComponentMap = /* @__PURE__ */ new Map(); const getStaticLayout = (id) => staticComponentMap.get(joinPath(id, "layout").slice(1)); const getDynamicLayout = (segment) => { var _a2; return (_a2 = dynamicLayoutPathMap.get(segment)) == null ? void 0 : _a2[1]; }; const slicePathMap = /* @__PURE__ */ new Map(); const sliceIdMap = /* @__PURE__ */ new Map(); let rootItem = void 0; const noSsrSet = /* @__PURE__ */ new WeakSet(); const pagePathExists = (path2) => { for (const pathKey of apiPathMap.keys()) { const [_m, p] = pathKey.split(" "); if (p === path2) { return true; } } return staticPathMap.has(path2) || dynamicPagePathMap.has(path2) || wildcardPagePathMap.has(path2); }; const createPathPropsMapper = (path2) => { const layoutMatchPath = groupPathLookup.get(path2) ?? path2; const pathSpec = parsePathWithSlug(layoutMatchPath); return (pathname) => pathMappingWithoutGroups(pathSpec, pathname); }; const buildRouteElement = (layoutPaths, path2, pageComponent) => { const layouts = layoutPaths.map((lPath) => ({ component: Slot, props: { id: `layout:${lPath}` } })); const finalPageChildren = Array.isArray(pageComponent) ? jsxRuntime_reactServerExports.jsx(jsxRuntime_reactServerExports.Fragment, { children: pageComponent.map((_comp, order) => jsxRuntime_reactServerExports.jsx(Slot, { id: `page:${path2}:${order}` }, `page:${path2}:${order}`)) }) : jsxRuntime_reactServerExports.jsx(Slot, { id: `page:${path2}` }); return () => createNestedElements(layouts, finalPageChildren); }; const renderRoot = () => react_reactServerExports.createElement(rootItem ? rootItem.component : DefaultRoot, null, jsxRuntime_reactServerExports.jsx(Children, {})); const registerStaticComponent = (id, component) => { if (staticComponentMap.has(id) && staticComponentMap.get(id) !== component) { throw new Error(`Duplicated component for: ${id}`); } staticComponentMap.set(id, component); }; const isAllElementsStatic = (elements) => Object.values(elements).every((element) => element.isStatic); const isAllSlicesStatic = (path2) => (slicePathMap.get(path2) || []).every((sliceId) => { var _a2; return (_a2 = sliceIdMap.get(sliceId)) == null ? void 0 : _a2.isStatic; }); const createPage = (page) => { var _a2; if (configured) { throw new Error("createPage no longer available"); } if (pagePathExists(page.path)) { throw new Error(`Duplicated path: ${page.path}`); } const pathSpec = parsePathWithSlug(page.path); const { numSlugs, numWildcards } = getSlugsAndWildcards(pathSpec); if (page.unstable_disableSSR) { noSsrSet.add(pathSpec); } if (page.exactPath) { const spec = parseExactPath(page.path); if (page.render === "static") { staticPathMap.set(page.path, { literalSpec: spec }); const id = joinPath(page.path, "page").replace(/^\//, ""); if (page.component) { registerStaticComponent(id, page.component); } } else if (page.component) { dynamicPagePathMap.set(page.path, [ spec, page.component ]); } else { dynamicPagePathMap.set(page.path, [ spec, [] ]); } } else if (page.render === "static" && numSlugs === 0) { const pagePath = getGrouplessPath(page.path); staticPathMap.set(pagePath, { literalSpec: pathSpec }); const id = joinPath(pagePath, "page").replace(/^\//, ""); if (pagePath !== page.path) { groupPathLookup.set(pagePath, page.path); } if (page.component) { registerStaticComponent(id, page.component); } } else if (page.render === "static" && numSlugs > 0 && "staticPaths" in page) { const staticPaths = page.staticPaths.map((item) => (Array.isArray(item) ? item : [ item ]).map(sanitizeSlug)); for (const staticPath of staticPaths) { if (staticPath.length !== numSlugs && numWildcards === 0) { throw new Error("staticPaths does not match with slug pattern"); } const { definedPath, pathItems, mapping } = expandStaticPathSpec(pathSpec, staticPath); const pagePath = getGrouplessPath(definedPath); staticPathMap.set(pagePath, { literalSpec: pathItems.map((name) => ({ type: "literal", name })), originalSpec: pathSpec }); if (pagePath !== definedPath) { groupPathLookup.set(pagePath, definedPath); } const id = joinPath(pagePath, "page").replace(/^\//, ""); const WrappedComponent = (props) => react_reactServerExports.createElement(page.component, { ...props, ...mapping }); registerStaticComponent(id, WrappedComponent); } } else if (page.render === "dynamic" && numWildcards === 0) { const pagePath = getGrouplessPath(page.path); if (pagePath !== page.path) { groupPathLookup.set(pagePath, page.path); } dynamicPagePathMap.set(pagePath, [ pathSpec, page.component ]); } else if (page.render === "dynamic" && numWildcards === 1) { const pagePath = getGrouplessPath(page.path); if (pagePath !== page.path) { groupPathLookup.set(pagePath, page.path); } wildcardPagePathMap.set(pagePath, [ pathSpec, page.component ]); } else { throw new Error("Invalid page configuration " + JSON.stringify(page)); } if ((_a2 = page.slices) == null ? void 0 : _a2.length) { slicePathMap.set(page.path, page.slices); } return page; }; const createLayout = (layout) => { if (configured) { throw new Error("createLayout no longer available"); } if (layout.render === "static") { const id = joinPath(layout.path, "layout").replace(/^\//, ""); registerStaticComponent(id, layout.component); } else if (layout.render === "dynamic") { if (dynamicLayoutPathMap.has(layout.path)) { throw new Error(`Duplicated dynamic path: ${layout.path}`); } const pathSpec = parsePathWithSlug(layout.path); dynamicLayoutPathMap.set(layout.path, [ pathSpec, layout.component ]); } else { throw new Error("Invalid layout configuration"); } }; const createApi = (options) => { if (configured) { throw new Error("createApi no longer available"); } if (apiPathMap.has(options.path)) { throw new Error(`Duplicated api path: ${options.path}`); } const pathSpec = parsePathWithSlug(options.path); if (options.render === "static") { const { numSlugs, numWildcards } = getSlugsAndWildcards(pathSpec); if (numSlugs > 0 && options.staticPaths) { const staticPaths = options.staticPaths.map((item) => (Array.isArray(item) ? item : [ item ]).map(sanitizeSlug)); for (const staticPath of staticPaths) { if (staticPath.length !== numSlugs && numWildcards === 0) { throw new Error("staticPaths does not match with slug pattern"); } const { definedPath, pathItems } = expandStaticPathSpec(pathSpec, staticPath); if (apiPathMap.has(definedPath)) { throw new Error(`Duplicated api path: ${definedPath}`); } apiPathMap.set(definedPath, { render: "static", pathSpec: pathItems.map((name) => ({ type: "literal", name })), handlers: { GET: options.handler } }); } } else { apiPathMap.set(options.path, { render: "static", pathSpec, handlers: { GET: options.handler } }); } } else { apiPathMap.set(options.path, { render: "dynamic", pathSpec, handlers: options.handlers }); } }; const createRoot = (root) => { if (configured) { throw new Error("createRoot no longer available"); } if (rootItem) { throw new Error(`Duplicated root component`); } if (root.render === "static" || root.render === "dynamic") { rootItem = root; } else { throw new Error("Invalid root configuration"); } }; const createSlice = (slice) => { if (configured) { throw new Error("createSlice no longer available"); } if (sliceIdMap.has(slice.id)) { throw new Error(`Duplicated slice id: ${slice.id}`); } sliceIdMap.set(slice.id, { component: slice.component, isStatic: slice.render === "static" }); }; let ready; const configure = async () => { if (!configured && !ready) { ready = fn({ createPage, createLayout, createRoot, createApi, createSlice }); await ready; configured = true; } await ready; }; const getLayouts = (spec) => { const pathSegments = spec.reduce((acc, _segment, index) => { acc.push(pathSpecAsString(spec.slice(0, index + 1))); return acc; }, [ "/" ]); return pathSegments.filter((segment) => dynamicLayoutPathMap.has(segment) || getStaticLayout(segment)); }; const definedRouter = unstable_defineRouter({ getConfigs: async () => { await configure(); const routeConfigs = []; const rootIsStatic = !rootItem || rootItem.render === "static"; for (const [path2, { literalSpec, originalSpec }] of staticPathMap) { const noSsr = noSsrSet.has(literalSpec); const layoutPaths = getLayouts(originalSpec ?? literalSpec); const pageComponent = staticComponentMap.get(joinPath(path2, "page").slice(1)); const getPropsMapping = createPathPropsMapper(path2); const elements = {}; for (const lPath of layoutPaths) { const layout = getDynamicLayout(lPath) ?? getStaticLayout(lPath); if (!layout || Array.isArray(layout)) { throw new Error("Invalid layout " + lPath); } elements[`layout:${lPath}`] = { isStatic: !dynamicLayoutPathMap.has(lPath), renderer: () => react_reactServerExports.createElement(layout, null, jsxRuntime_reactServerExports.jsx(Children, {})) }; } elements[`page:${path2}`] = { isStatic: true, renderer: (option) => react_reactServerExports.createElement(pageComponent, { ...getPropsMapping(option.pathname), ...option.query ? { query: option.query } : {}, path: option.pathname }, jsxRuntime_reactServerExports.jsx(Children, {})) }; routeConfigs.push({ type: "route", path: literalSpec.filter((part) => { var _a2; return !((_a2 = part.name) == null ? void 0 : _a2.startsWith("(")); }), isStatic: rootIsStatic && isAllElementsStatic(elements) && isAllSlicesStatic(path2), ...originalSpec && { pathPattern: originalSpec }, rootElement: { isStatic: rootIsStatic, renderer: renderRoot }, routeElement: { isStatic: true, renderer: buildRouteElement(layoutPaths, path2, pageComponent) }, elements, noSsr, slices: slicePathMap.get(path2) || [] }); } for (const [path2, [pathSpec, components]] of dynamicPagePathMap) { const noSsr = noSsrSet.has(pathSpec); const layoutPaths = getLayouts(pathSpec); const getPropsMapping = createPathPropsMapper(path2); const elements = {}; for (const lPath of layoutPaths) { const layout = getDynamicLayout(lPath) ?? getStaticLayout(lPath); if (!layout || Array.isArray(layout)) { throw new Error("Invalid layout " + lPath); } elements[`layout:${lPath}`] = { isStatic: !dynamicLayoutPathMap.has(lPath), renderer: () => react_reactServerExports.createElement(layout, null, jsxRuntime_reactServerExports.jsx(Children, {})) }; } if (Array.isArray(components)) { for (let i = 0; i < components.length; i++) { const comp = components[i]; if (comp) { elements[`page:${path2}:${i}`] = { isStatic: comp.render === "static", renderer: (option) => react_reactServerExports.createElement(comp.component, { ...getPropsMapping(option.pathname), ...option.query ? { query: option.query } : {}, path: option.pathname }) }; } } } else { elements[`page:${path2}`] = { isStatic: false, renderer: (option) => react_reactServerExports.createElement(components, { ...getPropsMapping(option.pathname), ...option.query ? { query: option.query } : {}, path: option.pathname }, jsxRuntime_reactServerExports.jsx(Children, {})) }; } routeConfigs.push({ type: "route", isStatic: rootIsStatic && isAllElementsStatic(elements) && isAllSlicesStatic(path2), path: pathSpec.filter((part) => { var _a2; return !((_a2 = part.name) == null ? void 0 : _a2.startsWith("(")); }), rootElement: { isStatic: rootIsStatic, renderer: renderRoot }, routeElement: { isStatic: true, renderer: buildRouteElement(layoutPaths, path2, components) }, elements, noSsr, slices: slicePathMap.get(path2) || [] }); } for (const [path2, [pathSpec, components]] of wildcardPagePathMap) { const noSsr = noSsrSet.has(pathSpec); const layoutPaths = getLayouts(pathSpec); const getPropsMapping = createPathPropsMapper(path2); const elements = {}; for (const lPath of layoutPaths) { const layout = getDynamicLayout(lPath) ?? getStaticLayout(lPath); if (!layout || Array.isArray(layout)) { throw new Error("Invalid layout " + lPath); } elements[`layout:${lPath}`] = { isStatic: !dynamicLayoutPathMap.has(lPath), renderer: () => react_reactServerExports.createElement(layout, null, jsxRuntime_reactServerExports.jsx(Children, {})) }; } if (Array.isArray(components)) { for (let i = 0; i < components.length; i++) { const comp = components[i]; if (comp) { elements[`page:${path2}:${i}`] = { isStatic: comp.render === "static", renderer: (option) => react_reactServerExports.createElement(comp.component, { ...getPropsMapping(option.pathname), ...option.query ? { query: option.query } : {}, path: option.pathname }) }; } } } else { elements[`page:${path2}`] = { isStatic: false, renderer: (option) => react_reactServerExports.createElement(components, { ...getPropsMapping(option.pathname), ...option.query ? { query: option.query } : {}, path: option.pathname }, jsxRuntime_reactServerExports.jsx(Children, {})) }; } routeConfigs.push({ type: "route", isStatic: rootIsStatic && isAllElementsStatic(elements) && isAllSlicesStatic(path2), path: pathSpec.filter((part) => { var _a2; return !((_a2 = part.name) == null ? void 0 : _a2.startsWith("(")); }), rootElement: { isStatic: rootIsStatic, renderer: renderRoot }, routeElement: { isStatic: true, renderer: buildRouteElement(layoutPaths, path2, components) }, elements, noSsr, slices: slicePathMap.get(path2) || [] }); } const apiConfigs = Array.from(apiPathMap.values()).map(({ pathSpec, render, handlers }) => { return { type: "api", path: pathSpec, isStatic: render === "static", handler: async (req, apiContext) => { const path2 = new URL(req.url).pathname; const method = req.method; const handler = handlers[method] ?? handlers.all; if (!handler) { throw new Error("API method not found: " + method + "for path: " + path2); } return handler(req, apiContext); } }; }); const sliceConfigs = Array.from(sliceIdMap).map(([id, { isStatic }]) => ({ type: "slice", id, isStatic, renderer: async () => { const slice = sliceIdMap.get(id); if (!slice) { throw new Error("Slice not found: " + id); } return jsxRuntime_reactServerExports.jsx(slice.component, {}); } })); const pathConfigs = [ ...routeConfigs, ...apiConfigs ].sort((configA, configB) => routePriorityComparator(configA, configB)); return [ ...pathConfigs, ...sliceConfigs ]; } }); return definedRouter; }; const getSlugsAndWildcards = (pathSpec) => { let numSlugs = 0; let numWildcards = 0; for (const slug of pathSpec) { if (slug.type !== "literal") { numSlugs++; } if (slug.type === "wildcard") { numWildcards++; } } return { numSlugs, numWildcards }; }; function expandStaticPathSpec(pathSpec, staticPath) { const mapping = {}; let slugIndex = 0; const pathItems = []; pathSpec.forEach(({ type, name }) => { switch (type) { case "literal": pathItems.push(name); break; case "wildcard": mapping[name] = staticPath.slice(slugIndex); staticPath.slice(slugIndex++).forEach((slug) => { pathItems.push(slug); }); break; case "group": pathItems.push(staticPath[slugIndex++]); mapping[name] = pathItems[pathItems.length - 1]; break; } }); const definedPath = "/" + pathItems.join("/"); return { definedPath, pathItems, mapping }; } const IGNORED_PATH_PARTS = /* @__PURE__ */ new Set([ "_components", "_hooks" ]); const isIgnoredPath = (paths) => paths.some((p) => IGNORED_PATH_PARTS.has(p)); let didWarnAboutApiDirMigration = false; function fsRouter(pages, options = { apiDir: "_api", slicesDir: "_slices" }) { if (!didWarnAboutApiDirMigration && !options.temporary_doNotWarnAboutApiDirMigration) { didWarnAboutApiDirMigration = true; if (Object.keys(pages).some((file) => file.startsWith("./api/"))) { console.warn('[fsRouter] Migration required (v1.0.0-alpha.1): Move "./api/" to "./_api/". To preserve the old "/api/*" URL paths, move to "./_api/api/". See https://github.com/wakujs/waku/pull/1885'); } } return createPages(async ({ createPage, createLayout, createRoot, createApi, createSlice }) => { var _a2, _b2; for (let file in pages) { const mod = await pages[file](); file = new URL(file, "http://localhost:3000").pathname.slice(1); const config2 = await ((_a2 = mod.getConfig) == null ? void 0 : _a2.call(mod)); const pathItems = file.replace(/\.\w+$/, "").split("/").filter(Boolean); if (isIgnoredPath(pathItems)) { continue; } const path2 = "/" + ([ "_layout", "index", "_root" ].includes(pathItems.at(-1)) || ((_b2 = pathItems.at(-1)) == null ? void 0 : _b2.startsWith("_part")) ? pathItems.slice(0, -1) : pathItems).join("/"); if (pathItems.at(-1) === "[path]") { throw new Error("Page file cannot be named [path]. This will conflict with the path prop of the page component."); } else if (pathItems.at(0) === options.apiDir) { const apiPath = pathItems.slice(1).join("/"); if ((config2 == null ? void 0 : config2.render) === "static") { if (Object.keys(mod).length !== 2 || !mod.GET) { console.warn(`API ${path2} is invalid. For static API routes, only a single GET handler is supported.`); } createApi({ ...config2, path: apiPath, render: "static", method: "GET", handler: mod.GET }); } else { const validMethods = new Set(METHODS$1); const handlers = Object.fromEntries(Object.entries(mod).flatMap(([exportName, handler]) => { const isValidExport = exportName === "getConfig" || exportName === "default" || validMethods.has(exportName); if (!isValidExport) { console.warn(`API ${path2} has an invalid export: ${exportName}. Valid exports are: ${METHODS$1.join(", ")}`); } return isValidExport && exportName !== "getConfig" ? exportName === "default" ? [ [ "all", handler ] ] : [ [ exportName, handler ] ] : []; })); createApi({ path: apiPath, render: "dynamic", handlers }); } } else if (pathItems.at(0) === options.slicesDir) { createSlice({ component: mod.default, render: "static", id: pathItems.slice(1).join("/"), ...config2 }); } else if (pathItems.at(-1) === "_layout") { createLayout({ path: path2, component: mod.default, render: "static", ...config2 }); } else if (pathItems.at(-1) === "_root") { createRoot({ component: mod.default, render: "static", ...config2 }); } else { createPage({ path: path2, component: mod.default, render: "static", ...config2 }); } } return null; }); } var RequestError = class extends Error { constructor(message, options) { super(message, options); this.name = "RequestError"; } }; var toRequestError = (e) => { if (e instanceof RequestError) { return e; } return new RequestError(e.message, { cause: e }); }; var GlobalRequest = global.Request; var Request$1 = class Request extends GlobalRequest { constructor(input, options) { var _a2; if (typeof input === "object" && getRequestCache in input) { input = input[getRequestCache](); } if (typeof ((_a2 = options == null ? void 0 : options.body) == null ? void 0 : _a2.getReader) !== "undefined") { options.duplex ?? (options.duplex = "half"); } super(input, options); } }; var newHeadersFromIncoming = (incoming) => { const headerRecord = []; const rawHeaders = incoming.rawHeaders; for (let i = 0; i < rawHeaders.length; i += 2) { const { [i]: key, [i + 1]: value } = rawHeaders; if (key.charCodeAt(0) !== 58) { headerRecord.push([ key, value ]); } } return new Headers(headerRecord); }; var wrapBodyStream = /* @__PURE__ */ Symbol("wrapBodyStream"); var newRequestFromIncoming = (method, url, headers, incoming, abortController) => { const init2 = { method, headers, signal: abortController.signal }; if (method === "TRACE") { init2.method = "GET"; const req = new Request$1(url, init2); Object.defineProperty(req, "method", { get() { return "TRACE"; } }); return req; } if (!(method === "GET" || method === "HEAD")) { if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) { init2.body = new ReadableStream({ start(controller) { controller.enqueue(incoming.rawBody); controller.close(); } }); } else if (incoming[wrapBodyStream]) { let reader; init2.body = new ReadableStream({ async pull(controller) { try { reader || (reader = Readable.toWeb(incoming).getReader()); const { done, value } = await reader.read(); if (done) { controller.close(); } else { controller.enqueue(value); } } catch (error) { controller.error(error); } } }); } else { init2.body = Readable.toWeb(incoming); } } return new Request$1(url, init2); }; var getRequestCache = /* @__PURE__ */ Symbol("getRequestCache"); var requestCache = /* @__PURE__ */ Symbol("requestCache"); var incomingKey = /* @__PURE__ */ Symbol("incomingKey"); var urlKey = /* @__PURE__ */ Symbol("urlKey"); var headersKey = /* @__PURE__ */ Symbol("headersKey"); var abortControllerKey = /* @__PURE__ */ Symbol("abortControllerKey"); var getAbortController = /* @__PURE__ */ Symbol("getAbortController"); var requestPrototype = { get method() { return this[incomingKey].method || "GET"; }, get url() { return this[urlKey]; }, get headers() { return this[headersKey] || (this[headersKey] = newHeadersFromIncoming(this[incomingKey])); }, [getAbortController]() { this[getRequestCache](); return this[abortControllerKey]; }, [getRequestCache]() { this[abortControllerKey] || (this[abortControllerKey] = new AbortController()); return this[requestCache] || (this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], this[abortControllerKey])); } }; [ "body", "bodyUsed", "cache", "credentials", "destination", "integrity", "mode", "redirect", "referrer", "referrerPolicy", "signal", "keepalive" ].forEach((k) => { Object.defineProperty(requestPrototype, k, { get() { return this[getRequestCache]()[k]; } }); }); [ "arrayBuffer", "blob", "clone", "formData", "json", "text" ].forEach((k) => { Object.defineProperty(requestPrototype, k, { value: function() { return this[getRequestCache]()[k](); } }); }); Object.setPrototypeOf(requestPrototype, Request$1.prototype); var newRequest = (incoming, defaultHostname) => { const req = Object.create(requestPrototype); req[incomingKey] = incoming; const incomingUrl = incoming.url || ""; if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) { if (incoming instanceof Http2ServerRequest) { throw new RequestError("Absolute URL for :path is not allowed in HTTP/2"); } try { const url2 = new URL(incomingUrl); req[urlKey] = url2.href; } catch (e) { throw new RequestError("Invalid absolute URL", { cause: e }); } return req; } const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname; if (!host) { throw new RequestError("Missing host header"); } let scheme; if (incoming instanceof Http2ServerRequest) { scheme = incoming.scheme; if (!(scheme === "http" || scheme === "https")) { throw new RequestError("Unsupported scheme"); } } else { scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http"; } const url = new URL(`${scheme}://${host}${incomingUrl}`); if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) { throw new RequestError("Invalid host header"); } req[urlKey] = url.href; return req; }; var responseCache = /* @__PURE__ */ Symbol("responseCache"); var getResponseCache = /* @__PURE__ */ Symbol("getResponseCache"); var cacheKey = /* @__PURE__ */ Symbol("cache"); var GlobalResponse = global.Response; var Response2 = (_a = class { constructor(body, init2) { __privateAdd(this, _body); __privateAdd(this, _init); let headers; __privateSet(this, _body, body); if (init2 instanceof _a) { const cachedGlobalResponse = init2[responseCache]; if (cachedGlobalResponse) { __privateSet(this, _init, cachedGlobalResponse); this[getResponseCache](); return; } else { __privateSet(this, _init, __privateGet(init2, _init)); headers = new Headers(__privateGet(init2, _init).headers); } } else { __privateSet(this, _init, init2); } if (typeof body === "string" || typeof (body == null ? void 0 : body.getReader) !== "undefined" || body instanceof Blob || body instanceof Uint8Array) { this[cacheKey] = [ (init2 == null ? void 0 : init2.status) || 200, body, headers || (init2 == null ? void 0 : init2.headers) ]; } } [getResponseCache]() { delete this[cacheKey]; return this[responseCache] || (this[responseCache] = new GlobalResponse(__privateGet(this, _body), __privateGet(this, _init))); } get headers() { const cache = this[cacheKey]; if (cache) { if (!(cache[2] instanceof Headers)) { cache[2] = new Headers(cache[2] || { "content-type": "text/plain; charset=UTF-8" }); } return cache[2]; } return this[getResponseCache]().headers; } get status() { var _a2; return ((_a2 = this[cacheKey]) == null ? void 0 : _a2[0]) ?? this[getResponseCache]().status; } get ok() { const status = this.status; return status >= 200 && status < 300; } }, _body = new WeakMap(), _init = new WeakMap(), _a); [ "body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url" ].forEach((k) => { Object.defineProperty(Response2.prototype, k, { get() { return this[getResponseCache]()[k]; } }); }); [ "arrayBuffer", "blob", "clone", "formData", "json", "text" ].forEach((k) => { Object.defineProperty(Response2.prototype, k, { value: function() { return this[getResponseCache]()[k](); } }); }); Object.setPrototypeOf(Response2, GlobalResponse); Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype); async function readWithoutBlocking(readPromise) { return Promise.race([ readPromise, Promise.resolve().then(() => Promise.resolve(void 0)) ]); } function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) { const cancel = (error) => { reader.cancel(error).catch(() => { }); }; writable.on("close", cancel); writable.on("error", cancel); (currentReadPromise ?? reader.read()).then(flow, handleStreamError); return reader.closed.finally(() => { writable.off("close", cancel); writable.off("error", cancel); }); function handleStreamError(error) { if (error) { writable.destroy(error); } } function onDrain() { reader.read().then(flow, handleStreamError); } function flow({ done, value }) { try { if (done) { writable.end(); } else if (!writable.write(value)) { writable.once("drain", onDrain); } else { return reader.read().then(flow, handleStreamError); } } catch (e) { handleStreamError(e); } } } function writeFromReadableStream(stream, writable) { if (stream.locked) { throw new TypeError("ReadableStream is locked."); } else if (writable.destroyed) { return; } return writeFromReadableStreamDefaultReader(stream.getReader(), writable); } var buildOutgoingHttpHeaders = (headers) => { const res = {}; if (!(headers instanceof Headers)) { headers = new Headers(headers ?? void 0); } const cookies = []; for (const [k, v] of headers) { if (k === "set-cookie") { cookies.push(v); } else { res[k] = v; } } if (cookies.length > 0) { res["set-cookie"] = cookies; } res["content-type"] ?? (res["content-type"] = "text/plain; charset=UTF-8"); return res; }; var X_ALREADY_SENT = "x-hono-already-sent"; if (typeof global.crypto === "undefined") { global.crypto = crypto; } var outgoingEnded = /* @__PURE__ */ Symbol("outgoingEnded"); var handleRequestError = () => new Response(null, { status: 400 }); var handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 }); var handleResponseError = (e, outgoing) => { const err = e instanceof Error ? e : new Error("unknown error", { cause: e }); if (err.code === "ERR_STREAM_PREMATURE_CLOSE") { console.info("The user aborted a request."); } else { console.error(e); if (!outgoing.headersSent) { outgoing.writeHead(500, { "Content-Type": "text/plain" }); } outgoing.end(`Error: ${err.message}`); outgoing.destroy(err); } }; var flushHeaders = (outgoing) => { if ("flushHeaders" in outgoing && outgoing.writable) { outgoing.flushHeaders(); } }; var responseViaCache = async (res, outgoing) => { var _a2, _b2; let [status, body, header] = res[cacheKey]; let hasContentLength = false; if (!header) { header = { "content-type": "text/plain; charset=UTF-8" }; } else if (header instanceof Headers) { hasContentLength = header.has("content-length"); header = buildOutgoingHttpHeaders(header); } else if (Array.isArray(header)) { const headerObj = new Headers(header); hasContentLength = headerObj.has("content-length"); header = buildOutgoingHttpHeaders(headerObj); } else { for (const key in header) { if (key.length === 14 && key.toLowerCase() === "content-length") { hasContentLength = true; break; } } } if (!hasContentLength) { if (typeof body === "string") { header["Content-Length"] = Buffer.byteLength(body); } else if (body instanceof Uint8Array) { header["Content-Length"] = body.byteLength; } else if (body instanceof Blob) { header["Content-Length"] = body.size; } } outgoing.writeHead(status, header); if (typeof body === "string" || body instanceof Uint8Array) { outgoing.end(body); } else if (body instanceof Blob) { outgoing.end(new Uint8Array(await body.arrayBuffer())); } else { flushHeaders(outgoing); await ((_a2 = writeFromReadableStream(body, outgoing)) == null ? void 0 : _a2.catch((e) => handleResponseError(e, outgoing))); } (_b2 = outgoing[outgoingEnded]) == null ? void 0 : _b2.call(outgoing); }; var isPromise = (res) => typeof res.then === "function"; var responseViaResponseObject = async (res, outgoing, options = {}) => { var _a2; if (isPromise(res)) { if (options.errorHandler) { try { res = await res; } catch (err) { const errRes = await options.errorHandler(err); if (!errRes) { return; } res = errRes; } } else { res = await res.catch(handleFetchError); } } if (cacheKey in res) { return responseViaCache(res, outgoing); } const resHeaderRecord = buildOutgoingHttpHeaders(res.headers); if (res.body) { const reader = res.body.getReader(); const values = []; let done = false; let currentReadPromise = void 0; if (resHeaderRecord["transfer-encoding"] !== "chunked") { let maxReadCount = 2; for (let i = 0; i < maxReadCount; i++) { currentReadPromise || (currentReadPromise = reader.read()); const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => { console.error(e); done = true; }); if (!chunk) { if (i === 1) { await new Promise((resolve) => setTimeout(resolve)); maxReadCount = 3; continue; } break; } currentReadPromise = void 0; if (chunk.value) { values.push(chunk.value); } if (chunk.done) { done = true; break; } } if (done && !("content-length" in resHeaderRecord)) { resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0); } } outgoing.writeHead(res.status, resHeaderRecord); values.forEach((value) => { outgoing.write(value); }); if (done) { outgoing.end(); } else { if (values.length === 0) { flushHeaders(outgoing); } await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise); } } else if (resHeaderRecord[X_ALREADY_SENT]) ; else { outgoing.writeHead(res.status, resHeaderRecord); outgoing.end(); } (_a2 = outgoing[outgoingEnded]) == null ? void 0 : _a2.call(outgoing); }; var getRequestListener = (fetchCallback, options = {}) => { const autoCleanupIncoming = options.autoCleanupIncoming ?? true; if (options.overrideGlobalObjects !== false && global.Request !== Request$1) { Object.defineProperty(global, "Request", { value: Request$1 }); Object.defineProperty(global, "Response", { value: Response2 }); } return async (incoming, outgoing) => { let res, req; try { req = newRequest(incoming, options.hostname); let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD"; if (!incomingEnded) { ; incoming[wrapBodyStream] = true; incoming.on("end", () => { incomingEnded = true; }); if (incoming instanceof Http2ServerRequest) { ; outgoing[outgoingEnded] = () => { if (!incomingEnded) { setTimeout(() => { if (!incomingEnded) { setTimeout(() => { incoming.destroy(); outgoing.destroy(); }); } }); } }; } } outgoing.on("close", () => { const abortController = req[abortControllerKey]; if (abortController) { if (incoming.errored) { req[abortControllerKey].abort(incoming.errored.toString()); } else if (!outgoing.writableFinished) { req[abortControllerKey].abort("Client connection prematurely closed."); } } if (!incomingEnded) { setTimeout(() => { if (!incomingEnded) { setTimeout(() => { incoming.destroy(); }); } }); } }); res = fetchCallback(req, { incoming, outgoing }); if (cacheKey in res) { return responseViaCache(res, outgoing); } } catch (e) { if (!res) { if (options.errorHandler) { res = await options.errorHandler(req ? e : toRequestError(e)); if (!res) { return; } } else if (!req) { res = handleRequestError(); } else { res = handleFetchError(e); } } else { return handleResponseError(e, outgoing); } } try { return await responseViaResponseObject(res, outgoing, options); } catch (e) { return handleResponseError(e, outgoing); } }; }; var createAdaptorServer = (options) => { const fetchCallback = options.fetch; const requestListener = getRequestListener(fetchCallback, { hostname: options.hostname, overrideGlobalObjects: options.overrideGlobalObjects, autoCleanupIncoming: options.autoCleanupIncoming }); const createServer$1 = options.createServer || createServer; const server = createServer$1(options.serverOptions || {}, requestListener); return server; }; var serve = (options, listeningListener) => { const server = createAdaptorServer(options); server.listen((options == null ? void 0 : options.port) ?? 3e3, options.hostname, () => { const serverInfo = server.address(); listeningListener && listeningListener(serverInfo); }); return server; }; var getMimeType = (filename, mimes = baseMimes) => { const regexp = /\.([a-zA-Z0-9]+?)$/; const match = filename.match(regexp); if (!match) { return; } let mimeType = mimes[match[1]]; if (mimeType && mimeType.startsWith("text")) { mimeType += "; charset=utf-8"; } return mimeType; }; var _baseMimes = { aac: "audio/aac", avi: "video/x-msvideo", avif: "image/avif", av1: "video/av1", bin: "application/octet-stream", bmp: "image/bmp", css: "text/css", csv: "text/csv", eot: "application/vnd.ms-fontobject", epub: "application/epub+zip", gif: "image/gif", gz: "application/gzip", htm: "text/html", html: "text/html", ico: "image/x-icon", ics: "text/calendar", jpeg: "image/jpeg", jpg: "image/jpeg", js: "text/javascript", json: "application/json", jsonld: "application/ld+json", map: "application/json", mid: "audio/x-midi", midi: "audio/x-midi", mjs: "text/javascript", mp3: "audio/mpeg", mp4: "video/mp4", mpeg: "video/mpeg", oga: "audio/ogg", ogv: "video/ogg", ogx: "application/ogg", opus: "audio/opus", otf: "font/otf", pdf: "application/pdf", png: "image/png", rtf: "application/rtf", svg: "image/svg+xml", tif: "image/tiff", tiff: "image/tiff", ts: "video/mp2t", ttf: "font/ttf", txt: "text/plain", wasm: "application/wasm", webm: "video/webm", weba: "audio/webm", webmanifest: "application/manifest+json", webp: "image/webp", woff: "font/woff", woff2: "font/woff2", xhtml: "application/xhtml+xml", xml: "application/xml", zip: "application/zip", "3gp": "video/3gpp", "3g2": "video/3gpp2", gltf: "model/gltf+json", glb: "model/gltf-binary" }; var baseMimes = _baseMimes; var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i; var ENCODINGS = { br: ".br", zstd: ".zst", gzip: ".gz" }; var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS); var pr54206Applied = () => { const [major, minor] = versions.node.split(".").map((component) => parseInt(component)); return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18; }; var useReadableToWeb = pr54206Applied(); var createStreamBody = (stream) => { if (useReadableToWeb) { return Readable.toWeb(stream); } const body = new ReadableStream({ start(controller) { stream.on("data", (chunk) => { controller.enqueue(chunk); }); stream.on("error", (err) => { controller.error(err); }); stream.on("end", () => { controller.close(); }); }, cancel() { stream.destroy(); } }); return body; }; var getStats = (path2) => { let stats; try { stats = statSync(path2); } catch { } return stats; }; var tryDecode$1 = (str, decoder) => { try { return decoder(str); } catch { return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => { try { return decoder(match); } catch { return match; } }); } }; var tryDecodeURI$1 = (str) => tryDecode$1(str, decodeURI); var serveStatic = (options = { root: "" }) => { const root = options.root || ""; const optionPath = options.path; if (root !== "" && !existsSync(root)) { console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`); } return async (c, next) => { var _a2, _b2, _c2, _d2; if (c.finalized) { return next(); } let filename; if (optionPath) { filename = optionPath; } else { try { filename = tryDecodeURI$1(c.req.path); if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) { throw new Error(); } } catch { await ((_a2 = options.onNotFound) == null ? void 0 : _a2.call(options, c.req.path, c)); return next(); } } let path2 = join(root, !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename); let stats = getStats(path2); if (stats && stats.isDirectory()) { const indexFile = options.index ?? "index.html"; path2 = join(path2, indexFile); stats = getStats(path2); } if (!stats) { await ((_b2 = options.onNotFound) == null ? void 0 : _b2.call(options, path2, c)); return next(); } const mimeType = getMimeType(path2); c.header("Content-Type", mimeType || "application/octet-stream"); if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) { const acceptEncodingSet = new Set((_c2 = c.req.header("Accept-Encoding")) == null ? void 0 : _c2.split(",").map((encoding) => encoding.trim())); for (const encoding of ENCODINGS_ORDERED_KEYS) { if (!acceptEncodingSet.has(encoding)) { continue; } const precompressedStats = getStats(path2 + ENCODINGS[encoding]); if (precompressedStats) { c.header("Content-Encoding", encoding); c.header("Vary", "Accept-Encoding", { append: true }); stats = precompressedStats; path2 = path2 + ENCODINGS[encoding]; break; } } } let result; const size = stats.size; const range = c.req.header("range") || ""; if (c.req.method == "HEAD" || c.req.method == "OPTIONS") { c.header("Content-Length", size.toString()); c.status(200); result = c.body(null); } else if (!range) { c.header("Content-Length", size.toString()); result = c.body(createStreamBody(createReadStream(path2)), 200); } else { c.header("Accept-Ranges", "bytes"); c.header("Date", stats.birthtime.toUTCString()); const parts = range.replace(/bytes=/, "").split("-", 2); const start = parseInt(parts[0], 10) || 0; let end = parseInt(parts[1], 10) || size - 1; if (size < end - start + 1) { end = size - 1; } const chunksize = end - start + 1; const stream = createReadStream(path2, { start, end }); c.header("Content-Length", chunksize.toString()); c.header("Content-Range", `bytes ${start}-${end}/${stats.size}`); result = c.body(createStreamBody(stream), 206); } await ((_d2 = options.onFound) == null ? void 0 : _d2.call(options, path2, c)); return result; }; }; var compose = (middleware, onError, onNotFound) => { return (context, next) => { let index = -1; return dispatch(0); async function dispatch(i) { if (i <= index) { throw new Error("next() called multiple times"); } index = i; let res; let isError = false; let handler; if (middleware[i]) { handler = middleware[i][0][0]; context.req.routeIndex = i; } else { handler = i === middleware.length && next || void 0; } if (handler) { try { res = await handler(context, () => dispatch(i + 1)); } catch (err) { if (err instanceof Error && onError) { context.error = err; res = await onError(err, context); isError = true; } else { throw err; } } } else { if (context.finalized === false && onNotFound) { res = await onNotFound(context); } } if (res && (context.finalized === false || isError)) { context.res = res; } return context; } }; }; var GET_MATCH_RESULT = /* @__PURE__ */ Symbol(); var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => { const { all = false, dot = false } = options; const headers = request instanceof HonoRequest ? request.raw.headers : request.headers; const contentType = headers.get("Content-Type"); if ((contentType == null ? void 0 : contentType.startsWith("multipart/form-data")) || (contentType == null ? void 0 : contentType.startsWith("application/x-www-form-urlencoded"))) { return parseFormData(request, { all, dot }); } return {}; }; async function parseFormData(request, options) { const formData = await request.formData(); if (formData) { return convertFormDataToBodyData(formData, options); } return {}; } function convertFormDataToBodyData(formData, options) { const form = /* @__PURE__ */ Object.create(null); formData.forEach((value, key) => { const shouldParseAllValues = options.all || key.endsWith("[]"); if (!shouldParseAllValues) { form[key] = value; } else { handleParsingAllValues(form, key, value); } }); if (options.dot) { Object.entries(form).forEach(([key, value]) => { const shouldParseDotValues = key.includes("."); if (shouldParseDotValues) { handleParsingNestedValues(form, key, value); delete form[key]; } }); } return form; } var handleParsingAllValues = (form, key, value) => { if (form[key] !== void 0) { if (Array.isArray(form[key])) { form[key].push(value); } else { form[key] = [ form[key], value ]; } } else { if (!key.endsWith("[]")) { form[key] = value; } else { form[key] = [ value ]; } } }; var handleParsingNestedValues = (form, key, value) => { let nestedForm = form; const keys = key.split("."); keys.forEach((key2, index) => { if (index === keys.length - 1) { nestedForm[key2] = value; } else { if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) { nestedForm[key2] = /* @__PURE__ */ Object.create(null); } nestedForm = nestedForm[key2]; } }); }; var tryDecode = (str, decoder) => { try { return decoder(str); } catch { return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => { try { return decoder(match); } catch { return match; } }); } }; var tryDecodeURI = (str) => tryDecode(str, decodeURI); var getPath = (request) => { const url = request.url; const start = url.indexOf("/", url.indexOf(":") + 4); let i = start; for (; i < url.length; i++) { const charCode = url.charCodeAt(i); if (charCode === 37) { const queryIndex = url.indexOf("?", i); const hashIndex = url.indexOf("#", i); const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex); const path2 = url.slice(start, end); return tryDecodeURI(path2.includes("%25") ? path2.replace(/%25/g, "%2525") : path2); } else if (charCode === 63 || charCode === 35) { break; } } return url.slice(start, i); }; var getPathNoStrict = (request) => { const result = getPath(request); return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result; }; var mergePath = (base, sub, ...rest) => { if (rest.length) { sub = mergePath(sub, ...rest); } return `${(base == null ? void 0 : base[0]) === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${(base == null ? void 0 : base.at(-1)) === "/" ? "" : "/"}${(sub == null ? void 0 : sub[0]) === "/" ? sub.slice(1) : sub}`}`; }; var _decodeURI = (value) => { if (!/[%+]/.test(value)) { return value; } if (value.indexOf("+") !== -1) { value = value.replace(/\+/g, " "); } return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value; }; var _getQueryParam = (url, key, multiple) => { let encoded; if (!multiple && key && !/[%+]/.test(key)) { let keyIndex2 = url.indexOf("?", 8); if (keyIndex2 === -1) { return void 0; } if (!url.startsWith(key, keyIndex2 + 1)) { keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1); } while (keyIndex2 !== -1) { const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1); if (trailingKeyCode === 61) { const valueIndex = keyIndex2 + key.length + 2; const endIndex = url.indexOf("&", valueIndex); return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex)); } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) { return ""; } keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1); } encoded = /[%+]/.test(url); if (!encoded) { return void 0; } } const results = {}; encoded ?? (encoded = /[%+]/.test(url)); let keyIndex = url.indexOf("?", 8); while (keyIndex !== -1) { const nextKeyIndex = url.indexOf("&", keyIndex + 1); let valueIndex = url.indexOf("=", keyIndex); if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) { valueIndex = -1; } let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex); if (encoded) { name = _decodeURI(name); } keyIndex = nextKeyIndex; if (name === "") { continue; } let value; if (valueIndex === -1) { value = ""; } else { value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex); if (encoded) { value = _decodeURI(value); } } if (multiple) { if (!(results[name] && Array.isArray(results[name]))) { results[name] = []; } results[name].push(value); } else { results[name] ?? (results[name] = value); } } return key ? results[key] : results; }; var getQueryParam = _getQueryParam; var getQueryParams = (url, key) => { return _getQueryParam(url, key, true); }; var decodeURIComponent_ = decodeURIComponent; var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_); var HonoRequest = (_b = class { constructor(request, path2 = "/", matchResult = [ [] ]) { __privateAdd(this, _HonoRequest_instances); __publicField(this, "raw"); __privateAdd(this, _validatedData); __privateAdd(this, _matchResult); __publicField(this, "routeIndex", 0); __publicField(this, "path"); __publicField(this, "bodyCache", {}); __privateAdd(this, _cachedBody, (key) => { const { bodyCache, raw } = this; const cachedBody = bodyCache[key]; if (cachedBody) { return cachedBody; } const anyCachedKey = Object.keys(bodyCache)[0]; if (anyCachedKey) { return bodyCache[anyCachedKey].then((body) => { if (anyCachedKey === "json") { body = JSON.stringify(body); } return new Response(body)[key](); }); } return bodyCache[key] = raw[key](); }); this.raw = request; this.path = path2; __privateSet(this, _matchResult, matchResult); __privateSet(this, _validatedData, {}); } param(key) { return key ? __privateMethod(this, _HonoRequest_instances, getDecodedParam_fn).call(this, key) : __privateMethod(this, _HonoRequest_instances, getAllDecodedParams_fn).call(this); } query(key) { return getQueryParam(this.url, key); } queries(key) { return getQueryParams(this.url, key); } header(name) { if (name) { return this.raw.headers.get(name) ?? void 0; } const headerData = {}; this.raw.headers.forEach((value, key) => { headerData[key] = value; }); return headerData; } async parseBody(options) { var _a2; return (_a2 = this.bodyCache).parsedBody ?? (_a2.parsedBody = await parseBody(this, options)); } json() { return __privateGet(this, _cachedBody).call(this, "text").then((text) => JSON.parse(text)); } text() { return __privateGet(this, _cachedBody).call(this, "text"); } arrayBuffer() { return __privateGet(this, _cachedBody).call(this, "arrayBuffer"); } blob() { return __privateGet(this, _cachedBody).call(this, "blob"); } formData() { return __privateGet(this, _cachedBody).call(this, "formData"); } addValidatedData(target, data) { __privateGet(this, _validatedData)[target] = data; } valid(target) { return __privateGet(this, _validatedData)[target]; } get url() { return this.raw.url; } get method() { return this.raw.method; } get [GET_MATCH_RESULT]() { return __privateGet(this, _matchResult); } get matchedRoutes() { return __privateGet(this, _matchResult)[0].map(([[, route]]) => route); } get routePath() { return __privateGet(this, _matchResult)[0].map(([[, route]]) => route)[this.routeIndex].path; } }, _validatedData = new WeakMap(), _matchResult = new WeakMap(), _HonoRequest_instances = new WeakSet(), getDecodedParam_fn = function(key) { const paramKey = __privateGet(this, _matchResult)[0][this.routeIndex][1][key]; const param = __privateMethod(this, _HonoRequest_instances, getParamValue_fn).call(this, paramKey); return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param; }, getAllDecodedParams_fn = function() { const decoded = {}; const keys = Object.keys(__privateGet(this, _matchResult)[0][this.routeIndex][1]); for (const key of keys) { const value = __privateMethod(this, _HonoRequest_instances, getParamValue_fn).call(this, __privateGet(this, _matchResult)[0][this.routeIndex][1][key]); if (value !== void 0) { decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value; } } return decoded; }, getParamValue_fn = function(paramKey) { return __privateGet(this, _matchResult)[1] ? __privateGet(this, _matchResult)[1][paramKey] : paramKey; }, _cachedBody = new WeakMap(), _b); var HtmlEscapedCallbackPhase = { Stringify: 1 }; var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => { if (typeof str === "object" && !(str instanceof String)) { if (!(str instanceof Promise)) { str = str.toString(); } if (str instanceof Promise) { str = await str; } } const callbacks = str.callbacks; if (!(callbacks == null ? void 0 : callbacks.length)) { return Promise.resolve(str); } if (buffer) { buffer[0] += str; } else { buffer = [ str ]; } const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0])); { return resStr; } }; var TEXT_PLAIN = "text/plain; charset=UTF-8"; var setDefaultContentType = (contentType, headers) => { return { "Content-Type": contentType, ...headers }; }; var createResponseInstance = (body, init2) => new Response(body, init2); var Context = (_c = class { constructor(req, options) { __privateAdd(this, _Context_instances); __privateAdd(this, _rawRequest); __privateAdd(this, _req); __publicField(this, "env", {}); __privateAdd(this, _var); __publicField(this, "finalized", false); __publicField(this, "error"); __privateAdd(this, _status); __privateAdd(this, _executionCtx); __privateAdd(this, _res); __privateAdd(this, _layout); __privateAdd(this, _renderer); __privateAdd(this, _notFoundHandler); __privateAdd(this, _preparedHeaders); __privateAdd(this, _matchResult2); __privateAdd(this, _path); __publicField(this, "render", (...args) => { __privateGet(this, _renderer) ?? __privateSet(this, _renderer, (content) => this.html(content)); return __privateGet(this, _renderer).call(this, ...args); }); __publicField(this, "setLayout", (layout) => __privateSet(this, _layout, layout)); __publicField(this, "getLayout", () => __privateGet(this, _layout)); __publicField(this, "setRenderer", (renderer) => { __privateSet(this, _renderer, renderer); }); __publicField(this, "header", (name, value, options) => { if (this.finalized) { __privateSet(this, _res, createResponseInstance(__privateGet(this, _res).body, __privateGet(this, _res))); } const headers = __privateGet(this, _res) ? __privateGet(this, _res).headers : __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, new Headers()); if (value === void 0) { headers.delete(name); } else if (options == null ? void 0 : options.append) { headers.append(name, value); } else { headers.set(name, value); } }); __publicField(this, "status", (status) => { __privateSet(this, _status, status); }); __publicField(this, "set", (key, value) => { __privateGet(this, _var) ?? __privateSet(this, _var, /* @__PURE__ */ new Map()); __privateGet(this, _var).set(key, value); }); __publicField(this, "get", (key) => { return __privateGet(this, _var) ? __privateGet(this, _var).get(key) : void 0; }); __publicField(this, "newResponse", (...args) => __privateMethod(this, _Context_instances, newResponse_fn).call(this, ...args)); __publicField(this, "body", (data, arg, headers) => __privateMethod(this, _Context_instances, newResponse_fn).call(this, data, arg, headers)); __publicField(this, "text", (text, arg, headers) => { return !__privateGet(this, _preparedHeaders) && !__privateGet(this, _status) && !arg && !headers && !this.finalized ? new Response(text) : __privateMethod(this, _Context_instances, newResponse_fn).call(this, text, arg, setDefaultContentType(TEXT_PLAIN, headers)); }); __publicField(this, "json", (object, arg, headers) => { return __privateMethod(this, _Context_instances, newResponse_fn).call(this, JSON.stringify(object), arg, setDefaultContentType("application/json", headers)); }); __publicField(this, "html", (html, arg, headers) => { const res = (html2) => __privateMethod(this, _Context_instances, newResponse_fn).call(this, html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers)); return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html); }); __publicField(this, "redirect", (location, status) => { const locationString = String(location); this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)); return this.newResponse(null, status ?? 302); }); __publicField(this, "notFound", () => { __privateGet(this, _notFoundHandler) ?? __privateSet(this, _notFoundHandler, () => createResponseInstance()); return __privateGet(this, _notFoundHandler).call(this, this); }); __privateSet(this, _rawRequest, req); if (options) { __privateSet(this, _executionCtx, options.executionCtx); this.env = options.env; __privateSet(this, _notFoundHandler, options.notFoundHandler); __privateSet(this, _path, options.path); __privateSet(this, _matchResult2, options.matchResult); } } get req() { __privateGet(this, _req) ?? __privateSet(this, _req, new HonoRequest(__privateGet(this, _rawRequest), __privateGet(this, _path), __privateGet(this, _matchResult2))); return __privateGet(this, _req); } get event() { if (__privateGet(this, _executionCtx) && "respondWith" in __privateGet(this, _executionCtx)) { return __privateGet(this, _executionCtx); } else { throw Error("This context has no FetchEvent"); } } get executionCtx() { if (__privateGet(this, _executionCtx)) { return __privateGet(this, _executionCtx); } else { throw Error("This context has no ExecutionContext"); } } get res() { return __privateGet(this, _res) || __privateSet(this, _res, createResponseInstance(null, { headers: __privateGet(this, _preparedHeaders) ?? __privateSet(this, _preparedHeaders, new Headers()) })); } set res(_res2) { if (__privateGet(this, _res) && _res2) { _res2 = createResponseInstance(_res2.body, _res2); for (const [k, v] of __privateGet(this, _res).headers.entries()) { if (k === "content-type") { continue; } if (k === "set-cookie") { const cookies = __privateGet(this, _res).headers.getSetCookie(); _res2.headers.delete("set-cookie"); for (const cookie of cookies) { _res2.headers.append("set-cookie", cookie); } } else { _res2.headers.set(k, v); } } } __privateSet(this, _res, _res2); this.finalized = true; } get var() { if (!__privateGet(this, _var)) { return {}; } return Object.fromEntries(__privateGet(this, _var)); } }, _rawRequest = new WeakMap(), _req = new WeakMap(), _var = new WeakMap(), _status = new WeakMap(), _executionCtx = new WeakMap(), _res = new WeakMap(), _layout = new WeakMap(), _renderer = new WeakMap(), _notFoundHandler = new WeakMap(), _preparedHeaders = new WeakMap(), _matchResult2 = new WeakMap(), _path = new WeakMap(), _Context_instances = new WeakSet(), newResponse_fn = function(data, arg, headers) { const responseHeaders = __privateGet(this, _res) ? new Headers(__privateGet(this, _res).headers) : __privateGet(this, _preparedHeaders) ?? new Headers(); if (typeof arg === "object" && "headers" in arg) { const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers); for (const [key, value] of argHeaders) { if (key.toLowerCase() === "set-cookie") { responseHeaders.append(key, value); } else { responseHeaders.set(key, value); } } } if (headers) { for (const [k, v] of Object.entries(headers)) { if (typeof v === "string") { responseHeaders.set(k, v); } else { responseHeaders.delete(k); for (const v2 of v) { responseHeaders.append(k, v2); } } } } const status = typeof arg === "number" ? arg : (arg == null ? void 0 : arg.status) ?? __privateGet(this, _status); return createResponseInstance(data, { status, headers: responseHeaders }); }, _c); var METHOD_NAME_ALL = "ALL"; var METHOD_NAME_ALL_LOWERCASE = "all"; var METHODS = [ "get", "post", "put", "delete", "options", "patch" ]; var UnsupportedPathError = class extends Error { }; var COMPOSED_HANDLER = "__COMPOSED_HANDLER"; var notFoundHandler = (c) => { return c.text("404 Not Found", 404); }; var errorHandler = (err, c) => { if ("getResponse" in err) { const res = err.getResponse(); return c.newResponse(res.body, res); } console.error(err); return c.text("Internal Server Error", 500); }; var Hono$1 = (_d = class { constructor(options = {}) { __privateAdd(this, __Hono_instances); __publicField(this, "get"); __publicField(this, "post"); __publicField(this, "put"); __publicField(this, "delete"); __publicField(this, "options"); __publicField(this, "patch"); __publicField(this, "all"); __publicField(this, "on"); __publicField(this, "use"); __publicField(this, "router"); __publicField(this, "getPath"); __publicField(this, "_basePath", "/"); __privateAdd(this, _path2, "/"); __publicField(this, "routes", []); __privateAdd(this, _notFoundHandler2, notFoundHandler); __publicField(this, "errorHandler", errorHandler); __publicField(this, "onError", (handler) => { this.errorHandler = handler; return this; }); __publicField(this, "notFound", (handler) => { __privateSet(this, _notFoundHandler2, handler); return this; }); __publicField(this, "fetch", (request, ...rest) => { return __privateMethod(this, __Hono_instances, dispatch_fn).call(this, request, rest[1], rest[0], request.method); }); __publicField(this, "request", (input, requestInit, Env, executionCtx) => { if (input instanceof Request) { return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx); } input = input.toString(); return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx); }); __publicField(this, "fire", () => { addEventListener("fetch", (event) => { event.respondWith(__privateMethod(this, __Hono_instances, dispatch_fn).call(this, event.request, event, void 0, event.request.method)); }); }); const allMethods = [ ...METHODS, METHOD_NAME_ALL_LOWERCASE ]; allMethods.forEach((method) => { this[method] = (args1, ...args) => { if (typeof args1 === "string") { __privateSet(this, _path2, args1); } else { __privateMethod(this, __Hono_instances, addRoute_fn).call(this, method, __privateGet(this, _path2), args1); } args.forEach((handler) => { __privateMethod(this, __Hono_instances, addRoute_fn).call(this, method, __privateGet(this, _path2), handler); }); return this; }; }); this.on = (method, path2, ...handlers) => { for (const p of [ path2 ].flat()) { __privateSet(this, _path2, p); for (const m of [ method ].flat()) { handlers.map((handler) => { __privateMethod(this, __Hono_instances, addRoute_fn).call(this, m.toUpperCase(), __privateGet(this, _path2), handler); }); } } return this; }; this.use = (arg1, ...handlers) => { if (typeof arg1 === "string") { __privateSet(this, _path2, arg1); } else { __privateSet(this, _path2, "*"); handlers.unshift(arg1); } handlers.forEach((handler) => { __privateMethod(this, __Hono_instances, addRoute_fn).call(this, METHOD_NAME_ALL, __privateGet(this, _path2), handler); }); return this; }; const { strict, ...optionsWithoutStrict } = options; Object.assign(this, optionsWithoutStrict); this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict; } route(path2, app) { const subApp = this.basePath(path2); app.routes.map((r) => { var _a2; let handler; if (app.errorHandler === errorHandler) { handler = r.handler; } else { handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res; handler[COMPOSED_HANDLER] = r.handler; } __privateMethod(_a2 = subApp, __Hono_instances, addRoute_fn).call(_a2, r.method, r.path, handler); }); return this; } basePath(path2) { const subApp = __privateMethod(this, __Hono_instances, clone_fn).call(this); subApp._basePath = mergePath(this._basePath, path2); return subApp; } mount(path2, applicationHandler, options) { let replaceRequest; let optionHandler; if (options) { if (typeof options === "function") { optionHandler = options; } else { optionHandler = options.optionHandler; if (options.replaceRequest === false) { replaceRequest = (request) => request; } else { replaceRequest = options.replaceRequest; } } } const getOptions = optionHandler ? (c) => { const options2 = optionHandler(c); return Array.isArray(options2) ? options2 : [ options2 ]; } : (c) => { let executionContext = void 0; try { executionContext = c.executionCtx; } catch { } return [ c.env, executionContext ]; }; replaceRequest || (replaceRequest = (() => { const mergedPath = mergePath(this._basePath, path2); const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length; return (request) => { const url = new URL(request.url); url.pathname = url.pathname.slice(pathPrefixLength) || "/"; return new Request(url, request); }; })()); const handler = async (c, next) => { const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c)); if (res) { return res; } await next(); }; __privateMethod(this, __Hono_instances, addRoute_fn).call(this, METHOD_NAME_ALL, mergePath(path2, "*"), handler); return this; } }, _path2 = new WeakMap(), __Hono_instances = new WeakSet(), clone_fn = function() { const clone = new _d({ router: this.router, getPath: this.getPath }); clone.errorHandler = this.errorHandler; __privateSet(clone, _notFoundHandler2, __privateGet(this, _notFoundHandler2)); clone.routes = this.routes; return clone; }, _notFoundHandler2 = new WeakMap(), addRoute_fn = function(method, path2, handler) { method = method.toUpperCase(); path2 = mergePath(this._basePath, path2); const r = { basePath: this._basePath, path: path2, method, handler }; this.router.add(method, path2, [ handler, r ]); this.routes.push(r); }, handleError_fn = function(err, c) { if (err instanceof Error) { return this.errorHandler(err, c); } throw err; }, dispatch_fn = function(request, executionCtx, env, method) { if (method === "HEAD") { return (async () => new Response(null, await __privateMethod(this, __Hono_instances, dispatch_fn).call(this, request, executionCtx, env, "GET")))(); } const path2 = this.getPath(request, { env }); const matchResult = this.router.match(method, path2); const c = new Context(request, { path: path2, matchResult, env, executionCtx, notFoundHandler: __privateGet(this, _notFoundHandler2) }); if (matchResult[0].length === 1) { let res; try { res = matchResult[0][0][0][0](c, async () => { c.res = await __privateGet(this, _notFoundHandler2).call(this, c); }); } catch (err) { return __privateMethod(this, __Hono_instances, handleError_fn).call(this, err, c); } return res instanceof Promise ? res.then((resolved) => resolved || (c.finalized ? c.res : __privateGet(this, _notFoundHandler2).call(this, c))).catch((err) => __privateMethod(this, __Hono_instances, handleError_fn).call(this, err, c)) : res ?? __privateGet(this, _notFoundHandler2).call(this, c); } const composed = compose(matchResult[0], this.errorHandler, __privateGet(this, _notFoundHandler2)); return (async () => { try { const context = await composed(c); if (!context.finalized) { throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?"); } return context.res; } catch (err) { return __privateMethod(this, __Hono_instances, handleError_fn).call(this, err, c); } })(); }, _d); var emptyParams = /* @__PURE__ */ Object.create(null); var PatternRouter = (_e = class { constructor() { __publicField(this, "name", "PatternRouter"); __privateAdd(this, _routes, []); } add(method, path2, handler) { const endsWithWildcard = path2.at(-1) === "*"; if (endsWithWildcard) { path2 = path2.slice(0, -2); } if (path2.at(-1) === "?") { path2 = path2.slice(0, -1); this.add(method, path2.replace(/\/[^/]+$/, ""), handler); } const parts = (path2.match(/\/?(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/?[^\/\?]+/g) || []).map((part) => { const match = part.match(/^\/:([^{]+)(?:{(.*)})?/); return match ? `/(?<${match[1]}>${match[2] || "[^/]+"})` : part === "/*" ? "/[^/]+" : part.replace(/[.\\+*[^\]$()]/g, "\\$&"); }); try { __privateGet(this, _routes).push([ new RegExp(`^${parts.join("")}${endsWithWildcard ? "" : "/?$"}`), method, handler ]); } catch { throw new UnsupportedPathError(); } } match(method, path2) { const handlers = []; for (let i = 0, len = __privateGet(this, _routes).length; i < len; i++) { const [pattern, routeMethod, handler] = __privateGet(this, _routes)[i]; if (routeMethod === method || routeMethod === METHOD_NAME_ALL) { const match = pattern.exec(path2); if (match) { handlers.push([ handler, match.groups || emptyParams ]); } } } return [ handlers ]; } }, _routes = new WeakMap(), _e); var Hono = class extends Hono$1 { constructor(options = {}) { super(options); this.router = new PatternRouter(); } }; const serverReferences = {}; initialize(); function initialize() { setRequireModule({ load: async (id) => { { const import_ = serverReferences[id]; if (!import_) throw new Error(`server reference not found '${id}'`); return import_(); } } }); } function renderToReadableStream(data, options, extraOptions) { return renderToReadableStream$1(data, options, { onClientReference(metadata) { var _a2; const deps = assetsManifest.clientReferenceDeps[metadata.id] ?? { js: [], css: [] }; (_a2 = extraOptions == null ? void 0 : extraOptions.onClientReference) == null ? void 0 : _a2.call(extraOptions, { id: metadata.id, name: metadata.name, deps }); } }); } const config = { "basePath": "/", "srcDir": "src", "distDir": "dist", "privateDir": "private", "rscBase": "RSC", "unstable_adapter": "waku/adapters/node" }; const isBuild = true; const notFoundHtml = void 0; const DIST_PUBLIC$1 = "public"; const DIST_SERVER = "server"; const BUILD_METADATA_FILE = "__waku_build_metadata.js"; const constants = Object.freeze(Object.defineProperty({ __proto__: null, BUILD_METADATA_FILE, DIST_PUBLIC: DIST_PUBLIC$1, DIST_SERVER }, Symbol.toStringTag, { value: "Module" })); function createRenderUtils(temporaryReferences, renderToReadableStream2, createFromReadableStream2, loadSsrEntryModule2) { const onError = (e) => { console.error("Error during rendering:", e); if (e && typeof e === "object" && "digest" in e && typeof e.digest === "string") { return e.digest; } }; return { async renderRsc(elements, options) { return renderToReadableStream2(elements, { temporaryReferences, onError }, { onClientReference(metadata) { var _a2; (_a2 = options == null ? void 0 : options.unstable_clientModuleCallback) == null ? void 0 : _a2.call(options, metadata.deps.js); } }); }, async parseRsc(stream) { return createFromReadableStream2(stream, {}); }, async renderHtml(elementsStream, html, options) { const { INTERNAL_renderHtmlStream: renderHtmlStream } = await loadSsrEntryModule2(); const rscHtmlStream = renderToReadableStream2(html, { onError }); const htmlResult = await renderHtmlStream(elementsStream, rscHtmlStream, { rscPath: options.rscPath, formState: options.formState, nonce: options.nonce, extraScriptContent: options.unstable_extraScriptContent }); return new Response(htmlResult.stream, { status: htmlResult.status || options.status || 200, headers: { "content-type": "text/html" } }); } }; } const encodeRscPath = (rscPath) => { if (rscPath === "") { rscPath = "_"; } else { if (rscPath.startsWith("_") || rscPath.startsWith("/")) { rscPath = "_" + rscPath; } if (rscPath.endsWith("_") || rscPath.endsWith("/")) { rscPath += "_"; } } return rscPath + ".txt"; }; const decodeRscPath = (rscPath) => { if (!rscPath.endsWith(".txt")) { const err = new Error("Invalid encoded rscPath"); err.statusCode = 400; throw err; } rscPath = rscPath.slice(0, -".txt".length); if (rscPath.startsWith("_")) { rscPath = rscPath.slice(1); } if (rscPath.endsWith("_")) { rscPath = rscPath.slice(0, -1); } return rscPath; }; const FUNC_PREFIX = "F/"; const decodeFuncId = (encoded) => { if (!encoded.startsWith(FUNC_PREFIX)) { return null; } const index = encoded.lastIndexOf("/"); const file = encoded.slice(FUNC_PREFIX.length, index); const name = encoded.slice(index + 1); if (file.startsWith("_")) { return file.slice(1) + "#" + name; } return file + "#" + name; }; async function getInput(req, config2, temporaryReferences, decodeReply2, decodeAction2, decodeFormState2, loadServerAction2) { const url = new URL(req.url); const pathname = removeBase(url.pathname, config2.basePath); const rscPathPrefix = "/" + config2.rscBase + "/"; let rscPath; let input; if (pathname.startsWith(rscPathPrefix)) { rscPath = decodeRscPath(pathname.slice(rscPathPrefix.length)); const actionId = decodeFuncId(rscPath); if (actionId) { const body = await getActionBody(req); const args = await decodeReply2(body, { temporaryReferences }); const action = await loadServerAction2(actionId); input = { type: "function", fn: action, args, pathname, req }; } else { let rscParams = url.searchParams; if (req.body) { const body = await getActionBody(req); rscParams = await decodeReply2(body, { temporaryReferences }); } input = { type: "component", rscPath, rscParams, pathname, req }; } } else if (req.method === "POST") { const contentType = req.headers.get("content-type"); if (typeof contentType === "string" && contentType.startsWith("multipart/form-data")) { input = { type: "action", fn: async () => { const formData = await getActionBody(req); const decodedAction = await decodeAction2(formData); const result = await decodedAction(); return await decodeFormState2(result, formData); }, pathname, req }; } else { input = { type: "custom", pathname, req }; } } else { input = { type: "custom", pathname, req }; } return input; } async function getActionBody(req) { if (!req.body) { throw new Error("missing request body for server function"); } const contentType = req.headers.get("content-type"); if (contentType == null ? void 0 : contentType.startsWith("multipart/form-data")) { return req.formData(); } else { return req.text(); } } function loadSsrEntryModule() { return import("../ssr/index.js"); } const toProcessRequest = (handleRequest) => async (req) => { const temporaryReferences = createTemporaryReferenceSet(); const input = await getInput(req, config, temporaryReferences, decodeReply, decodeAction, decodeFormState, loadServerAction); const renderUtils = createRenderUtils(temporaryReferences, renderToReadableStream, createFromReadableStream, loadSsrEntryModule); let res; try { res = await handleRequest(input, { ...renderUtils, loadBuildMetadata: async (key) => buildMetadata.get(key) }); } catch (e) { const info = getErrorInfo(e); const status = (info == null ? void 0 : info.status) || 500; const body = stringToStream((e == null ? void 0 : e.message) || String(e)); const headers = {}; if (info == null ? void 0 : info.location) { headers.location = info.location; } return new Response(body, { status, headers }); } if (res instanceof ReadableStream) { return new Response(res); } else if (res && res !== "fallback") { return res; } const url = new URL(req.url); if (res === "fallback" || !res && url.pathname === "/") { const { INTERNAL_renderHtmlFallback } = await loadSsrEntryModule(); const htmlFallbackStream = await INTERNAL_renderHtmlFallback(); const headers = { "content-type": "text/html; charset=utf-8" }; return new Response(htmlFallbackStream, { headers }); } return null; }; const toProcessBuild = (handleBuild) => async ({ emitFile }) => { const renderUtils = createRenderUtils(void 0, renderToReadableStream, createFromReadableStream, loadSsrEntryModule); let fallbackHtml; const getFallbackHtml = async () => { if (!fallbackHtml) { const ssrEntryModule = await loadSsrEntryModule(); fallbackHtml = await ssrEntryModule.INTERNAL_renderHtmlFallback(); } return fallbackHtml; }; const buildMetadata2 = /* @__PURE__ */ new Map(); await handleBuild({ renderRsc: renderUtils.renderRsc, parseRsc: renderUtils.parseRsc, renderHtml: renderUtils.renderHtml, rscPath2pathname: (rscPath) => joinPath(config.rscBase, encodeRscPath(rscPath)), saveBuildMetadata: async (key, value) => { buildMetadata2.set(key, value); }, withRequest: (req, fn) => INTERNAL_runWithContext(req, fn), generateFile: async (fileName, body) => { await emitFile(joinPath(DIST_PUBLIC$1, fileName), typeof body === "string" ? stringToStream(body) : body); }, generateDefaultHtml: async (fileName) => { await emitFile(joinPath(DIST_PUBLIC$1, fileName), stringToStream(await getFallbackHtml())); } }); await emitFile(joinPath(DIST_SERVER, BUILD_METADATA_FILE), stringToStream(`export const buildMetadata = new Map(${JSON.stringify(Array.from(buildMetadata2))});`)); }; const createServerEntryAdapter = (fn) => (handlers, options) => { const processRequest = toProcessRequest(handlers.handleRequest); const processBuild = toProcessBuild(handlers.handleBuild); return fn({ handlers, processRequest, processBuild, setAllEnv: INTERNAL_setAllEnv, config, isBuild, notFoundHtml }, options); }; function contextMiddleware$1() { return (c, next) => { const req = c.req.raw; return INTERNAL_runWithContext(req, next); }; } function rscMiddleware$1({ processRequest }) { return async (c, next) => { const req = c.req.raw; const res = await processRequest(req); if (res) { c.res = res; return; } await next(); }; } function middlewareRunner$1(middlewareModules) { let handlersPromise; return async (c, next) => { if (!handlersPromise) { handlersPromise = Promise.all(Object.values(middlewareModules).map((m) => m().then((mod) => mod.default()))); } const handlers = await handlersPromise; const run = async (index) => { const handler = handlers[index]; if (handler) { await handler(c, () => run(index + 1)); } else { await next(); } }; await run(0); }; } const honoMiddleware = Object.freeze(Object.defineProperty({ __proto__: null, contextMiddleware: contextMiddleware$1, middlewareRunner: middlewareRunner$1, rscMiddleware: rscMiddleware$1 }, Symbol.toStringTag, { value: "Module" })); const { DIST_PUBLIC } = constants; const { contextMiddleware, rscMiddleware, middlewareRunner } = honoMiddleware; const adapter = createServerEntryAdapter(({ processRequest, processBuild, config: config2, isBuild: isBuild2, notFoundHtml: notFoundHtml2 }, options) => { const { middlewareFns = [], middlewareModules = {} } = options || {}; const app = new Hono(); app.notFound((c) => { if (notFoundHtml2) { return c.html(notFoundHtml2, 404); } return c.text("404 Not Found", 404); }); if (isBuild2) { app.use(`${config2.basePath}*`, serveStatic({ root: path.join(config2.distDir, DIST_PUBLIC), rewriteRequestPath: (path2) => path2.slice(config2.basePath.length - 1) })); } app.use(contextMiddleware()); for (const middlewareFn of middlewareFns) { app.use(middlewareFn()); } app.use(middlewareRunner(middlewareModules)); app.use(rscMiddleware({ processRequest })); const buildOptions = { distDir: config2.distDir }; return { fetch: app.fetch, build: processBuild, buildOptions, buildEnhancers: [ "waku/adapters/node-build-enhancer" ], serve }; }); serverEntry = adapter(fsRouter(Object.assign({ "./_layout.tsx": () => import("./_layout-Cnq791cx.js"), "./_root.tsx": () => import("./_root-_BZAZd6T.js"), "./index.tsx": () => import("./index-BU_VRdfq.js"), "./poll/[id].tsx": () => import("./_id_-D3sxE6t8.js") })), { middlewareModules: Object.assign({}) }); })(); export { INTERNAL_setAllEnv as I, __vite_rsc_react__ as _, __tla, jsxRuntime_reactServerExports as a, joinPath as j, registerClientReference as r, serverEntry as s };