diff --git a/.example.env b/.example.env new file mode 100644 index 000000000..d37cde2c7 --- /dev/null +++ b/.example.env @@ -0,0 +1,5 @@ +PORT=8080 +POSTGRES_URI=postgres://root:example@0.0.0.0:5432/animegarden +REDIS_URI=redis://0.0.0.0:6379 +MEILI_URL=http://0.0.0.0:7700 +MEILI_KEY=example diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index c0e2b620e..7f3831dfa 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -7,12 +7,13 @@ on: - main - remix paths: + - apps/frontend/web/** - packages/worker/** - packages/anitomy/** - packages/animegarden/** jobs: - deploy: + worker: runs-on: ubuntu-latest if: github.ref == 'refs/heads/main' @@ -62,6 +63,8 @@ jobs: - name: Build run: pnpm build:web + env: + SSR_ADAPTER: cloudflare - name: Deploy run: pnpm -C apps/frontend/web run deploy:worker diff --git a/apps/backend/database/.gitkeep b/apps/backend/database/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/apps/backend/manager/.gitkeep b/apps/backend/manager/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/apps/backend/server/.gitkeep b/apps/backend/server/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/apps/frontend/app/.gitkeep b/apps/frontend/app/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/apps/frontend/web/.gitignore b/apps/frontend/web/.gitignore new file mode 100644 index 000000000..041bfb028 --- /dev/null +++ b/apps/frontend/web/.gitignore @@ -0,0 +1,6 @@ +node_modules + +/.cache +/build +.env +.wrangler diff --git a/apps/frontend/web/.wrangler/tmp/deploy-SnAdjV/worker.js b/apps/frontend/web/.wrangler/tmp/deploy-SnAdjV/worker.js new file mode 100644 index 000000000..92962e291 --- /dev/null +++ b/apps/frontend/web/.wrangler/tmp/deploy-SnAdjV/worker.js @@ -0,0 +1,50106 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// ../../../node_modules/.pnpm/cookie@0.6.0/node_modules/cookie/index.js +var require_cookie = __commonJS({ + "../../../node_modules/.pnpm/cookie@0.6.0/node_modules/cookie/index.js"(exports) { + "use strict"; + exports.parse = parse; + exports.serialize = serialize; + var __toString = Object.prototype.toString; + var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + function parse(str, options) { + if (typeof str !== "string") { + throw new TypeError("argument str must be a string"); + } + var obj = {}; + var opt = options || {}; + var dec = opt.decode || decode; + var index = 0; + while (index < str.length) { + var eqIdx = str.indexOf("=", index); + if (eqIdx === -1) { + break; + } + var endIdx = str.indexOf(";", index); + if (endIdx === -1) { + endIdx = str.length; + } else if (endIdx < eqIdx) { + index = str.lastIndexOf(";", eqIdx - 1) + 1; + continue; + } + var key = str.slice(index, eqIdx).trim(); + if (void 0 === obj[key]) { + var val = str.slice(eqIdx + 1, endIdx).trim(); + if (val.charCodeAt(0) === 34) { + val = val.slice(1, -1); + } + obj[key] = tryDecode(val, dec); + } + index = endIdx + 1; + } + return obj; + } + function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + if (typeof enc !== "function") { + throw new TypeError("option encode is invalid"); + } + if (!fieldContentRegExp.test(name)) { + throw new TypeError("argument name is invalid"); + } + var value = enc(val); + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError("argument val is invalid"); + } + var str = name + "=" + value; + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + if (isNaN(maxAge) || !isFinite(maxAge)) { + throw new TypeError("option maxAge is invalid"); + } + str += "; Max-Age=" + Math.floor(maxAge); + } + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError("option domain is invalid"); + } + str += "; Domain=" + opt.domain; + } + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError("option path is invalid"); + } + str += "; Path=" + opt.path; + } + if (opt.expires) { + var expires = opt.expires; + if (!isDate(expires) || isNaN(expires.valueOf())) { + throw new TypeError("option expires is invalid"); + } + str += "; Expires=" + expires.toUTCString(); + } + if (opt.httpOnly) { + str += "; HttpOnly"; + } + if (opt.secure) { + str += "; Secure"; + } + if (opt.partitioned) { + str += "; Partitioned"; + } + if (opt.priority) { + var priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority; + switch (priority) { + case "low": + str += "; Priority=Low"; + break; + case "medium": + str += "; Priority=Medium"; + break; + case "high": + str += "; Priority=High"; + break; + default: + throw new TypeError("option priority is invalid"); + } + } + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite; + switch (sameSite) { + case true: + str += "; SameSite=Strict"; + break; + case "lax": + str += "; SameSite=Lax"; + break; + case "strict": + str += "; SameSite=Strict"; + break; + case "none": + str += "; SameSite=None"; + break; + default: + throw new TypeError("option sameSite is invalid"); + } + } + return str; + } + function decode(str) { + return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str; + } + function encode(val) { + return encodeURIComponent(val); + } + function isDate(val) { + return __toString.call(val) === "[object Date]" || val instanceof Date; + } + function tryDecode(str, decode2) { + try { + return decode2(str); + } catch (e2) { + return str; + } + } + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/warnings.js +var require_warnings = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/warnings.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var alreadyWarned = {}; + function warnOnce(condition, message) { + if (!condition && !alreadyWarned[message]) { + alreadyWarned[message] = true; + console.warn(message); + } + } + exports.warnOnce = warnOnce; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/cookies.js +var require_cookies = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/cookies.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var cookie = require_cookie(); + var warnings = require_warnings(); + var createCookieFactory = ({ + sign, + unsign + }) => (name, cookieOptions = {}) => { + let { + secrets = [], + ...options + } = { + path: "/", + sameSite: "lax", + ...cookieOptions + }; + warnOnceAboutExpiresCookie(name, options.expires); + return { + get name() { + return name; + }, + get isSigned() { + return secrets.length > 0; + }, + get expires() { + return typeof options.maxAge !== "undefined" ? new Date(Date.now() + options.maxAge * 1e3) : options.expires; + }, + async parse(cookieHeader, parseOptions) { + if (!cookieHeader) + return null; + let cookies = cookie.parse(cookieHeader, { + ...options, + ...parseOptions + }); + return name in cookies ? cookies[name] === "" ? "" : await decodeCookieValue(unsign, cookies[name], secrets) : null; + }, + async serialize(value, serializeOptions) { + return cookie.serialize(name, value === "" ? "" : await encodeCookieValue(sign, value, secrets), { + ...options, + ...serializeOptions + }); + } + }; + }; + var isCookie = (object) => { + return object != null && typeof object.name === "string" && typeof object.isSigned === "boolean" && typeof object.parse === "function" && typeof object.serialize === "function"; + }; + async function encodeCookieValue(sign, value, secrets) { + let encoded = encodeData(value); + if (secrets.length > 0) { + encoded = await sign(encoded, secrets[0]); + } + return encoded; + } + async function decodeCookieValue(unsign, value, secrets) { + if (secrets.length > 0) { + for (let secret of secrets) { + let unsignedValue = await unsign(value, secret); + if (unsignedValue !== false) { + return decodeData(unsignedValue); + } + } + return null; + } + return decodeData(value); + } + function encodeData(value) { + return btoa(myUnescape(encodeURIComponent(JSON.stringify(value)))); + } + function decodeData(value) { + try { + return JSON.parse(decodeURIComponent(myEscape(atob(value)))); + } catch (error) { + return {}; + } + } + function myEscape(value) { + let str = value.toString(); + let result = ""; + let index = 0; + let chr, code; + while (index < str.length) { + chr = str.charAt(index++); + if (/[\w*+\-./@]/.exec(chr)) { + result += chr; + } else { + code = chr.charCodeAt(0); + if (code < 256) { + result += "%" + hex(code, 2); + } else { + result += "%u" + hex(code, 4).toUpperCase(); + } + } + } + return result; + } + function hex(code, length) { + let result = code.toString(16); + while (result.length < length) + result = "0" + result; + return result; + } + function myUnescape(value) { + let str = value.toString(); + let result = ""; + let index = 0; + let chr, part; + while (index < str.length) { + chr = str.charAt(index++); + if (chr === "%") { + if (str.charAt(index) === "u") { + part = str.slice(index + 1, index + 5); + if (/^[\da-f]{4}$/i.exec(part)) { + result += String.fromCharCode(parseInt(part, 16)); + index += 5; + continue; + } + } else { + part = str.slice(index, index + 2); + if (/^[\da-f]{2}$/i.exec(part)) { + result += String.fromCharCode(parseInt(part, 16)); + index += 2; + continue; + } + } + } + result += chr; + } + return result; + } + function warnOnceAboutExpiresCookie(name, expires) { + warnings.warnOnce(!expires, `The "${name}" cookie has an "expires" property set. This will cause the expires value to not be updated when the session is committed. Instead, you should set the expires value when serializing the cookie. You can use \`commitSession(session, { expires })\` if using a session storage object, or \`cookie.serialize("value", { expires })\` if you're using the cookie directly.`); + } + exports.createCookieFactory = createCookieFactory; + exports.isCookie = isCookie; + } +}); + +// ../../../node_modules/.pnpm/@web3-storage+multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/utils.js +function stringToArray(s) { + const utf8 = unescape(encodeURIComponent(s)); + return Uint8Array.from(utf8, (_, i2) => utf8.charCodeAt(i2)); +} +function arrayToString(a2) { + const utf8 = String.fromCharCode.apply(null, a2); + return decodeURIComponent(escape(utf8)); +} +function mergeArrays(...arrays) { + const out = new Uint8Array(arrays.reduce((total, arr) => total + arr.length, 0)); + let offset = 0; + for (const arr of arrays) { + out.set(arr, offset); + offset += arr.length; + } + return out; +} +function arraysEqual(a2, b) { + if (a2.length !== b.length) { + return false; + } + for (let i2 = 0; i2 < a2.length; i2++) { + if (a2[i2] !== b[i2]) { + return false; + } + } + return true; +} +var init_utils = __esm({ + "../../../node_modules/.pnpm/@web3-storage+multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/utils.js"() { + } +}); + +// ../../../node_modules/.pnpm/@web3-storage+multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/search.js +function coerce(a2) { + if (a2 instanceof Uint8Array) { + return (index) => a2[index]; + } + return a2; +} +function jsmemcmp(buf1, pos1, buf2, pos2, len) { + const fn1 = coerce(buf1); + const fn2 = coerce(buf2); + for (let i2 = 0; i2 < len; ++i2) { + if (fn1(pos1 + i2) !== fn2(pos2 + i2)) { + return false; + } + } + return true; +} +function createOccurenceTable(s) { + const table = new Array(256).fill(s.length); + if (s.length > 1) { + for (let i2 = 0; i2 < s.length - 1; i2++) { + table[s[i2]] = s.length - 1 - i2; + } + } + return table; +} +var MATCH, StreamSearch, ReadableStreamSearch, EOQ, QueueableStreamSearch; +var init_search = __esm({ + "../../../node_modules/.pnpm/@web3-storage+multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/search.js"() { + init_utils(); + MATCH = Symbol("Match"); + StreamSearch = class { + constructor(needle) { + this._lookbehind = new Uint8Array(); + if (typeof needle === "string") { + this._needle = needle = stringToArray(needle); + } else { + this._needle = needle; + } + this._lastChar = needle[needle.length - 1]; + this._occ = createOccurenceTable(needle); + } + feed(chunk) { + let pos = 0; + let tokens; + const allTokens = []; + while (pos !== chunk.length) { + ; + [pos, ...tokens] = this._feed(chunk, pos); + allTokens.push(...tokens); + } + return allTokens; + } + end() { + const tail = this._lookbehind; + this._lookbehind = new Uint8Array(); + return tail; + } + _feed(data, bufPos) { + const tokens = []; + let pos = -this._lookbehind.length; + if (pos < 0) { + while (pos < 0 && pos <= data.length - this._needle.length) { + const ch = this._charAt(data, pos + this._needle.length - 1); + if (ch === this._lastChar && this._memcmp(data, pos, this._needle.length - 1)) { + if (pos > -this._lookbehind.length) { + tokens.push(this._lookbehind.slice(0, this._lookbehind.length + pos)); + } + tokens.push(MATCH); + this._lookbehind = new Uint8Array(); + return [ + pos + this._needle.length, + ...tokens + ]; + } else { + pos += this._occ[ch]; + } + } + if (pos < 0) { + while (pos < 0 && !this._memcmp(data, pos, data.length - pos)) { + pos++; + } + } + if (pos >= 0) { + tokens.push(this._lookbehind); + this._lookbehind = new Uint8Array(); + } else { + const bytesToCutOff = this._lookbehind.length + pos; + if (bytesToCutOff > 0) { + tokens.push(this._lookbehind.slice(0, bytesToCutOff)); + this._lookbehind = this._lookbehind.slice(bytesToCutOff); + } + this._lookbehind = Uint8Array.from(new Array(this._lookbehind.length + data.length), (_, i2) => this._charAt(data, i2 - this._lookbehind.length)); + return [ + data.length, + ...tokens + ]; + } + } + pos += bufPos; + while (pos <= data.length - this._needle.length) { + const ch = data[pos + this._needle.length - 1]; + if (ch === this._lastChar && data[pos] === this._needle[0] && jsmemcmp(this._needle, 0, data, pos, this._needle.length - 1)) { + if (pos > bufPos) { + tokens.push(data.slice(bufPos, pos)); + } + tokens.push(MATCH); + return [ + pos + this._needle.length, + ...tokens + ]; + } else { + pos += this._occ[ch]; + } + } + if (pos < data.length) { + while (pos < data.length && (data[pos] !== this._needle[0] || !jsmemcmp(data, pos, this._needle, 0, data.length - pos))) { + ++pos; + } + if (pos < data.length) { + this._lookbehind = data.slice(pos); + } + } + if (pos > 0) { + tokens.push(data.slice(bufPos, pos < data.length ? pos : data.length)); + } + return [ + data.length, + ...tokens + ]; + } + _charAt(data, pos) { + if (pos < 0) { + return this._lookbehind[this._lookbehind.length + pos]; + } + return data[pos]; + } + _memcmp(data, pos, len) { + return jsmemcmp(this._charAt.bind(this, data), pos, this._needle, 0, len); + } + }; + ReadableStreamSearch = class { + constructor(needle, _readableStream) { + this._readableStream = _readableStream; + this._search = new StreamSearch(needle); + } + async *[Symbol.asyncIterator]() { + const reader = this._readableStream.getReader(); + try { + while (true) { + const result = await reader.read(); + if (result.done) { + break; + } + yield* this._search.feed(result.value); + } + const tail = this._search.end(); + if (tail.length) { + yield tail; + } + } finally { + reader.releaseLock(); + } + } + }; + EOQ = Symbol("End of Queue"); + QueueableStreamSearch = class { + constructor(needle) { + this._chunksQueue = []; + this._closed = false; + this._search = new StreamSearch(needle); + } + push(...chunks) { + if (this._closed) { + throw new Error("cannot call push after close"); + } + this._chunksQueue.push(...chunks); + if (this._notify) { + this._notify(); + } + } + close() { + if (this._closed) { + throw new Error("close was already called"); + } + this._closed = true; + this._chunksQueue.push(EOQ); + if (this._notify) { + this._notify(); + } + } + async *[Symbol.asyncIterator]() { + while (true) { + let chunk; + while (!(chunk = this._chunksQueue.shift())) { + await new Promise((resolve) => this._notify = resolve); + this._notify = void 0; + } + if (chunk === EOQ) { + break; + } + yield* this._search.feed(chunk); + } + const tail = this._search.end(); + if (tail.length) { + yield tail; + } + } + }; + } +}); + +// ../../../node_modules/.pnpm/@web3-storage+multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/index.js +var src_exports = {}; +__export(src_exports, { + iterateMultipart: () => iterateMultipart, + streamMultipart: () => streamMultipart +}); +function parseContentDisposition(header) { + const parts = header.split(";").map((part) => part.trim()); + if (parts.shift() !== "form-data") { + throw new Error('malformed content-disposition header: missing "form-data" in `' + JSON.stringify(parts) + "`"); + } + const out = {}; + for (const part of parts) { + const kv = part.split("=", 2); + if (kv.length !== 2) { + throw new Error("malformed content-disposition header: key-value pair not found - " + part + " in `" + header + "`"); + } + const [name, value] = kv; + if (value[0] === '"' && value[value.length - 1] === '"') { + out[name] = value.slice(1, -1).replace(/\\"/g, '"'); + } else if (value[0] !== '"' && value[value.length - 1] !== '"') { + out[name] = value; + } else if (value[0] === '"' && value[value.length - 1] !== '"' || value[0] !== '"' && value[value.length - 1] === '"') { + throw new Error("malformed content-disposition header: mismatched quotations in `" + header + "`"); + } + } + if (!out.name) { + throw new Error("malformed content-disposition header: missing field name in `" + header + "`"); + } + return out; +} +function parsePartHeaders(lines) { + const entries = []; + let disposition = false; + let line; + while (typeof (line = lines.shift()) !== "undefined") { + const colon = line.indexOf(":"); + if (colon === -1) { + throw new Error("malformed multipart-form header: missing colon"); + } + const header = line.slice(0, colon).trim().toLowerCase(); + const value = line.slice(colon + 1).trim(); + switch (header) { + case "content-disposition": + disposition = true; + entries.push(...Object.entries(parseContentDisposition(value))); + break; + case "content-type": + entries.push([ + "contentType", + value + ]); + } + } + if (!disposition) { + throw new Error("malformed multipart-form header: missing content-disposition"); + } + return Object.fromEntries(entries); +} +async function readHeaderLines(it, needle) { + let firstChunk = true; + let lastTokenWasMatch = false; + const headerLines = [[]]; + const crlfSearch = new StreamSearch(CRLF); + for (; ; ) { + const result = await it.next(); + if (result.done) { + throw new Error("malformed multipart-form data: unexpected end of stream"); + } + if (firstChunk && result.value !== MATCH && arraysEqual(result.value.slice(0, 2), dash)) { + return [ + void 0, + new Uint8Array() + ]; + } + let chunk; + if (result.value !== MATCH) { + chunk = result.value; + } else if (!lastTokenWasMatch) { + chunk = needle; + } else { + throw new Error("malformed multipart-form data: unexpected boundary"); + } + if (!chunk.length) { + continue; + } + if (firstChunk) { + firstChunk = false; + } + const tokens = crlfSearch.feed(chunk); + for (const [i2, token] of tokens.entries()) { + const isMatch = token === MATCH; + if (!isMatch && !token.length) { + continue; + } + if (lastTokenWasMatch && isMatch) { + tokens.push(crlfSearch.end()); + return [ + headerLines.filter((chunks) => chunks.length).map(mergeArrays2).map(arrayToString), + mergeArrays(...tokens.slice(i2 + 1).map((token2) => token2 === MATCH ? CRLF : token2)) + ]; + } + if (lastTokenWasMatch = isMatch) { + headerLines.push([]); + } else { + headerLines[headerLines.length - 1].push(token); + } + } + } +} +async function* streamMultipart(body, boundary) { + const needle = mergeArrays(dash, stringToArray(boundary)); + const it = new ReadableStreamSearch(needle, body)[Symbol.asyncIterator](); + for (; ; ) { + const result = await it.next(); + if (result.done) { + return; + } + if (result.value === MATCH) { + break; + } + } + const crlfSearch = new StreamSearch(CRLF); + for (; ; ) { + let feedChunk = function(chunk) { + const chunks = []; + for (const token of crlfSearch.feed(chunk)) { + if (trailingCRLF) { + chunks.push(CRLF); + } + if (!(trailingCRLF = token === MATCH)) { + chunks.push(token); + } + } + return mergeArrays(...chunks); + }; + const [headerLines, tail] = await readHeaderLines(it, needle); + if (!headerLines) { + return; + } + async function nextToken() { + const result = await it.next(); + if (result.done) { + throw new Error("malformed multipart-form data: unexpected end of stream"); + } + return result; + } + let trailingCRLF = false; + let done = false; + async function nextChunk() { + const result = await nextToken(); + let chunk; + if (result.value !== MATCH) { + chunk = result.value; + } else if (!trailingCRLF) { + chunk = CRLF; + } else { + done = true; + return { value: crlfSearch.end() }; + } + return { value: feedChunk(chunk) }; + } + const bufferedChunks = [{ value: feedChunk(tail) }]; + yield { + ...parsePartHeaders(headerLines), + data: { + [Symbol.asyncIterator]() { + return this; + }, + async next() { + for (; ; ) { + const result = bufferedChunks.shift(); + if (!result) { + break; + } + if (result.value.length > 0) { + return result; + } + } + for (; ; ) { + if (done) { + return { + done, + value: void 0 + }; + } + const result = await nextChunk(); + if (result.value.length > 0) { + return result; + } + } + } + } + }; + while (!done) { + bufferedChunks.push(await nextChunk()); + } + } +} +async function* iterateMultipart(body, boundary) { + for await (const part of streamMultipart(body, boundary)) { + const chunks = []; + for await (const chunk of part.data) { + chunks.push(chunk); + } + yield { + ...part, + data: mergeArrays(...chunks) + }; + } +} +var mergeArrays2, dash, CRLF; +var init_src = __esm({ + "../../../node_modules/.pnpm/@web3-storage+multipart-parser@1.0.0/node_modules/@web3-storage/multipart-parser/esm/src/index.js"() { + init_search(); + init_utils(); + mergeArrays2 = Function.prototype.apply.bind(mergeArrays, void 0); + dash = stringToArray("--"); + CRLF = stringToArray("\r\n"); + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/formData.js +var require_formData = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/formData.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var multipartParser = (init_src(), __toCommonJS(src_exports)); + function composeUploadHandlers(...handlers) { + return async (part) => { + for (let handler of handlers) { + let value = await handler(part); + if (typeof value !== "undefined" && value !== null) { + return value; + } + } + return void 0; + }; + } + async function parseMultipartFormData(request, uploadHandler) { + let contentType = request.headers.get("Content-Type") || ""; + let [type, boundary] = contentType.split(/\s*;\s*boundary=/); + if (!request.body || !boundary || type !== "multipart/form-data") { + throw new TypeError("Could not parse content as FormData."); + } + let formData = new FormData(); + let parts = multipartParser.streamMultipart(request.body, boundary); + for await (let part of parts) { + if (part.done) + break; + if (typeof part.filename === "string") { + part.filename = part.filename.split(/[/\\]/).pop(); + } + let value = await uploadHandler(part); + if (typeof value !== "undefined" && value !== null) { + formData.append(part.name, value); + } + } + return formData; + } + exports.composeUploadHandlers = composeUploadHandlers; + exports.parseMultipartFormData = parseMultipartFormData; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+router@1.19.2/node_modules/@remix-run/router/dist/router.cjs.js +var require_router_cjs = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+router@1.19.2/node_modules/@remix-run/router/dist/router.cjs.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + function _extends2() { + _extends2 = Object.assign ? Object.assign.bind() : function(target) { + for (var i2 = 1; i2 < arguments.length; i2++) { + var source = arguments[i2]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return _extends2.apply(this, arguments); + } + var Action = /* @__PURE__ */ function(Action2) { + Action2["Pop"] = "POP"; + Action2["Push"] = "PUSH"; + Action2["Replace"] = "REPLACE"; + return Action2; + }({}); + var PopStateEventType = "popstate"; + function createMemoryHistory(options) { + if (options === void 0) { + options = {}; + } + let { + initialEntries = ["/"], + initialIndex, + v5Compat = false + } = options; + let entries; + entries = initialEntries.map((entry, index2) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index2 === 0 ? "default" : void 0)); + let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex); + let action = Action.Pop; + let listener = null; + function clampIndex(n2) { + return Math.min(Math.max(n2, 0), entries.length - 1); + } + function getCurrentLocation() { + return entries[index]; + } + function createMemoryLocation(to, state, key) { + if (state === void 0) { + state = null; + } + let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key); + warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to)); + return location; + } + function createHref(to) { + return typeof to === "string" ? to : createPath2(to); + } + let history = { + get index() { + return index; + }, + get action() { + return action; + }, + get location() { + return getCurrentLocation(); + }, + createHref, + createURL(to) { + return new URL(createHref(to), "http://localhost"); + }, + encodeLocation(to) { + let path = typeof to === "string" ? parsePath3(to) : to; + return { + pathname: path.pathname || "", + search: path.search || "", + hash: path.hash || "" + }; + }, + push(to, state) { + action = Action.Push; + let nextLocation = createMemoryLocation(to, state); + index += 1; + entries.splice(index, entries.length, nextLocation); + if (v5Compat && listener) { + listener({ + action, + location: nextLocation, + delta: 1 + }); + } + }, + replace(to, state) { + action = Action.Replace; + let nextLocation = createMemoryLocation(to, state); + entries[index] = nextLocation; + if (v5Compat && listener) { + listener({ + action, + location: nextLocation, + delta: 0 + }); + } + }, + go(delta) { + action = Action.Pop; + let nextIndex = clampIndex(index + delta); + let nextLocation = entries[nextIndex]; + index = nextIndex; + if (listener) { + listener({ + action, + location: nextLocation, + delta + }); + } + }, + listen(fn) { + listener = fn; + return () => { + listener = null; + }; + } + }; + return history; + } + function createBrowserHistory(options) { + if (options === void 0) { + options = {}; + } + function createBrowserLocation(window2, globalHistory) { + let { + pathname, + search, + hash + } = window2.location; + return createLocation( + "", + { + pathname, + search, + hash + }, + // state defaults to `null` because `window.history.state` does + globalHistory.state && globalHistory.state.usr || null, + globalHistory.state && globalHistory.state.key || "default" + ); + } + function createBrowserHref(window2, to) { + return typeof to === "string" ? to : createPath2(to); + } + return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options); + } + function createHashHistory(options) { + if (options === void 0) { + options = {}; + } + function createHashLocation(window2, globalHistory) { + let { + pathname = "/", + search = "", + hash = "" + } = parsePath3(window2.location.hash.substr(1)); + if (!pathname.startsWith("/") && !pathname.startsWith(".")) { + pathname = "/" + pathname; + } + return createLocation( + "", + { + pathname, + search, + hash + }, + // state defaults to `null` because `window.history.state` does + globalHistory.state && globalHistory.state.usr || null, + globalHistory.state && globalHistory.state.key || "default" + ); + } + function createHashHref(window2, to) { + let base = window2.document.querySelector("base"); + let href = ""; + if (base && base.getAttribute("href")) { + let url = window2.location.href; + let hashIndex = url.indexOf("#"); + href = hashIndex === -1 ? url : url.slice(0, hashIndex); + } + return href + "#" + (typeof to === "string" ? to : createPath2(to)); + } + function validateHashLocation(location, to) { + warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")"); + } + return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options); + } + function invariant2(value, message) { + if (value === false || value === null || typeof value === "undefined") { + throw new Error(message); + } + } + function warning(cond, message) { + if (!cond) { + if (typeof console !== "undefined") + console.warn(message); + try { + throw new Error(message); + } catch (e2) { + } + } + } + function createKey() { + return Math.random().toString(36).substr(2, 8); + } + function getHistoryState(location, index) { + return { + usr: location.state, + key: location.key, + idx: index + }; + } + function createLocation(current, to, state, key) { + if (state === void 0) { + state = null; + } + let location = _extends2({ + pathname: typeof current === "string" ? current : current.pathname, + search: "", + hash: "" + }, typeof to === "string" ? parsePath3(to) : to, { + state, + // TODO: This could be cleaned up. push/replace should probably just take + // full Locations now and avoid the need to run through this flow at all + // But that's a pretty big refactor to the current test suite so going to + // keep as is for the time being and just let any incoming keys take precedence + key: to && to.key || key || createKey() + }); + return location; + } + function createPath2(_ref) { + let { + pathname = "/", + search = "", + hash = "" + } = _ref; + if (search && search !== "?") + pathname += search.charAt(0) === "?" ? search : "?" + search; + if (hash && hash !== "#") + pathname += hash.charAt(0) === "#" ? hash : "#" + hash; + return pathname; + } + function parsePath3(path) { + let parsedPath = {}; + if (path) { + let hashIndex = path.indexOf("#"); + if (hashIndex >= 0) { + parsedPath.hash = path.substr(hashIndex); + path = path.substr(0, hashIndex); + } + let searchIndex = path.indexOf("?"); + if (searchIndex >= 0) { + parsedPath.search = path.substr(searchIndex); + path = path.substr(0, searchIndex); + } + if (path) { + parsedPath.pathname = path; + } + } + return parsedPath; + } + function getUrlBasedHistory(getLocation, createHref, validateLocation, options) { + if (options === void 0) { + options = {}; + } + let { + window: window2 = document.defaultView, + v5Compat = false + } = options; + let globalHistory = window2.history; + let action = Action.Pop; + let listener = null; + let index = getIndex(); + if (index == null) { + index = 0; + globalHistory.replaceState(_extends2({}, globalHistory.state, { + idx: index + }), ""); + } + function getIndex() { + let state = globalHistory.state || { + idx: null + }; + return state.idx; + } + function handlePop() { + action = Action.Pop; + let nextIndex = getIndex(); + let delta = nextIndex == null ? null : nextIndex - index; + index = nextIndex; + if (listener) { + listener({ + action, + location: history.location, + delta + }); + } + } + function push(to, state) { + action = Action.Push; + let location = createLocation(history.location, to, state); + if (validateLocation) + validateLocation(location, to); + index = getIndex() + 1; + let historyState = getHistoryState(location, index); + let url = history.createHref(location); + try { + globalHistory.pushState(historyState, "", url); + } catch (error) { + if (error instanceof DOMException && error.name === "DataCloneError") { + throw error; + } + window2.location.assign(url); + } + if (v5Compat && listener) { + listener({ + action, + location: history.location, + delta: 1 + }); + } + } + function replace2(to, state) { + action = Action.Replace; + let location = createLocation(history.location, to, state); + if (validateLocation) + validateLocation(location, to); + index = getIndex(); + let historyState = getHistoryState(location, index); + let url = history.createHref(location); + globalHistory.replaceState(historyState, "", url); + if (v5Compat && listener) { + listener({ + action, + location: history.location, + delta: 0 + }); + } + } + function createURL(to) { + let base = window2.location.origin !== "null" ? window2.location.origin : window2.location.href; + let href = typeof to === "string" ? to : createPath2(to); + href = href.replace(/ $/, "%20"); + invariant2(base, "No window.location.(origin|href) available to create URL for href: " + href); + return new URL(href, base); + } + let history = { + get action() { + return action; + }, + get location() { + return getLocation(window2, globalHistory); + }, + listen(fn) { + if (listener) { + throw new Error("A history only accepts one active listener"); + } + window2.addEventListener(PopStateEventType, handlePop); + listener = fn; + return () => { + window2.removeEventListener(PopStateEventType, handlePop); + listener = null; + }; + }, + createHref(to) { + return createHref(window2, to); + }, + createURL, + encodeLocation(to) { + let url = createURL(to); + return { + pathname: url.pathname, + search: url.search, + hash: url.hash + }; + }, + push, + replace: replace2, + go(n2) { + return globalHistory.go(n2); + } + }; + return history; + } + var ResultType = /* @__PURE__ */ function(ResultType2) { + ResultType2["data"] = "data"; + ResultType2["deferred"] = "deferred"; + ResultType2["redirect"] = "redirect"; + ResultType2["error"] = "error"; + return ResultType2; + }({}); + var immutableRouteKeys = /* @__PURE__ */ new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]); + function isIndexRoute(route) { + return route.index === true; + } + function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) { + if (parentPath === void 0) { + parentPath = []; + } + if (manifest === void 0) { + manifest = {}; + } + return routes.map((route, index) => { + let treePath = [...parentPath, String(index)]; + let id = typeof route.id === "string" ? route.id : treePath.join("-"); + invariant2(route.index !== true || !route.children, "Cannot specify children on an index route"); + invariant2(!manifest[id], 'Found a route id collision on id "' + id + `". Route id's must be globally unique within Data Router usages`); + if (isIndexRoute(route)) { + let indexRoute = _extends2({}, route, mapRouteProperties(route), { + id + }); + manifest[id] = indexRoute; + return indexRoute; + } else { + let pathOrLayoutRoute = _extends2({}, route, mapRouteProperties(route), { + id, + children: void 0 + }); + manifest[id] = pathOrLayoutRoute; + if (route.children) { + pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest); + } + return pathOrLayoutRoute; + } + }); + } + function matchRoutes4(routes, locationArg, basename) { + if (basename === void 0) { + basename = "/"; + } + return matchRoutesImpl(routes, locationArg, basename, false); + } + function matchRoutesImpl(routes, locationArg, basename, allowPartial) { + let location = typeof locationArg === "string" ? parsePath3(locationArg) : locationArg; + let pathname = stripBasename(location.pathname || "/", basename); + if (pathname == null) { + return null; + } + let branches = flattenRoutes(routes); + rankRouteBranches(branches); + let matches = null; + for (let i2 = 0; matches == null && i2 < branches.length; ++i2) { + let decoded = decodePath(pathname); + matches = matchRouteBranch(branches[i2], decoded, allowPartial); + } + return matches; + } + function convertRouteMatchToUiMatch(match, loaderData) { + let { + route, + pathname, + params + } = match; + return { + id: route.id, + pathname, + params, + data: loaderData[route.id], + handle: route.handle + }; + } + function flattenRoutes(routes, branches, parentsMeta, parentPath) { + if (branches === void 0) { + branches = []; + } + if (parentsMeta === void 0) { + parentsMeta = []; + } + if (parentPath === void 0) { + parentPath = ""; + } + let flattenRoute = (route, index, relativePath) => { + let meta = { + relativePath: relativePath === void 0 ? route.path || "" : relativePath, + caseSensitive: route.caseSensitive === true, + childrenIndex: index, + route + }; + if (meta.relativePath.startsWith("/")) { + invariant2(meta.relativePath.startsWith(parentPath), 'Absolute route path "' + meta.relativePath + '" nested under path ' + ('"' + parentPath + '" is not valid. An absolute child route path ') + "must start with the combined path of all its parent routes."); + meta.relativePath = meta.relativePath.slice(parentPath.length); + } + let path = joinPaths([parentPath, meta.relativePath]); + let routesMeta = parentsMeta.concat(meta); + if (route.children && route.children.length > 0) { + invariant2( + // Our types know better, but runtime JS may not! + // @ts-expect-error + route.index !== true, + "Index routes must not have child routes. Please remove " + ('all child routes from route path "' + path + '".') + ); + flattenRoutes(route.children, branches, routesMeta, path); + } + if (route.path == null && !route.index) { + return; + } + branches.push({ + path, + score: computeScore(path, route.index), + routesMeta + }); + }; + routes.forEach((route, index) => { + var _route$path; + if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) { + flattenRoute(route, index); + } else { + for (let exploded of explodeOptionalSegments(route.path)) { + flattenRoute(route, index, exploded); + } + } + }); + return branches; + } + function explodeOptionalSegments(path) { + let segments = path.split("/"); + if (segments.length === 0) + return []; + let [first, ...rest] = segments; + let isOptional = first.endsWith("?"); + let required = first.replace(/\?$/, ""); + if (rest.length === 0) { + return isOptional ? [required, ""] : [required]; + } + let restExploded = explodeOptionalSegments(rest.join("/")); + let result = []; + result.push(...restExploded.map((subpath) => subpath === "" ? required : [required, subpath].join("/"))); + if (isOptional) { + result.push(...restExploded); + } + return result.map((exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded); + } + function rankRouteBranches(branches) { + branches.sort((a2, b) => a2.score !== b.score ? b.score - a2.score : compareIndexes(a2.routesMeta.map((meta) => meta.childrenIndex), b.routesMeta.map((meta) => meta.childrenIndex))); + } + var paramRe = /^:[\w-]+$/; + var dynamicSegmentValue = 3; + var indexRouteValue = 2; + var emptySegmentValue = 1; + var staticSegmentValue = 10; + var splatPenalty = -2; + var isSplat = (s) => s === "*"; + function computeScore(path, index) { + let segments = path.split("/"); + let initialScore = segments.length; + if (segments.some(isSplat)) { + initialScore += splatPenalty; + } + if (index) { + initialScore += indexRouteValue; + } + return segments.filter((s) => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore); + } + function compareIndexes(a2, b) { + let siblings = a2.length === b.length && a2.slice(0, -1).every((n2, i2) => n2 === b[i2]); + return siblings ? ( + // If two routes are siblings, we should try to match the earlier sibling + // first. This allows people to have fine-grained control over the matching + // behavior by simply putting routes with identical paths in the order they + // want them tried. + a2[a2.length - 1] - b[b.length - 1] + ) : ( + // Otherwise, it doesn't really make sense to rank non-siblings by index, + // so they sort equally. + 0 + ); + } + function matchRouteBranch(branch, pathname, allowPartial) { + if (allowPartial === void 0) { + allowPartial = false; + } + let { + routesMeta + } = branch; + let matchedParams = {}; + let matchedPathname = "/"; + let matches = []; + for (let i2 = 0; i2 < routesMeta.length; ++i2) { + let meta = routesMeta[i2]; + let end = i2 === routesMeta.length - 1; + let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/"; + let match = matchPath2({ + path: meta.relativePath, + caseSensitive: meta.caseSensitive, + end + }, remainingPathname); + let route = meta.route; + if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) { + match = matchPath2({ + path: meta.relativePath, + caseSensitive: meta.caseSensitive, + end: false + }, remainingPathname); + } + if (!match) { + return null; + } + Object.assign(matchedParams, match.params); + matches.push({ + // TODO: Can this as be avoided? + params: matchedParams, + pathname: joinPaths([matchedPathname, match.pathname]), + pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])), + route + }); + if (match.pathnameBase !== "/") { + matchedPathname = joinPaths([matchedPathname, match.pathnameBase]); + } + } + return matches; + } + function generatePath2(originalPath, params) { + if (params === void 0) { + params = {}; + } + let path = originalPath; + if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) { + warning(false, 'Route path "' + path + '" will be treated as if it were ' + ('"' + path.replace(/\*$/, "/*") + '" because the `*` character must ') + "always follow a `/` in the pattern. To get rid of this warning, " + ('please change the route path to "' + path.replace(/\*$/, "/*") + '".')); + path = path.replace(/\*$/, "/*"); + } + const prefix = path.startsWith("/") ? "/" : ""; + const stringify = (p) => p == null ? "" : typeof p === "string" ? p : String(p); + const segments = path.split(/\/+/).map((segment, index, array) => { + const isLastSegment = index === array.length - 1; + if (isLastSegment && segment === "*") { + const star = "*"; + return stringify(params[star]); + } + const keyMatch = segment.match(/^:([\w-]+)(\??)$/); + if (keyMatch) { + const [, key, optional] = keyMatch; + let param = params[key]; + invariant2(optional === "?" || param != null, 'Missing ":' + key + '" param'); + return stringify(param); + } + return segment.replace(/\?$/g, ""); + }).filter((segment) => !!segment); + return prefix + segments.join("/"); + } + function matchPath2(pattern, pathname) { + if (typeof pattern === "string") { + pattern = { + path: pattern, + caseSensitive: false, + end: true + }; + } + let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end); + let match = pathname.match(matcher); + if (!match) + return null; + let matchedPathname = match[0]; + let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1"); + let captureGroups = match.slice(1); + let params = compiledParams.reduce((memo, _ref, index) => { + let { + paramName, + isOptional + } = _ref; + if (paramName === "*") { + let splatValue = captureGroups[index] || ""; + pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1"); + } + const value = captureGroups[index]; + if (isOptional && !value) { + memo[paramName] = void 0; + } else { + memo[paramName] = (value || "").replace(/%2F/g, "/"); + } + return memo; + }, {}); + return { + params, + pathname: matchedPathname, + pathnameBase, + pattern + }; + } + function compilePath(path, caseSensitive, end) { + if (caseSensitive === void 0) { + caseSensitive = false; + } + if (end === void 0) { + end = true; + } + warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), 'Route path "' + path + '" will be treated as if it were ' + ('"' + path.replace(/\*$/, "/*") + '" because the `*` character must ') + "always follow a `/` in the pattern. To get rid of this warning, " + ('please change the route path to "' + path.replace(/\*$/, "/*") + '".')); + let params = []; + let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => { + params.push({ + paramName, + isOptional: isOptional != null + }); + return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)"; + }); + if (path.endsWith("*")) { + params.push({ + paramName: "*" + }); + regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$"; + } else if (end) { + regexpSource += "\\/*$"; + } else if (path !== "" && path !== "/") { + regexpSource += "(?:(?=\\/|$))"; + } else + ; + let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i"); + return [matcher, params]; + } + function decodePath(value) { + try { + return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/"); + } catch (error) { + warning(false, 'The URL path "' + value + '" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent ' + ("encoding (" + error + ").")); + return value; + } + } + function stripBasename(pathname, basename) { + if (basename === "/") + return pathname; + if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) { + return null; + } + let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length; + let nextChar = pathname.charAt(startIndex); + if (nextChar && nextChar !== "/") { + return null; + } + return pathname.slice(startIndex) || "/"; + } + function resolvePath2(to, fromPathname) { + if (fromPathname === void 0) { + fromPathname = "/"; + } + let { + pathname: toPathname, + search = "", + hash = "" + } = typeof to === "string" ? parsePath3(to) : to; + let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname; + return { + pathname, + search: normalizeSearch(search), + hash: normalizeHash(hash) + }; + } + function resolvePathname(relativePath, fromPathname) { + let segments = fromPathname.replace(/\/+$/, "").split("/"); + let relativeSegments = relativePath.split("/"); + relativeSegments.forEach((segment) => { + if (segment === "..") { + if (segments.length > 1) + segments.pop(); + } else if (segment !== ".") { + segments.push(segment); + } + }); + return segments.length > 1 ? segments.join("/") : "/"; + } + function getInvalidPathError(char, field, dest, path) { + return "Cannot include a '" + char + "' character in a manually specified " + ("`to." + field + "` field [" + JSON.stringify(path) + "]. Please separate it out to the ") + ("`to." + dest + "` field. Alternatively you may provide the full path as ") + 'a string in and the router will parse it for you.'; + } + function getPathContributingMatches(matches) { + return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0); + } + function getResolveToMatches(matches, v7_relativeSplatPath) { + let pathMatches = getPathContributingMatches(matches); + if (v7_relativeSplatPath) { + return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase); + } + return pathMatches.map((match) => match.pathnameBase); + } + function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) { + if (isPathRelative === void 0) { + isPathRelative = false; + } + let to; + if (typeof toArg === "string") { + to = parsePath3(toArg); + } else { + to = _extends2({}, toArg); + invariant2(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to)); + invariant2(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to)); + invariant2(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to)); + } + let isEmptyPath = toArg === "" || to.pathname === ""; + let toPathname = isEmptyPath ? "/" : to.pathname; + let from; + if (toPathname == null) { + from = locationPathname; + } else { + let routePathnameIndex = routePathnames.length - 1; + if (!isPathRelative && toPathname.startsWith("..")) { + let toSegments = toPathname.split("/"); + while (toSegments[0] === "..") { + toSegments.shift(); + routePathnameIndex -= 1; + } + to.pathname = toSegments.join("/"); + } + from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/"; + } + let path = resolvePath2(to, from); + let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/"); + let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/"); + if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) { + path.pathname += "/"; + } + return path; + } + function getToPathname(to) { + return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath3(to).pathname : to.pathname; + } + var joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/"); + var normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/"); + var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search; + var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash; + var json = function json2(data2, init) { + if (init === void 0) { + init = {}; + } + let responseInit = typeof init === "number" ? { + status: init + } : init; + let headers = new Headers(responseInit.headers); + if (!headers.has("Content-Type")) { + headers.set("Content-Type", "application/json; charset=utf-8"); + } + return new Response(JSON.stringify(data2), _extends2({}, responseInit, { + headers + })); + }; + var DataWithResponseInit = class { + constructor(data2, init) { + this.type = "DataWithResponseInit"; + this.data = data2; + this.init = init || null; + } + }; + function data(data2, init) { + return new DataWithResponseInit(data2, typeof init === "number" ? { + status: init + } : init); + } + var AbortedDeferredError = class extends Error { + }; + var DeferredData = class { + constructor(data2, responseInit) { + this.pendingKeysSet = /* @__PURE__ */ new Set(); + this.subscribers = /* @__PURE__ */ new Set(); + this.deferredKeys = []; + invariant2(data2 && typeof data2 === "object" && !Array.isArray(data2), "defer() only accepts plain objects"); + let reject; + this.abortPromise = new Promise((_, r) => reject = r); + this.controller = new AbortController(); + let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted")); + this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort); + this.controller.signal.addEventListener("abort", onAbort); + this.data = Object.entries(data2).reduce((acc, _ref2) => { + let [key, value] = _ref2; + return Object.assign(acc, { + [key]: this.trackPromise(key, value) + }); + }, {}); + if (this.done) { + this.unlistenAbortSignal(); + } + this.init = responseInit; + } + trackPromise(key, value) { + if (!(value instanceof Promise)) { + return value; + } + this.deferredKeys.push(key); + this.pendingKeysSet.add(key); + let promise = Promise.race([value, this.abortPromise]).then((data2) => this.onSettle(promise, key, void 0, data2), (error) => this.onSettle(promise, key, error)); + promise.catch(() => { + }); + Object.defineProperty(promise, "_tracked", { + get: () => true + }); + return promise; + } + onSettle(promise, key, error, data2) { + if (this.controller.signal.aborted && error instanceof AbortedDeferredError) { + this.unlistenAbortSignal(); + Object.defineProperty(promise, "_error", { + get: () => error + }); + return Promise.reject(error); + } + this.pendingKeysSet.delete(key); + if (this.done) { + this.unlistenAbortSignal(); + } + if (error === void 0 && data2 === void 0) { + let undefinedError = new Error('Deferred data for key "' + key + '" resolved/rejected with `undefined`, you must resolve/reject with a value or `null`.'); + Object.defineProperty(promise, "_error", { + get: () => undefinedError + }); + this.emit(false, key); + return Promise.reject(undefinedError); + } + if (data2 === void 0) { + Object.defineProperty(promise, "_error", { + get: () => error + }); + this.emit(false, key); + return Promise.reject(error); + } + Object.defineProperty(promise, "_data", { + get: () => data2 + }); + this.emit(false, key); + return data2; + } + emit(aborted, settledKey) { + this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey)); + } + subscribe(fn) { + this.subscribers.add(fn); + return () => this.subscribers.delete(fn); + } + cancel() { + this.controller.abort(); + this.pendingKeysSet.forEach((v, k2) => this.pendingKeysSet.delete(k2)); + this.emit(true); + } + async resolveData(signal) { + let aborted = false; + if (!this.done) { + let onAbort = () => this.cancel(); + signal.addEventListener("abort", onAbort); + aborted = await new Promise((resolve) => { + this.subscribe((aborted2) => { + signal.removeEventListener("abort", onAbort); + if (aborted2 || this.done) { + resolve(aborted2); + } + }); + }); + } + return aborted; + } + get done() { + return this.pendingKeysSet.size === 0; + } + get unwrappedData() { + invariant2(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds"); + return Object.entries(this.data).reduce((acc, _ref3) => { + let [key, value] = _ref3; + return Object.assign(acc, { + [key]: unwrapTrackedPromise(value) + }); + }, {}); + } + get pendingKeys() { + return Array.from(this.pendingKeysSet); + } + }; + function isTrackedPromise(value) { + return value instanceof Promise && value._tracked === true; + } + function unwrapTrackedPromise(value) { + if (!isTrackedPromise(value)) { + return value; + } + if (value._error) { + throw value._error; + } + return value._data; + } + var defer = function defer2(data2, init) { + if (init === void 0) { + init = {}; + } + let responseInit = typeof init === "number" ? { + status: init + } : init; + return new DeferredData(data2, responseInit); + }; + var redirect2 = function redirect3(url, init) { + if (init === void 0) { + init = 302; + } + let responseInit = init; + if (typeof responseInit === "number") { + responseInit = { + status: responseInit + }; + } else if (typeof responseInit.status === "undefined") { + responseInit.status = 302; + } + let headers = new Headers(responseInit.headers); + headers.set("Location", url); + return new Response(null, _extends2({}, responseInit, { + headers + })); + }; + var redirectDocument = (url, init) => { + let response = redirect2(url, init); + response.headers.set("X-Remix-Reload-Document", "true"); + return response; + }; + var replace = (url, init) => { + let response = redirect2(url, init); + response.headers.set("X-Remix-Replace", "true"); + return response; + }; + var ErrorResponseImpl = class { + constructor(status, statusText, data2, internal) { + if (internal === void 0) { + internal = false; + } + this.status = status; + this.statusText = statusText || ""; + this.internal = internal; + if (data2 instanceof Error) { + this.data = data2.toString(); + this.error = data2; + } else { + this.data = data2; + } + } + }; + function isRouteErrorResponse3(error) { + return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error; + } + var validMutationMethodsArr = ["post", "put", "patch", "delete"]; + var validMutationMethods = new Set(validMutationMethodsArr); + var validRequestMethodsArr = ["get", ...validMutationMethodsArr]; + var validRequestMethods = new Set(validRequestMethodsArr); + var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]); + var redirectPreserveMethodStatusCodes = /* @__PURE__ */ new Set([307, 308]); + var IDLE_NAVIGATION = { + state: "idle", + location: void 0, + formMethod: void 0, + formAction: void 0, + formEncType: void 0, + formData: void 0, + json: void 0, + text: void 0 + }; + var IDLE_FETCHER = { + state: "idle", + data: void 0, + formMethod: void 0, + formAction: void 0, + formEncType: void 0, + formData: void 0, + json: void 0, + text: void 0 + }; + var IDLE_BLOCKER = { + state: "unblocked", + proceed: void 0, + reset: void 0, + location: void 0 + }; + var ABSOLUTE_URL_REGEX2 = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; + var defaultMapRouteProperties = (route) => ({ + hasErrorBoundary: Boolean(route.hasErrorBoundary) + }); + var TRANSITIONS_STORAGE_KEY = "remix-router-transitions"; + function createRouter(init) { + const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : void 0; + const isBrowser = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined"; + const isServer = !isBrowser; + invariant2(init.routes.length > 0, "You must provide a non-empty routes array to createRouter"); + let mapRouteProperties; + if (init.mapRouteProperties) { + mapRouteProperties = init.mapRouteProperties; + } else if (init.detectErrorBoundary) { + let detectErrorBoundary = init.detectErrorBoundary; + mapRouteProperties = (route) => ({ + hasErrorBoundary: detectErrorBoundary(route) + }); + } else { + mapRouteProperties = defaultMapRouteProperties; + } + let manifest = {}; + let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, void 0, manifest); + let inFlightDataRoutes; + let basename = init.basename || "/"; + let dataStrategyImpl = init.unstable_dataStrategy || defaultDataStrategy; + let patchRoutesOnNavigationImpl = init.unstable_patchRoutesOnNavigation; + let future = _extends2({ + v7_fetcherPersist: false, + v7_normalizeFormMethod: false, + v7_partialHydration: false, + v7_prependBasename: false, + v7_relativeSplatPath: false, + v7_skipActionErrorRevalidation: false + }, init.future); + let unlistenHistory = null; + let subscribers = /* @__PURE__ */ new Set(); + let discoveredRoutesMaxSize = 1e3; + let discoveredRoutes = /* @__PURE__ */ new Set(); + let savedScrollPositions = null; + let getScrollRestorationKey = null; + let getScrollPosition = null; + let initialScrollRestored = init.hydrationData != null; + let initialMatches = matchRoutes4(dataRoutes, init.history.location, basename); + let initialErrors = null; + if (initialMatches == null && !patchRoutesOnNavigationImpl) { + let error = getInternalRouterError(404, { + pathname: init.history.location.pathname + }); + let { + matches, + route + } = getShortCircuitMatches(dataRoutes); + initialMatches = matches; + initialErrors = { + [route.id]: error + }; + } + if (initialMatches && !init.hydrationData) { + let fogOfWar = checkFogOfWar(initialMatches, dataRoutes, init.history.location.pathname); + if (fogOfWar.active) { + initialMatches = null; + } + } + let initialized; + if (!initialMatches) { + initialized = false; + initialMatches = []; + if (future.v7_partialHydration) { + let fogOfWar = checkFogOfWar(null, dataRoutes, init.history.location.pathname); + if (fogOfWar.active && fogOfWar.matches) { + initialMatches = fogOfWar.matches; + } + } + } else if (initialMatches.some((m) => m.route.lazy)) { + initialized = false; + } else if (!initialMatches.some((m) => m.route.loader)) { + initialized = true; + } else if (future.v7_partialHydration) { + let loaderData = init.hydrationData ? init.hydrationData.loaderData : null; + let errors = init.hydrationData ? init.hydrationData.errors : null; + let isRouteInitialized = (m) => { + if (!m.route.loader) { + return true; + } + if (typeof m.route.loader === "function" && m.route.loader.hydrate === true) { + return false; + } + return loaderData && loaderData[m.route.id] !== void 0 || errors && errors[m.route.id] !== void 0; + }; + if (errors) { + let idx = initialMatches.findIndex((m) => errors[m.route.id] !== void 0); + initialized = initialMatches.slice(0, idx + 1).every(isRouteInitialized); + } else { + initialized = initialMatches.every(isRouteInitialized); + } + } else { + initialized = init.hydrationData != null; + } + let router; + let state = { + historyAction: init.history.action, + location: init.history.location, + matches: initialMatches, + initialized, + navigation: IDLE_NAVIGATION, + // Don't restore on initial updateState() if we were SSR'd + restoreScrollPosition: init.hydrationData != null ? false : null, + preventScrollReset: false, + revalidation: "idle", + loaderData: init.hydrationData && init.hydrationData.loaderData || {}, + actionData: init.hydrationData && init.hydrationData.actionData || null, + errors: init.hydrationData && init.hydrationData.errors || initialErrors, + fetchers: /* @__PURE__ */ new Map(), + blockers: /* @__PURE__ */ new Map() + }; + let pendingAction = Action.Pop; + let pendingPreventScrollReset = false; + let pendingNavigationController; + let pendingViewTransitionEnabled = false; + let appliedViewTransitions = /* @__PURE__ */ new Map(); + let removePageHideEventListener = null; + let isUninterruptedRevalidation = false; + let isRevalidationRequired = false; + let cancelledDeferredRoutes = []; + let cancelledFetcherLoads = /* @__PURE__ */ new Set(); + let fetchControllers = /* @__PURE__ */ new Map(); + let incrementingLoadId = 0; + let pendingNavigationLoadId = -1; + let fetchReloadIds = /* @__PURE__ */ new Map(); + let fetchRedirectIds = /* @__PURE__ */ new Set(); + let fetchLoadMatches = /* @__PURE__ */ new Map(); + let activeFetchers = /* @__PURE__ */ new Map(); + let deletedFetchers = /* @__PURE__ */ new Set(); + let activeDeferreds = /* @__PURE__ */ new Map(); + let blockerFunctions = /* @__PURE__ */ new Map(); + let pendingPatchRoutes = /* @__PURE__ */ new Map(); + let unblockBlockerHistoryUpdate = void 0; + function initialize() { + unlistenHistory = init.history.listen((_ref) => { + let { + action: historyAction, + location, + delta + } = _ref; + if (unblockBlockerHistoryUpdate) { + unblockBlockerHistoryUpdate(); + unblockBlockerHistoryUpdate = void 0; + return; + } + warning(blockerFunctions.size === 0 || delta != null, "You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL."); + let blockerKey = shouldBlockNavigation({ + currentLocation: state.location, + nextLocation: location, + historyAction + }); + if (blockerKey && delta != null) { + let nextHistoryUpdatePromise = new Promise((resolve) => { + unblockBlockerHistoryUpdate = resolve; + }); + init.history.go(delta * -1); + updateBlocker(blockerKey, { + state: "blocked", + location, + proceed() { + updateBlocker(blockerKey, { + state: "proceeding", + proceed: void 0, + reset: void 0, + location + }); + nextHistoryUpdatePromise.then(() => init.history.go(delta)); + }, + reset() { + let blockers = new Map(state.blockers); + blockers.set(blockerKey, IDLE_BLOCKER); + updateState({ + blockers + }); + } + }); + return; + } + return startNavigation(historyAction, location); + }); + if (isBrowser) { + restoreAppliedTransitions(routerWindow, appliedViewTransitions); + let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions); + routerWindow.addEventListener("pagehide", _saveAppliedTransitions); + removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions); + } + if (!state.initialized) { + startNavigation(Action.Pop, state.location, { + initialHydration: true + }); + } + return router; + } + function dispose() { + if (unlistenHistory) { + unlistenHistory(); + } + if (removePageHideEventListener) { + removePageHideEventListener(); + } + subscribers.clear(); + pendingNavigationController && pendingNavigationController.abort(); + state.fetchers.forEach((_, key) => deleteFetcher(key)); + state.blockers.forEach((_, key) => deleteBlocker(key)); + } + function subscribe(fn) { + subscribers.add(fn); + return () => subscribers.delete(fn); + } + function updateState(newState, opts) { + if (opts === void 0) { + opts = {}; + } + state = _extends2({}, state, newState); + let completedFetchers = []; + let deletedFetchersKeys = []; + if (future.v7_fetcherPersist) { + state.fetchers.forEach((fetcher, key) => { + if (fetcher.state === "idle") { + if (deletedFetchers.has(key)) { + deletedFetchersKeys.push(key); + } else { + completedFetchers.push(key); + } + } + }); + } + [...subscribers].forEach((subscriber) => subscriber(state, { + deletedFetchers: deletedFetchersKeys, + unstable_viewTransitionOpts: opts.viewTransitionOpts, + unstable_flushSync: opts.flushSync === true + })); + if (future.v7_fetcherPersist) { + completedFetchers.forEach((key) => state.fetchers.delete(key)); + deletedFetchersKeys.forEach((key) => deleteFetcher(key)); + } + } + function completeNavigation(location, newState, _temp) { + var _location$state, _location$state2; + let { + flushSync + } = _temp === void 0 ? {} : _temp; + let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true; + let actionData; + if (newState.actionData) { + if (Object.keys(newState.actionData).length > 0) { + actionData = newState.actionData; + } else { + actionData = null; + } + } else if (isActionReload) { + actionData = state.actionData; + } else { + actionData = null; + } + let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData; + let blockers = state.blockers; + if (blockers.size > 0) { + blockers = new Map(blockers); + blockers.forEach((_, k2) => blockers.set(k2, IDLE_BLOCKER)); + } + let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true; + if (inFlightDataRoutes) { + dataRoutes = inFlightDataRoutes; + inFlightDataRoutes = void 0; + } + if (isUninterruptedRevalidation) + ; + else if (pendingAction === Action.Pop) + ; + else if (pendingAction === Action.Push) { + init.history.push(location, location.state); + } else if (pendingAction === Action.Replace) { + init.history.replace(location, location.state); + } + let viewTransitionOpts; + if (pendingAction === Action.Pop) { + let priorPaths = appliedViewTransitions.get(state.location.pathname); + if (priorPaths && priorPaths.has(location.pathname)) { + viewTransitionOpts = { + currentLocation: state.location, + nextLocation: location + }; + } else if (appliedViewTransitions.has(location.pathname)) { + viewTransitionOpts = { + currentLocation: location, + nextLocation: state.location + }; + } + } else if (pendingViewTransitionEnabled) { + let toPaths = appliedViewTransitions.get(state.location.pathname); + if (toPaths) { + toPaths.add(location.pathname); + } else { + toPaths = /* @__PURE__ */ new Set([location.pathname]); + appliedViewTransitions.set(state.location.pathname, toPaths); + } + viewTransitionOpts = { + currentLocation: state.location, + nextLocation: location + }; + } + updateState(_extends2({}, newState, { + // matches, errors, fetchers go through as-is + actionData, + loaderData, + historyAction: pendingAction, + location, + initialized: true, + navigation: IDLE_NAVIGATION, + revalidation: "idle", + restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches), + preventScrollReset, + blockers + }), { + viewTransitionOpts, + flushSync: flushSync === true + }); + pendingAction = Action.Pop; + pendingPreventScrollReset = false; + pendingViewTransitionEnabled = false; + isUninterruptedRevalidation = false; + isRevalidationRequired = false; + cancelledDeferredRoutes = []; + } + async function navigate(to, opts) { + if (typeof to === "number") { + init.history.go(to); + return; + } + let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative); + let { + path, + submission, + error + } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts); + let currentLocation = state.location; + let nextLocation = createLocation(state.location, path, opts && opts.state); + nextLocation = _extends2({}, nextLocation, init.history.encodeLocation(nextLocation)); + let userReplace = opts && opts.replace != null ? opts.replace : void 0; + let historyAction = Action.Push; + if (userReplace === true) { + historyAction = Action.Replace; + } else if (userReplace === false) + ; + else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) { + historyAction = Action.Replace; + } + let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : void 0; + let flushSync = (opts && opts.unstable_flushSync) === true; + let blockerKey = shouldBlockNavigation({ + currentLocation, + nextLocation, + historyAction + }); + if (blockerKey) { + updateBlocker(blockerKey, { + state: "blocked", + location: nextLocation, + proceed() { + updateBlocker(blockerKey, { + state: "proceeding", + proceed: void 0, + reset: void 0, + location: nextLocation + }); + navigate(to, opts); + }, + reset() { + let blockers = new Map(state.blockers); + blockers.set(blockerKey, IDLE_BLOCKER); + updateState({ + blockers + }); + } + }); + return; + } + return await startNavigation(historyAction, nextLocation, { + submission, + // Send through the formData serialization error if we have one so we can + // render at the right error boundary after we match routes + pendingError: error, + preventScrollReset, + replace: opts && opts.replace, + enableViewTransition: opts && opts.unstable_viewTransition, + flushSync + }); + } + function revalidate() { + interruptActiveLoads(); + updateState({ + revalidation: "loading" + }); + if (state.navigation.state === "submitting") { + return; + } + if (state.navigation.state === "idle") { + startNavigation(state.historyAction, state.location, { + startUninterruptedRevalidation: true + }); + return; + } + startNavigation(pendingAction || state.historyAction, state.navigation.location, { + overrideNavigation: state.navigation, + // Proxy through any rending view transition + enableViewTransition: pendingViewTransitionEnabled === true + }); + } + async function startNavigation(historyAction, location, opts) { + pendingNavigationController && pendingNavigationController.abort(); + pendingNavigationController = null; + pendingAction = historyAction; + isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true; + saveScrollPosition(state.location, state.matches); + pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; + pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true; + let routesToUse = inFlightDataRoutes || dataRoutes; + let loadingNavigation = opts && opts.overrideNavigation; + let matches = matchRoutes4(routesToUse, location, basename); + let flushSync = (opts && opts.flushSync) === true; + let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname); + if (fogOfWar.active && fogOfWar.matches) { + matches = fogOfWar.matches; + } + if (!matches) { + let { + error, + notFoundMatches, + route + } = handleNavigational404(location.pathname); + completeNavigation(location, { + matches: notFoundMatches, + loaderData: {}, + errors: { + [route.id]: error + } + }, { + flushSync + }); + return; + } + if (state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) { + completeNavigation(location, { + matches + }, { + flushSync + }); + return; + } + pendingNavigationController = new AbortController(); + let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission); + let pendingActionResult; + if (opts && opts.pendingError) { + pendingActionResult = [findNearestBoundary(matches).route.id, { + type: ResultType.error, + error: opts.pendingError + }]; + } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) { + let actionResult = await handleAction(request, location, opts.submission, matches, fogOfWar.active, { + replace: opts.replace, + flushSync + }); + if (actionResult.shortCircuited) { + return; + } + if (actionResult.pendingActionResult) { + let [routeId, result] = actionResult.pendingActionResult; + if (isErrorResult(result) && isRouteErrorResponse3(result.error) && result.error.status === 404) { + pendingNavigationController = null; + completeNavigation(location, { + matches: actionResult.matches, + loaderData: {}, + errors: { + [routeId]: result.error + } + }); + return; + } + } + matches = actionResult.matches || matches; + pendingActionResult = actionResult.pendingActionResult; + loadingNavigation = getLoadingNavigation(location, opts.submission); + flushSync = false; + fogOfWar.active = false; + request = createClientSideRequest(init.history, request.url, request.signal); + } + let { + shortCircuited, + matches: updatedMatches, + loaderData, + errors + } = await handleLoaders(request, location, matches, fogOfWar.active, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult); + if (shortCircuited) { + return; + } + pendingNavigationController = null; + completeNavigation(location, _extends2({ + matches: updatedMatches || matches + }, getActionDataForCommit(pendingActionResult), { + loaderData, + errors + })); + } + async function handleAction(request, location, submission, matches, isFogOfWar, opts) { + if (opts === void 0) { + opts = {}; + } + interruptActiveLoads(); + let navigation = getSubmittingNavigation(location, submission); + updateState({ + navigation + }, { + flushSync: opts.flushSync === true + }); + if (isFogOfWar) { + let discoverResult = await discoverRoutes(matches, location.pathname, request.signal); + if (discoverResult.type === "aborted") { + return { + shortCircuited: true + }; + } else if (discoverResult.type === "error") { + let { + boundaryId, + error + } = handleDiscoverRouteError(location.pathname, discoverResult); + return { + matches: discoverResult.partialMatches, + pendingActionResult: [boundaryId, { + type: ResultType.error, + error + }] + }; + } else if (!discoverResult.matches) { + let { + notFoundMatches, + error, + route + } = handleNavigational404(location.pathname); + return { + matches: notFoundMatches, + pendingActionResult: [route.id, { + type: ResultType.error, + error + }] + }; + } else { + matches = discoverResult.matches; + } + } + let result; + let actionMatch = getTargetMatch(matches, location); + if (!actionMatch.route.action && !actionMatch.route.lazy) { + result = { + type: ResultType.error, + error: getInternalRouterError(405, { + method: request.method, + pathname: location.pathname, + routeId: actionMatch.route.id + }) + }; + } else { + let results = await callDataStrategy("action", state, request, [actionMatch], matches, null); + result = results[actionMatch.route.id]; + if (request.signal.aborted) { + return { + shortCircuited: true + }; + } + } + if (isRedirectResult(result)) { + let replace2; + if (opts && opts.replace != null) { + replace2 = opts.replace; + } else { + let location2 = normalizeRedirectLocation(result.response.headers.get("Location"), new URL(request.url), basename); + replace2 = location2 === state.location.pathname + state.location.search; + } + await startRedirectNavigation(request, result, true, { + submission, + replace: replace2 + }); + return { + shortCircuited: true + }; + } + if (isDeferredResult(result)) { + throw getInternalRouterError(400, { + type: "defer-action" + }); + } + if (isErrorResult(result)) { + let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); + if ((opts && opts.replace) !== true) { + pendingAction = Action.Push; + } + return { + matches, + pendingActionResult: [boundaryMatch.route.id, result] + }; + } + return { + matches, + pendingActionResult: [actionMatch.route.id, result] + }; + } + async function handleLoaders(request, location, matches, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace2, initialHydration, flushSync, pendingActionResult) { + let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission); + let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation); + let shouldUpdateNavigationState = !isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration); + if (isFogOfWar) { + if (shouldUpdateNavigationState) { + let actionData = getUpdatedActionData(pendingActionResult); + updateState(_extends2({ + navigation: loadingNavigation + }, actionData !== void 0 ? { + actionData + } : {}), { + flushSync + }); + } + let discoverResult = await discoverRoutes(matches, location.pathname, request.signal); + if (discoverResult.type === "aborted") { + return { + shortCircuited: true + }; + } else if (discoverResult.type === "error") { + let { + boundaryId, + error + } = handleDiscoverRouteError(location.pathname, discoverResult); + return { + matches: discoverResult.partialMatches, + loaderData: {}, + errors: { + [boundaryId]: error + } + }; + } else if (!discoverResult.matches) { + let { + error, + notFoundMatches, + route + } = handleNavigational404(location.pathname); + return { + matches: notFoundMatches, + loaderData: {}, + errors: { + [route.id]: error + } + }; + } else { + matches = discoverResult.matches; + } + } + let routesToUse = inFlightDataRoutes || dataRoutes; + let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult); + cancelActiveDeferreds((routeId) => !(matches && matches.some((m) => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId)); + pendingNavigationLoadId = ++incrementingLoadId; + if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) { + let updatedFetchers2 = markFetchRedirectsDone(); + completeNavigation(location, _extends2({ + matches, + loaderData: {}, + // Commit pending error if we're short circuiting + errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { + [pendingActionResult[0]]: pendingActionResult[1].error + } : null + }, getActionDataForCommit(pendingActionResult), updatedFetchers2 ? { + fetchers: new Map(state.fetchers) + } : {}), { + flushSync + }); + return { + shortCircuited: true + }; + } + if (shouldUpdateNavigationState) { + let updates = {}; + if (!isFogOfWar) { + updates.navigation = loadingNavigation; + let actionData = getUpdatedActionData(pendingActionResult); + if (actionData !== void 0) { + updates.actionData = actionData; + } + } + if (revalidatingFetchers.length > 0) { + updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers); + } + updateState(updates, { + flushSync + }); + } + revalidatingFetchers.forEach((rf) => { + if (fetchControllers.has(rf.key)) { + abortFetcher(rf.key); + } + if (rf.controller) { + fetchControllers.set(rf.key, rf.controller); + } + }); + let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((f) => abortFetcher(f.key)); + if (pendingNavigationController) { + pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations); + } + let { + loaderResults, + fetcherResults + } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, request); + if (request.signal.aborted) { + return { + shortCircuited: true + }; + } + if (pendingNavigationController) { + pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations); + } + revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key)); + let redirect3 = findRedirect(loaderResults); + if (redirect3) { + await startRedirectNavigation(request, redirect3.result, true, { + replace: replace2 + }); + return { + shortCircuited: true + }; + } + redirect3 = findRedirect(fetcherResults); + if (redirect3) { + fetchRedirectIds.add(redirect3.key); + await startRedirectNavigation(request, redirect3.result, true, { + replace: replace2 + }); + return { + shortCircuited: true + }; + } + let { + loaderData, + errors + } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds); + activeDeferreds.forEach((deferredData, routeId) => { + deferredData.subscribe((aborted) => { + if (aborted || deferredData.done) { + activeDeferreds.delete(routeId); + } + }); + }); + if (future.v7_partialHydration && initialHydration && state.errors) { + Object.entries(state.errors).filter((_ref2) => { + let [id] = _ref2; + return !matchesToLoad.some((m) => m.route.id === id); + }).forEach((_ref3) => { + let [routeId, error] = _ref3; + errors = Object.assign(errors || {}, { + [routeId]: error + }); + }); + } + let updatedFetchers = markFetchRedirectsDone(); + let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId); + let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0; + return _extends2({ + matches, + loaderData, + errors + }, shouldUpdateFetchers ? { + fetchers: new Map(state.fetchers) + } : {}); + } + function getUpdatedActionData(pendingActionResult) { + if (pendingActionResult && !isErrorResult(pendingActionResult[1])) { + return { + [pendingActionResult[0]]: pendingActionResult[1].data + }; + } else if (state.actionData) { + if (Object.keys(state.actionData).length === 0) { + return null; + } else { + return state.actionData; + } + } + } + function getUpdatedRevalidatingFetchers(revalidatingFetchers) { + revalidatingFetchers.forEach((rf) => { + let fetcher = state.fetchers.get(rf.key); + let revalidatingFetcher = getLoadingFetcher(void 0, fetcher ? fetcher.data : void 0); + state.fetchers.set(rf.key, revalidatingFetcher); + }); + return new Map(state.fetchers); + } + function fetch2(key, routeId, href, opts) { + if (isServer) { + throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback."); + } + if (fetchControllers.has(key)) + abortFetcher(key); + let flushSync = (opts && opts.unstable_flushSync) === true; + let routesToUse = inFlightDataRoutes || dataRoutes; + let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative); + let matches = matchRoutes4(routesToUse, normalizedPath, basename); + let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath); + if (fogOfWar.active && fogOfWar.matches) { + matches = fogOfWar.matches; + } + if (!matches) { + setFetcherError(key, routeId, getInternalRouterError(404, { + pathname: normalizedPath + }), { + flushSync + }); + return; + } + let { + path, + submission, + error + } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts); + if (error) { + setFetcherError(key, routeId, error, { + flushSync + }); + return; + } + let match = getTargetMatch(matches, path); + pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; + if (submission && isMutationMethod(submission.formMethod)) { + handleFetcherAction(key, routeId, path, match, matches, fogOfWar.active, flushSync, submission); + return; + } + fetchLoadMatches.set(key, { + routeId, + path + }); + handleFetcherLoader(key, routeId, path, match, matches, fogOfWar.active, flushSync, submission); + } + async function handleFetcherAction(key, routeId, path, match, requestMatches, isFogOfWar, flushSync, submission) { + interruptActiveLoads(); + fetchLoadMatches.delete(key); + function detectAndHandle405Error(m) { + if (!m.route.action && !m.route.lazy) { + let error = getInternalRouterError(405, { + method: submission.formMethod, + pathname: path, + routeId + }); + setFetcherError(key, routeId, error, { + flushSync + }); + return true; + } + return false; + } + if (!isFogOfWar && detectAndHandle405Error(match)) { + return; + } + let existingFetcher = state.fetchers.get(key); + updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), { + flushSync + }); + let abortController = new AbortController(); + let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission); + if (isFogOfWar) { + let discoverResult = await discoverRoutes(requestMatches, path, fetchRequest.signal); + if (discoverResult.type === "aborted") { + return; + } else if (discoverResult.type === "error") { + let { + error + } = handleDiscoverRouteError(path, discoverResult); + setFetcherError(key, routeId, error, { + flushSync + }); + return; + } else if (!discoverResult.matches) { + setFetcherError(key, routeId, getInternalRouterError(404, { + pathname: path + }), { + flushSync + }); + return; + } else { + requestMatches = discoverResult.matches; + match = getTargetMatch(requestMatches, path); + if (detectAndHandle405Error(match)) { + return; + } + } + } + fetchControllers.set(key, abortController); + let originatingLoadId = incrementingLoadId; + let actionResults = await callDataStrategy("action", state, fetchRequest, [match], requestMatches, key); + let actionResult = actionResults[match.route.id]; + if (fetchRequest.signal.aborted) { + if (fetchControllers.get(key) === abortController) { + fetchControllers.delete(key); + } + return; + } + if (future.v7_fetcherPersist && deletedFetchers.has(key)) { + if (isRedirectResult(actionResult) || isErrorResult(actionResult)) { + updateFetcherState(key, getDoneFetcher(void 0)); + return; + } + } else { + if (isRedirectResult(actionResult)) { + fetchControllers.delete(key); + if (pendingNavigationLoadId > originatingLoadId) { + updateFetcherState(key, getDoneFetcher(void 0)); + return; + } else { + fetchRedirectIds.add(key); + updateFetcherState(key, getLoadingFetcher(submission)); + return startRedirectNavigation(fetchRequest, actionResult, false, { + fetcherSubmission: submission + }); + } + } + if (isErrorResult(actionResult)) { + setFetcherError(key, routeId, actionResult.error); + return; + } + } + if (isDeferredResult(actionResult)) { + throw getInternalRouterError(400, { + type: "defer-action" + }); + } + let nextLocation = state.navigation.location || state.location; + let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal); + let routesToUse = inFlightDataRoutes || dataRoutes; + let matches = state.navigation.state !== "idle" ? matchRoutes4(routesToUse, state.navigation.location, basename) : state.matches; + invariant2(matches, "Didn't find any matches after fetcher action"); + let loadId = ++incrementingLoadId; + fetchReloadIds.set(key, loadId); + let loadFetcher = getLoadingFetcher(submission, actionResult.data); + state.fetchers.set(key, loadFetcher); + let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, false, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, [match.route.id, actionResult]); + revalidatingFetchers.filter((rf) => rf.key !== key).forEach((rf) => { + let staleKey = rf.key; + let existingFetcher2 = state.fetchers.get(staleKey); + let revalidatingFetcher = getLoadingFetcher(void 0, existingFetcher2 ? existingFetcher2.data : void 0); + state.fetchers.set(staleKey, revalidatingFetcher); + if (fetchControllers.has(staleKey)) { + abortFetcher(staleKey); + } + if (rf.controller) { + fetchControllers.set(staleKey, rf.controller); + } + }); + updateState({ + fetchers: new Map(state.fetchers) + }); + let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach((rf) => abortFetcher(rf.key)); + abortController.signal.addEventListener("abort", abortPendingFetchRevalidations); + let { + loaderResults, + fetcherResults + } = await callLoadersAndMaybeResolveData(state, matches, matchesToLoad, revalidatingFetchers, revalidationRequest); + if (abortController.signal.aborted) { + return; + } + abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations); + fetchReloadIds.delete(key); + fetchControllers.delete(key); + revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key)); + let redirect3 = findRedirect(loaderResults); + if (redirect3) { + return startRedirectNavigation(revalidationRequest, redirect3.result, false); + } + redirect3 = findRedirect(fetcherResults); + if (redirect3) { + fetchRedirectIds.add(redirect3.key); + return startRedirectNavigation(revalidationRequest, redirect3.result, false); + } + let { + loaderData, + errors + } = processLoaderData(state, matches, matchesToLoad, loaderResults, void 0, revalidatingFetchers, fetcherResults, activeDeferreds); + if (state.fetchers.has(key)) { + let doneFetcher = getDoneFetcher(actionResult.data); + state.fetchers.set(key, doneFetcher); + } + abortStaleFetchLoads(loadId); + if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) { + invariant2(pendingAction, "Expected pending action"); + pendingNavigationController && pendingNavigationController.abort(); + completeNavigation(state.navigation.location, { + matches, + loaderData, + errors, + fetchers: new Map(state.fetchers) + }); + } else { + updateState({ + errors, + loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors), + fetchers: new Map(state.fetchers) + }); + isRevalidationRequired = false; + } + } + async function handleFetcherLoader(key, routeId, path, match, matches, isFogOfWar, flushSync, submission) { + let existingFetcher = state.fetchers.get(key); + updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : void 0), { + flushSync + }); + let abortController = new AbortController(); + let fetchRequest = createClientSideRequest(init.history, path, abortController.signal); + if (isFogOfWar) { + let discoverResult = await discoverRoutes(matches, path, fetchRequest.signal); + if (discoverResult.type === "aborted") { + return; + } else if (discoverResult.type === "error") { + let { + error + } = handleDiscoverRouteError(path, discoverResult); + setFetcherError(key, routeId, error, { + flushSync + }); + return; + } else if (!discoverResult.matches) { + setFetcherError(key, routeId, getInternalRouterError(404, { + pathname: path + }), { + flushSync + }); + return; + } else { + matches = discoverResult.matches; + match = getTargetMatch(matches, path); + } + } + fetchControllers.set(key, abortController); + let originatingLoadId = incrementingLoadId; + let results = await callDataStrategy("loader", state, fetchRequest, [match], matches, key); + let result = results[match.route.id]; + if (isDeferredResult(result)) { + result = await resolveDeferredData(result, fetchRequest.signal, true) || result; + } + if (fetchControllers.get(key) === abortController) { + fetchControllers.delete(key); + } + if (fetchRequest.signal.aborted) { + return; + } + if (deletedFetchers.has(key)) { + updateFetcherState(key, getDoneFetcher(void 0)); + return; + } + if (isRedirectResult(result)) { + if (pendingNavigationLoadId > originatingLoadId) { + updateFetcherState(key, getDoneFetcher(void 0)); + return; + } else { + fetchRedirectIds.add(key); + await startRedirectNavigation(fetchRequest, result, false); + return; + } + } + if (isErrorResult(result)) { + setFetcherError(key, routeId, result.error); + return; + } + invariant2(!isDeferredResult(result), "Unhandled fetcher deferred data"); + updateFetcherState(key, getDoneFetcher(result.data)); + } + async function startRedirectNavigation(request, redirect3, isNavigation, _temp2) { + let { + submission, + fetcherSubmission, + replace: replace2 + } = _temp2 === void 0 ? {} : _temp2; + if (redirect3.response.headers.has("X-Remix-Revalidate")) { + isRevalidationRequired = true; + } + let location = redirect3.response.headers.get("Location"); + invariant2(location, "Expected a Location header on the redirect Response"); + location = normalizeRedirectLocation(location, new URL(request.url), basename); + let redirectLocation = createLocation(state.location, location, { + _isRedirect: true + }); + if (isBrowser) { + let isDocumentReload = false; + if (redirect3.response.headers.has("X-Remix-Reload-Document")) { + isDocumentReload = true; + } else if (ABSOLUTE_URL_REGEX2.test(location)) { + const url = init.history.createURL(location); + isDocumentReload = // Hard reload if it's an absolute URL to a new origin + url.origin !== routerWindow.location.origin || // Hard reload if it's an absolute URL that does not match our basename + stripBasename(url.pathname, basename) == null; + } + if (isDocumentReload) { + if (replace2) { + routerWindow.location.replace(location); + } else { + routerWindow.location.assign(location); + } + return; + } + } + pendingNavigationController = null; + let redirectHistoryAction = replace2 === true || redirect3.response.headers.has("X-Remix-Replace") ? Action.Replace : Action.Push; + let { + formMethod, + formAction, + formEncType + } = state.navigation; + if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) { + submission = getSubmissionFromNavigation(state.navigation); + } + let activeSubmission = submission || fetcherSubmission; + if (redirectPreserveMethodStatusCodes.has(redirect3.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) { + await startNavigation(redirectHistoryAction, redirectLocation, { + submission: _extends2({}, activeSubmission, { + formAction: location + }), + // Preserve these flags across redirects + preventScrollReset: pendingPreventScrollReset, + enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0 + }); + } else { + let overrideNavigation = getLoadingNavigation(redirectLocation, submission); + await startNavigation(redirectHistoryAction, redirectLocation, { + overrideNavigation, + // Send fetcher submissions through for shouldRevalidate + fetcherSubmission, + // Preserve these flags across redirects + preventScrollReset: pendingPreventScrollReset, + enableViewTransition: isNavigation ? pendingViewTransitionEnabled : void 0 + }); + } + } + async function callDataStrategy(type, state2, request, matchesToLoad, matches, fetcherKey) { + let results; + let dataResults = {}; + try { + results = await callDataStrategyImpl(dataStrategyImpl, type, state2, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties); + } catch (e2) { + matchesToLoad.forEach((m) => { + dataResults[m.route.id] = { + type: ResultType.error, + error: e2 + }; + }); + return dataResults; + } + for (let [routeId, result] of Object.entries(results)) { + if (isRedirectDataStrategyResultResult(result)) { + let response = result.result; + dataResults[routeId] = { + type: ResultType.redirect, + response: normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, future.v7_relativeSplatPath) + }; + } else { + dataResults[routeId] = await convertDataStrategyResultToDataResult(result); + } + } + return dataResults; + } + async function callLoadersAndMaybeResolveData(state2, matches, matchesToLoad, fetchersToLoad, request) { + let currentMatches = state2.matches; + let loaderResultsPromise = callDataStrategy("loader", state2, request, matchesToLoad, matches, null); + let fetcherResultsPromise = Promise.all(fetchersToLoad.map(async (f) => { + if (f.matches && f.match && f.controller) { + let results = await callDataStrategy("loader", state2, createClientSideRequest(init.history, f.path, f.controller.signal), [f.match], f.matches, f.key); + let result = results[f.match.route.id]; + return { + [f.key]: result + }; + } else { + return Promise.resolve({ + [f.key]: { + type: ResultType.error, + error: getInternalRouterError(404, { + pathname: f.path + }) + } + }); + } + })); + let loaderResults = await loaderResultsPromise; + let fetcherResults = (await fetcherResultsPromise).reduce((acc, r) => Object.assign(acc, r), {}); + await Promise.all([resolveNavigationDeferredResults(matches, loaderResults, request.signal, currentMatches, state2.loaderData), resolveFetcherDeferredResults(matches, fetcherResults, fetchersToLoad)]); + return { + loaderResults, + fetcherResults + }; + } + function interruptActiveLoads() { + isRevalidationRequired = true; + cancelledDeferredRoutes.push(...cancelActiveDeferreds()); + fetchLoadMatches.forEach((_, key) => { + if (fetchControllers.has(key)) { + cancelledFetcherLoads.add(key); + abortFetcher(key); + } + }); + } + function updateFetcherState(key, fetcher, opts) { + if (opts === void 0) { + opts = {}; + } + state.fetchers.set(key, fetcher); + updateState({ + fetchers: new Map(state.fetchers) + }, { + flushSync: (opts && opts.flushSync) === true + }); + } + function setFetcherError(key, routeId, error, opts) { + if (opts === void 0) { + opts = {}; + } + let boundaryMatch = findNearestBoundary(state.matches, routeId); + deleteFetcher(key); + updateState({ + errors: { + [boundaryMatch.route.id]: error + }, + fetchers: new Map(state.fetchers) + }, { + flushSync: (opts && opts.flushSync) === true + }); + } + function getFetcher(key) { + if (future.v7_fetcherPersist) { + activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1); + if (deletedFetchers.has(key)) { + deletedFetchers.delete(key); + } + } + return state.fetchers.get(key) || IDLE_FETCHER; + } + function deleteFetcher(key) { + let fetcher = state.fetchers.get(key); + if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) { + abortFetcher(key); + } + fetchLoadMatches.delete(key); + fetchReloadIds.delete(key); + fetchRedirectIds.delete(key); + deletedFetchers.delete(key); + cancelledFetcherLoads.delete(key); + state.fetchers.delete(key); + } + function deleteFetcherAndUpdateState(key) { + if (future.v7_fetcherPersist) { + let count = (activeFetchers.get(key) || 0) - 1; + if (count <= 0) { + activeFetchers.delete(key); + deletedFetchers.add(key); + } else { + activeFetchers.set(key, count); + } + } else { + deleteFetcher(key); + } + updateState({ + fetchers: new Map(state.fetchers) + }); + } + function abortFetcher(key) { + let controller = fetchControllers.get(key); + invariant2(controller, "Expected fetch controller: " + key); + controller.abort(); + fetchControllers.delete(key); + } + function markFetchersDone(keys) { + for (let key of keys) { + let fetcher = getFetcher(key); + let doneFetcher = getDoneFetcher(fetcher.data); + state.fetchers.set(key, doneFetcher); + } + } + function markFetchRedirectsDone() { + let doneKeys = []; + let updatedFetchers = false; + for (let key of fetchRedirectIds) { + let fetcher = state.fetchers.get(key); + invariant2(fetcher, "Expected fetcher: " + key); + if (fetcher.state === "loading") { + fetchRedirectIds.delete(key); + doneKeys.push(key); + updatedFetchers = true; + } + } + markFetchersDone(doneKeys); + return updatedFetchers; + } + function abortStaleFetchLoads(landedId) { + let yeetedKeys = []; + for (let [key, id] of fetchReloadIds) { + if (id < landedId) { + let fetcher = state.fetchers.get(key); + invariant2(fetcher, "Expected fetcher: " + key); + if (fetcher.state === "loading") { + abortFetcher(key); + fetchReloadIds.delete(key); + yeetedKeys.push(key); + } + } + } + markFetchersDone(yeetedKeys); + return yeetedKeys.length > 0; + } + function getBlocker(key, fn) { + let blocker = state.blockers.get(key) || IDLE_BLOCKER; + if (blockerFunctions.get(key) !== fn) { + blockerFunctions.set(key, fn); + } + return blocker; + } + function deleteBlocker(key) { + state.blockers.delete(key); + blockerFunctions.delete(key); + } + function updateBlocker(key, newBlocker) { + let blocker = state.blockers.get(key) || IDLE_BLOCKER; + invariant2(blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked", "Invalid blocker state transition: " + blocker.state + " -> " + newBlocker.state); + let blockers = new Map(state.blockers); + blockers.set(key, newBlocker); + updateState({ + blockers + }); + } + function shouldBlockNavigation(_ref4) { + let { + currentLocation, + nextLocation, + historyAction + } = _ref4; + if (blockerFunctions.size === 0) { + return; + } + if (blockerFunctions.size > 1) { + warning(false, "A router only supports one blocker at a time"); + } + let entries = Array.from(blockerFunctions.entries()); + let [blockerKey, blockerFunction] = entries[entries.length - 1]; + let blocker = state.blockers.get(blockerKey); + if (blocker && blocker.state === "proceeding") { + return; + } + if (blockerFunction({ + currentLocation, + nextLocation, + historyAction + })) { + return blockerKey; + } + } + function handleNavigational404(pathname) { + let error = getInternalRouterError(404, { + pathname + }); + let routesToUse = inFlightDataRoutes || dataRoutes; + let { + matches, + route + } = getShortCircuitMatches(routesToUse); + cancelActiveDeferreds(); + return { + notFoundMatches: matches, + route, + error + }; + } + function handleDiscoverRouteError(pathname, discoverResult) { + return { + boundaryId: findNearestBoundary(discoverResult.partialMatches).route.id, + error: getInternalRouterError(400, { + type: "route-discovery", + pathname, + message: discoverResult.error != null && "message" in discoverResult.error ? discoverResult.error : String(discoverResult.error) + }) + }; + } + function cancelActiveDeferreds(predicate) { + let cancelledRouteIds = []; + activeDeferreds.forEach((dfd, routeId) => { + if (!predicate || predicate(routeId)) { + dfd.cancel(); + cancelledRouteIds.push(routeId); + activeDeferreds.delete(routeId); + } + }); + return cancelledRouteIds; + } + function enableScrollRestoration(positions, getPosition, getKey) { + savedScrollPositions = positions; + getScrollPosition = getPosition; + getScrollRestorationKey = getKey || null; + if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) { + initialScrollRestored = true; + let y2 = getSavedScrollPosition(state.location, state.matches); + if (y2 != null) { + updateState({ + restoreScrollPosition: y2 + }); + } + } + return () => { + savedScrollPositions = null; + getScrollPosition = null; + getScrollRestorationKey = null; + }; + } + function getScrollKey(location, matches) { + if (getScrollRestorationKey) { + let key = getScrollRestorationKey(location, matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))); + return key || location.key; + } + return location.key; + } + function saveScrollPosition(location, matches) { + if (savedScrollPositions && getScrollPosition) { + let key = getScrollKey(location, matches); + savedScrollPositions[key] = getScrollPosition(); + } + } + function getSavedScrollPosition(location, matches) { + if (savedScrollPositions) { + let key = getScrollKey(location, matches); + let y2 = savedScrollPositions[key]; + if (typeof y2 === "number") { + return y2; + } + } + return null; + } + function checkFogOfWar(matches, routesToUse, pathname) { + if (patchRoutesOnNavigationImpl) { + if (discoveredRoutes.has(pathname)) { + return { + active: false, + matches + }; + } + if (!matches) { + let fogMatches = matchRoutesImpl(routesToUse, pathname, basename, true); + return { + active: true, + matches: fogMatches || [] + }; + } else { + if (Object.keys(matches[0].params).length > 0) { + let partialMatches = matchRoutesImpl(routesToUse, pathname, basename, true); + return { + active: true, + matches: partialMatches + }; + } + } + } + return { + active: false, + matches: null + }; + } + async function discoverRoutes(matches, pathname, signal) { + let partialMatches = matches; + while (true) { + let isNonHMR = inFlightDataRoutes == null; + let routesToUse = inFlightDataRoutes || dataRoutes; + try { + await loadLazyRouteChildren(patchRoutesOnNavigationImpl, pathname, partialMatches, routesToUse, manifest, mapRouteProperties, pendingPatchRoutes, signal); + } catch (e2) { + return { + type: "error", + error: e2, + partialMatches + }; + } finally { + if (isNonHMR) { + dataRoutes = [...dataRoutes]; + } + } + if (signal.aborted) { + return { + type: "aborted" + }; + } + let newMatches = matchRoutes4(routesToUse, pathname, basename); + if (newMatches) { + addToFifoQueue(pathname, discoveredRoutes); + return { + type: "success", + matches: newMatches + }; + } + let newPartialMatches = matchRoutesImpl(routesToUse, pathname, basename, true); + if (!newPartialMatches || partialMatches.length === newPartialMatches.length && partialMatches.every((m, i2) => m.route.id === newPartialMatches[i2].route.id)) { + addToFifoQueue(pathname, discoveredRoutes); + return { + type: "success", + matches: null + }; + } + partialMatches = newPartialMatches; + } + } + function addToFifoQueue(path, queue) { + if (queue.size >= discoveredRoutesMaxSize) { + let first = queue.values().next().value; + queue.delete(first); + } + queue.add(path); + } + function _internalSetRoutes(newRoutes) { + manifest = {}; + inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, void 0, manifest); + } + function patchRoutes(routeId, children) { + let isNonHMR = inFlightDataRoutes == null; + let routesToUse = inFlightDataRoutes || dataRoutes; + patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties); + if (isNonHMR) { + dataRoutes = [...dataRoutes]; + updateState({}); + } + } + router = { + get basename() { + return basename; + }, + get future() { + return future; + }, + get state() { + return state; + }, + get routes() { + return dataRoutes; + }, + get window() { + return routerWindow; + }, + initialize, + subscribe, + enableScrollRestoration, + navigate, + fetch: fetch2, + revalidate, + // Passthrough to history-aware createHref used by useHref so we get proper + // hash-aware URLs in DOM paths + createHref: (to) => init.history.createHref(to), + encodeLocation: (to) => init.history.encodeLocation(to), + getFetcher, + deleteFetcher: deleteFetcherAndUpdateState, + dispose, + getBlocker, + deleteBlocker, + patchRoutes, + _internalFetchControllers: fetchControllers, + _internalActiveDeferreds: activeDeferreds, + // TODO: Remove setRoutes, it's temporary to avoid dealing with + // updating the tree while validating the update algorithm. + _internalSetRoutes + }; + return router; + } + var UNSAFE_DEFERRED_SYMBOL = Symbol("deferred"); + function createStaticHandler(routes, opts) { + invariant2(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler"); + let manifest = {}; + let basename = (opts ? opts.basename : null) || "/"; + let mapRouteProperties; + if (opts != null && opts.mapRouteProperties) { + mapRouteProperties = opts.mapRouteProperties; + } else if (opts != null && opts.detectErrorBoundary) { + let detectErrorBoundary = opts.detectErrorBoundary; + mapRouteProperties = (route) => ({ + hasErrorBoundary: detectErrorBoundary(route) + }); + } else { + mapRouteProperties = defaultMapRouteProperties; + } + let future = _extends2({ + v7_relativeSplatPath: false, + v7_throwAbortReason: false + }, opts ? opts.future : null); + let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, void 0, manifest); + async function query(request, _temp3) { + let { + requestContext, + skipLoaderErrorBubbling, + unstable_dataStrategy + } = _temp3 === void 0 ? {} : _temp3; + let url = new URL(request.url); + let method = request.method; + let location = createLocation("", createPath2(url), null, "default"); + let matches = matchRoutes4(dataRoutes, location, basename); + if (!isValidMethod(method) && method !== "HEAD") { + let error = getInternalRouterError(405, { + method + }); + let { + matches: methodNotAllowedMatches, + route + } = getShortCircuitMatches(dataRoutes); + return { + basename, + location, + matches: methodNotAllowedMatches, + loaderData: {}, + actionData: null, + errors: { + [route.id]: error + }, + statusCode: error.status, + loaderHeaders: {}, + actionHeaders: {}, + activeDeferreds: null + }; + } else if (!matches) { + let error = getInternalRouterError(404, { + pathname: location.pathname + }); + let { + matches: notFoundMatches, + route + } = getShortCircuitMatches(dataRoutes); + return { + basename, + location, + matches: notFoundMatches, + loaderData: {}, + actionData: null, + errors: { + [route.id]: error + }, + statusCode: error.status, + loaderHeaders: {}, + actionHeaders: {}, + activeDeferreds: null + }; + } + let result = await queryImpl(request, location, matches, requestContext, unstable_dataStrategy || null, skipLoaderErrorBubbling === true, null); + if (isResponse(result)) { + return result; + } + return _extends2({ + location, + basename + }, result); + } + async function queryRoute(request, _temp4) { + let { + routeId, + requestContext, + unstable_dataStrategy + } = _temp4 === void 0 ? {} : _temp4; + let url = new URL(request.url); + let method = request.method; + let location = createLocation("", createPath2(url), null, "default"); + let matches = matchRoutes4(dataRoutes, location, basename); + if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") { + throw getInternalRouterError(405, { + method + }); + } else if (!matches) { + throw getInternalRouterError(404, { + pathname: location.pathname + }); + } + let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location); + if (routeId && !match) { + throw getInternalRouterError(403, { + pathname: location.pathname, + routeId + }); + } else if (!match) { + throw getInternalRouterError(404, { + pathname: location.pathname + }); + } + let result = await queryImpl(request, location, matches, requestContext, unstable_dataStrategy || null, false, match); + if (isResponse(result)) { + return result; + } + let error = result.errors ? Object.values(result.errors)[0] : void 0; + if (error !== void 0) { + throw error; + } + if (result.actionData) { + return Object.values(result.actionData)[0]; + } + if (result.loaderData) { + var _result$activeDeferre; + let data2 = Object.values(result.loaderData)[0]; + if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) { + data2[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id]; + } + return data2; + } + return void 0; + } + async function queryImpl(request, location, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch) { + invariant2(request.signal, "query()/queryRoute() requests must contain an AbortController signal"); + try { + if (isMutationMethod(request.method.toLowerCase())) { + let result2 = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch != null); + return result2; + } + let result = await loadRouteData(request, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch); + return isResponse(result) ? result : _extends2({}, result, { + actionData: null, + actionHeaders: {} + }); + } catch (e2) { + if (isDataStrategyResult(e2) && isResponse(e2.result)) { + if (e2.type === ResultType.error) { + throw e2.result; + } + return e2.result; + } + if (isRedirectResponse(e2)) { + return e2; + } + throw e2; + } + } + async function submit(request, matches, actionMatch, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, isRouteRequest) { + let result; + if (!actionMatch.route.action && !actionMatch.route.lazy) { + let error = getInternalRouterError(405, { + method: request.method, + pathname: new URL(request.url).pathname, + routeId: actionMatch.route.id + }); + if (isRouteRequest) { + throw error; + } + result = { + type: ResultType.error, + error + }; + } else { + let results = await callDataStrategy("action", request, [actionMatch], matches, isRouteRequest, requestContext, unstable_dataStrategy); + result = results[actionMatch.route.id]; + if (request.signal.aborted) { + throwStaticHandlerAbortedError(request, isRouteRequest, future); + } + } + if (isRedirectResult(result)) { + throw new Response(null, { + status: result.response.status, + headers: { + Location: result.response.headers.get("Location") + } + }); + } + if (isDeferredResult(result)) { + let error = getInternalRouterError(400, { + type: "defer-action" + }); + if (isRouteRequest) { + throw error; + } + result = { + type: ResultType.error, + error + }; + } + if (isRouteRequest) { + if (isErrorResult(result)) { + throw result.error; + } + return { + matches: [actionMatch], + loaderData: {}, + actionData: { + [actionMatch.route.id]: result.data + }, + errors: null, + // Note: statusCode + headers are unused here since queryRoute will + // return the raw Response or value + statusCode: 200, + loaderHeaders: {}, + actionHeaders: {}, + activeDeferreds: null + }; + } + let loaderRequest = new Request(request.url, { + headers: request.headers, + redirect: request.redirect, + signal: request.signal + }); + if (isErrorResult(result)) { + let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id); + let context2 = await loadRouteData(loaderRequest, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, null, [boundaryMatch.route.id, result]); + return _extends2({}, context2, { + statusCode: isRouteErrorResponse3(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500, + actionData: null, + actionHeaders: _extends2({}, result.headers ? { + [actionMatch.route.id]: result.headers + } : {}) + }); + } + let context = await loadRouteData(loaderRequest, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, null); + return _extends2({}, context, { + actionData: { + [actionMatch.route.id]: result.data + } + }, result.statusCode ? { + statusCode: result.statusCode + } : {}, { + actionHeaders: result.headers ? { + [actionMatch.route.id]: result.headers + } : {} + }); + } + async function loadRouteData(request, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) { + let isRouteRequest = routeMatch != null; + if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) { + throw getInternalRouterError(400, { + method: request.method, + pathname: new URL(request.url).pathname, + routeId: routeMatch == null ? void 0 : routeMatch.route.id + }); + } + let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches; + let matchesToLoad = requestMatches.filter((m) => m.route.loader || m.route.lazy); + if (matchesToLoad.length === 0) { + return { + matches, + // Add a null for all matched routes for proper revalidation on the client + loaderData: matches.reduce((acc, m) => Object.assign(acc, { + [m.route.id]: null + }), {}), + errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? { + [pendingActionResult[0]]: pendingActionResult[1].error + } : null, + statusCode: 200, + loaderHeaders: {}, + activeDeferreds: null + }; + } + let results = await callDataStrategy("loader", request, matchesToLoad, matches, isRouteRequest, requestContext, unstable_dataStrategy); + if (request.signal.aborted) { + throwStaticHandlerAbortedError(request, isRouteRequest, future); + } + let activeDeferreds = /* @__PURE__ */ new Map(); + let context = processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling); + let executedLoaders = new Set(matchesToLoad.map((match) => match.route.id)); + matches.forEach((match) => { + if (!executedLoaders.has(match.route.id)) { + context.loaderData[match.route.id] = null; + } + }); + return _extends2({}, context, { + matches, + activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null + }); + } + async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, unstable_dataStrategy) { + let results = await callDataStrategyImpl(unstable_dataStrategy || defaultDataStrategy, type, null, request, matchesToLoad, matches, null, manifest, mapRouteProperties, requestContext); + let dataResults = {}; + await Promise.all(matches.map(async (match) => { + if (!(match.route.id in results)) { + return; + } + let result = results[match.route.id]; + if (isRedirectDataStrategyResultResult(result)) { + let response = result.result; + throw normalizeRelativeRoutingRedirectResponse(response, request, match.route.id, matches, basename, future.v7_relativeSplatPath); + } + if (isResponse(result.result) && isRouteRequest) { + throw result; + } + dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result); + })); + return dataResults; + } + return { + dataRoutes, + query, + queryRoute + }; + } + function getStaticContextFromError(routes, context, error) { + let newContext = _extends2({}, context, { + statusCode: isRouteErrorResponse3(error) ? error.status : 500, + errors: { + [context._deepestRenderedBoundaryId || routes[0].id]: error + } + }); + return newContext; + } + function throwStaticHandlerAbortedError(request, isRouteRequest, future) { + if (future.v7_throwAbortReason && request.signal.reason !== void 0) { + throw request.signal.reason; + } + let method = isRouteRequest ? "queryRoute" : "query"; + throw new Error(method + "() call aborted: " + request.method + " " + request.url); + } + function isSubmissionNavigation(opts) { + return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== void 0); + } + function normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) { + let contextualMatches; + let activeRouteMatch; + if (fromRouteId) { + contextualMatches = []; + for (let match of matches) { + contextualMatches.push(match); + if (match.route.id === fromRouteId) { + activeRouteMatch = match; + break; + } + } + } else { + contextualMatches = matches; + activeRouteMatch = matches[matches.length - 1]; + } + let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === "path"); + if (to == null) { + path.search = location.search; + path.hash = location.hash; + } + if ((to == null || to === "" || to === ".") && activeRouteMatch && activeRouteMatch.route.index && !hasNakedIndexQuery(path.search)) { + path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index"; + } + if (prependBasename && basename !== "/") { + path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]); + } + return createPath2(path); + } + function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) { + if (!opts || !isSubmissionNavigation(opts)) { + return { + path + }; + } + if (opts.formMethod && !isValidMethod(opts.formMethod)) { + return { + path, + error: getInternalRouterError(405, { + method: opts.formMethod + }) + }; + } + let getInvalidBodyError = () => ({ + path, + error: getInternalRouterError(400, { + type: "invalid-body" + }) + }); + let rawFormMethod = opts.formMethod || "get"; + let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase(); + let formAction = stripHashFromPath(path); + if (opts.body !== void 0) { + if (opts.formEncType === "text/plain") { + if (!isMutationMethod(formMethod)) { + return getInvalidBodyError(); + } + let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? ( + // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data + Array.from(opts.body.entries()).reduce((acc, _ref5) => { + let [name, value] = _ref5; + return "" + acc + name + "=" + value + "\n"; + }, "") + ) : String(opts.body); + return { + path, + submission: { + formMethod, + formAction, + formEncType: opts.formEncType, + formData: void 0, + json: void 0, + text + } + }; + } else if (opts.formEncType === "application/json") { + if (!isMutationMethod(formMethod)) { + return getInvalidBodyError(); + } + try { + let json2 = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body; + return { + path, + submission: { + formMethod, + formAction, + formEncType: opts.formEncType, + formData: void 0, + json: json2, + text: void 0 + } + }; + } catch (e2) { + return getInvalidBodyError(); + } + } + } + invariant2(typeof FormData === "function", "FormData is not available in this environment"); + let searchParams; + let formData; + if (opts.formData) { + searchParams = convertFormDataToSearchParams(opts.formData); + formData = opts.formData; + } else if (opts.body instanceof FormData) { + searchParams = convertFormDataToSearchParams(opts.body); + formData = opts.body; + } else if (opts.body instanceof URLSearchParams) { + searchParams = opts.body; + formData = convertSearchParamsToFormData(searchParams); + } else if (opts.body == null) { + searchParams = new URLSearchParams(); + formData = new FormData(); + } else { + try { + searchParams = new URLSearchParams(opts.body); + formData = convertSearchParamsToFormData(searchParams); + } catch (e2) { + return getInvalidBodyError(); + } + } + let submission = { + formMethod, + formAction, + formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded", + formData, + json: void 0, + text: void 0 + }; + if (isMutationMethod(submission.formMethod)) { + return { + path, + submission + }; + } + let parsedPath = parsePath3(path); + if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) { + searchParams.append("index", ""); + } + parsedPath.search = "?" + searchParams; + return { + path: createPath2(parsedPath), + submission + }; + } + function getLoaderMatchesUntilBoundary(matches, boundaryId) { + let boundaryMatches = matches; + if (boundaryId) { + let index = matches.findIndex((m) => m.route.id === boundaryId); + if (index >= 0) { + boundaryMatches = matches.slice(0, index); + } + } + return boundaryMatches; + } + function getMatchesToLoad(history, state, matches, submission, location, isInitialLoad, skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult) { + let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : void 0; + let currentUrl = history.createURL(state.location); + let nextUrl = history.createURL(location); + let boundaryId = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[0] : void 0; + let boundaryMatches = boundaryId ? getLoaderMatchesUntilBoundary(matches, boundaryId) : matches; + let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : void 0; + let shouldSkipRevalidation = skipActionErrorRevalidation && actionStatus && actionStatus >= 400; + let navigationMatches = boundaryMatches.filter((match, index) => { + let { + route + } = match; + if (route.lazy) { + return true; + } + if (route.loader == null) { + return false; + } + if (isInitialLoad) { + if (typeof route.loader !== "function" || route.loader.hydrate) { + return true; + } + return state.loaderData[route.id] === void 0 && // Don't re-run if the loader ran and threw an error + (!state.errors || state.errors[route.id] === void 0); + } + if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some((id) => id === match.route.id)) { + return true; + } + let currentRouteMatch = state.matches[index]; + let nextRouteMatch = match; + return shouldRevalidateLoader(match, _extends2({ + currentUrl, + currentParams: currentRouteMatch.params, + nextUrl, + nextParams: nextRouteMatch.params + }, submission, { + actionResult, + actionStatus, + defaultShouldRevalidate: shouldSkipRevalidation ? false : ( + // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate + isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search || // Search params affect all loaders + currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch) + ) + })); + }); + let revalidatingFetchers = []; + fetchLoadMatches.forEach((f, key) => { + if (isInitialLoad || !matches.some((m) => m.route.id === f.routeId) || deletedFetchers.has(key)) { + return; + } + let fetcherMatches = matchRoutes4(routesToUse, f.path, basename); + if (!fetcherMatches) { + revalidatingFetchers.push({ + key, + routeId: f.routeId, + path: f.path, + matches: null, + match: null, + controller: null + }); + return; + } + let fetcher = state.fetchers.get(key); + let fetcherMatch = getTargetMatch(fetcherMatches, f.path); + let shouldRevalidate = false; + if (fetchRedirectIds.has(key)) { + shouldRevalidate = false; + } else if (cancelledFetcherLoads.has(key)) { + cancelledFetcherLoads.delete(key); + shouldRevalidate = true; + } else if (fetcher && fetcher.state !== "idle" && fetcher.data === void 0) { + shouldRevalidate = isRevalidationRequired; + } else { + shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends2({ + currentUrl, + currentParams: state.matches[state.matches.length - 1].params, + nextUrl, + nextParams: matches[matches.length - 1].params + }, submission, { + actionResult, + actionStatus, + defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired + })); + } + if (shouldRevalidate) { + revalidatingFetchers.push({ + key, + routeId: f.routeId, + path: f.path, + matches: fetcherMatches, + match: fetcherMatch, + controller: new AbortController() + }); + } + }); + return [navigationMatches, revalidatingFetchers]; + } + function isNewLoader(currentLoaderData, currentMatch, match) { + let isNew = ( + // [a] -> [a, b] + !currentMatch || // [a, b] -> [a, c] + match.route.id !== currentMatch.route.id + ); + let isMissingData = currentLoaderData[match.route.id] === void 0; + return isNew || isMissingData; + } + function isNewRouteInstance(currentMatch, match) { + let currentPath = currentMatch.route.path; + return ( + // param change for this match, /users/123 -> /users/456 + currentMatch.pathname !== match.pathname || // splat param changed, which is not present in match.path + // e.g. /files/images/avatar.jpg -> files/finances.xls + currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"] + ); + } + function shouldRevalidateLoader(loaderMatch, arg) { + if (loaderMatch.route.shouldRevalidate) { + let routeChoice = loaderMatch.route.shouldRevalidate(arg); + if (typeof routeChoice === "boolean") { + return routeChoice; + } + } + return arg.defaultShouldRevalidate; + } + async function loadLazyRouteChildren(patchRoutesOnNavigationImpl, path, matches, routes, manifest, mapRouteProperties, pendingRouteChildren, signal) { + let key = [path, ...matches.map((m) => m.route.id)].join("-"); + try { + let pending = pendingRouteChildren.get(key); + if (!pending) { + pending = patchRoutesOnNavigationImpl({ + path, + matches, + patch: (routeId, children) => { + if (!signal.aborted) { + patchRoutesImpl(routeId, children, routes, manifest, mapRouteProperties); + } + } + }); + pendingRouteChildren.set(key, pending); + } + if (pending && isPromise(pending)) { + await pending; + } + } finally { + pendingRouteChildren.delete(key); + } + } + function patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties) { + if (routeId) { + var _route$children; + let route = manifest[routeId]; + invariant2(route, "No route found to patch children into: routeId = " + routeId); + let dataChildren = convertRoutesToDataRoutes(children, mapRouteProperties, [routeId, "patch", String(((_route$children = route.children) == null ? void 0 : _route$children.length) || "0")], manifest); + if (route.children) { + route.children.push(...dataChildren); + } else { + route.children = dataChildren; + } + } else { + let dataChildren = convertRoutesToDataRoutes(children, mapRouteProperties, ["patch", String(routesToUse.length || "0")], manifest); + routesToUse.push(...dataChildren); + } + } + async function loadLazyRouteModule(route, mapRouteProperties, manifest) { + if (!route.lazy) { + return; + } + let lazyRoute = await route.lazy(); + if (!route.lazy) { + return; + } + let routeToUpdate = manifest[route.id]; + invariant2(routeToUpdate, "No route found in manifest"); + let routeUpdates = {}; + for (let lazyRouteProperty in lazyRoute) { + let staticRouteValue = routeToUpdate[lazyRouteProperty]; + let isPropertyStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based + // on the route updates + lazyRouteProperty !== "hasErrorBoundary"; + warning(!isPropertyStaticallyDefined, 'Route "' + routeToUpdate.id + '" has a static property "' + lazyRouteProperty + '" defined but its lazy function is also returning a value for this property. ' + ('The lazy route property "' + lazyRouteProperty + '" will be ignored.')); + if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) { + routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty]; + } + } + Object.assign(routeToUpdate, routeUpdates); + Object.assign(routeToUpdate, _extends2({}, mapRouteProperties(routeToUpdate), { + lazy: void 0 + })); + } + async function defaultDataStrategy(_ref6) { + let { + matches + } = _ref6; + let matchesToLoad = matches.filter((m) => m.shouldLoad); + let results = await Promise.all(matchesToLoad.map((m) => m.resolve())); + return results.reduce((acc, result, i2) => Object.assign(acc, { + [matchesToLoad[i2].route.id]: result + }), {}); + } + async function callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties, requestContext) { + let loadRouteDefinitionsPromises = matches.map((m) => m.route.lazy ? loadLazyRouteModule(m.route, mapRouteProperties, manifest) : void 0); + let dsMatches = matches.map((match, i2) => { + let loadRoutePromise = loadRouteDefinitionsPromises[i2]; + let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id); + let resolve = async (handlerOverride) => { + if (handlerOverride && request.method === "GET" && (match.route.lazy || match.route.loader)) { + shouldLoad = true; + } + return shouldLoad ? callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, requestContext) : Promise.resolve({ + type: ResultType.data, + result: void 0 + }); + }; + return _extends2({}, match, { + shouldLoad, + resolve + }); + }); + let results = await dataStrategyImpl({ + matches: dsMatches, + request, + params: matches[0].params, + fetcherKey, + context: requestContext + }); + try { + await Promise.all(loadRouteDefinitionsPromises); + } catch (e2) { + } + return results; + } + async function callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, staticContext) { + let result; + let onReject; + let runHandler = (handler) => { + let reject; + let abortPromise = new Promise((_, r) => reject = r); + onReject = () => reject(); + request.signal.addEventListener("abort", onReject); + let actualHandler = (ctx) => { + if (typeof handler !== "function") { + return Promise.reject(new Error("You cannot call the handler for a route which defines a boolean " + ('"' + type + '" [routeId: ' + match.route.id + "]"))); + } + return handler({ + request, + params: match.params, + context: staticContext + }, ...ctx !== void 0 ? [ctx] : []); + }; + let handlerPromise = (async () => { + try { + let val = await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler()); + return { + type: "data", + result: val + }; + } catch (e2) { + return { + type: "error", + result: e2 + }; + } + })(); + return Promise.race([handlerPromise, abortPromise]); + }; + try { + let handler = match.route[type]; + if (loadRoutePromise) { + if (handler) { + let handlerError; + let [value] = await Promise.all([ + // If the handler throws, don't let it immediately bubble out, + // since we need to let the lazy() execution finish so we know if this + // route has a boundary that can handle the error + runHandler(handler).catch((e2) => { + handlerError = e2; + }), + loadRoutePromise + ]); + if (handlerError !== void 0) { + throw handlerError; + } + result = value; + } else { + await loadRoutePromise; + handler = match.route[type]; + if (handler) { + result = await runHandler(handler); + } else if (type === "action") { + let url = new URL(request.url); + let pathname = url.pathname + url.search; + throw getInternalRouterError(405, { + method: request.method, + pathname, + routeId: match.route.id + }); + } else { + return { + type: ResultType.data, + result: void 0 + }; + } + } + } else if (!handler) { + let url = new URL(request.url); + let pathname = url.pathname + url.search; + throw getInternalRouterError(404, { + pathname + }); + } else { + result = await runHandler(handler); + } + invariant2(result.result !== void 0, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ('"' + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`."); + } catch (e2) { + return { + type: ResultType.error, + result: e2 + }; + } finally { + if (onReject) { + request.signal.removeEventListener("abort", onReject); + } + } + return result; + } + async function convertDataStrategyResultToDataResult(dataStrategyResult) { + let { + result, + type + } = dataStrategyResult; + if (isResponse(result)) { + let data2; + try { + let contentType = result.headers.get("Content-Type"); + if (contentType && /\bapplication\/json\b/.test(contentType)) { + if (result.body == null) { + data2 = null; + } else { + data2 = await result.json(); + } + } else { + data2 = await result.text(); + } + } catch (e2) { + return { + type: ResultType.error, + error: e2 + }; + } + if (type === ResultType.error) { + return { + type: ResultType.error, + error: new ErrorResponseImpl(result.status, result.statusText, data2), + statusCode: result.status, + headers: result.headers + }; + } + return { + type: ResultType.data, + data: data2, + statusCode: result.status, + headers: result.headers + }; + } + if (type === ResultType.error) { + if (isDataWithResponseInit(result)) { + var _result$init2; + if (result.data instanceof Error) { + var _result$init; + return { + type: ResultType.error, + error: result.data, + statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status + }; + } + result = new ErrorResponseImpl(((_result$init2 = result.init) == null ? void 0 : _result$init2.status) || 500, void 0, result.data); + } + return { + type: ResultType.error, + error: result, + statusCode: isRouteErrorResponse3(result) ? result.status : void 0 + }; + } + if (isDeferredData(result)) { + var _result$init3, _result$init4; + return { + type: ResultType.deferred, + deferredData: result, + statusCode: (_result$init3 = result.init) == null ? void 0 : _result$init3.status, + headers: ((_result$init4 = result.init) == null ? void 0 : _result$init4.headers) && new Headers(result.init.headers) + }; + } + if (isDataWithResponseInit(result)) { + var _result$init5, _result$init6; + return { + type: ResultType.data, + data: result.data, + statusCode: (_result$init5 = result.init) == null ? void 0 : _result$init5.status, + headers: (_result$init6 = result.init) != null && _result$init6.headers ? new Headers(result.init.headers) : void 0 + }; + } + return { + type: ResultType.data, + data: result + }; + } + function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, v7_relativeSplatPath) { + let location = response.headers.get("Location"); + invariant2(location, "Redirects returned/thrown from loaders/actions must have a Location header"); + if (!ABSOLUTE_URL_REGEX2.test(location)) { + let trimmedMatches = matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1); + location = normalizeTo(new URL(request.url), trimmedMatches, basename, true, location, v7_relativeSplatPath); + response.headers.set("Location", location); + } + return response; + } + function normalizeRedirectLocation(location, currentUrl, basename) { + if (ABSOLUTE_URL_REGEX2.test(location)) { + let normalizedLocation = location; + let url = normalizedLocation.startsWith("//") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation); + let isSameBasename = stripBasename(url.pathname, basename) != null; + if (url.origin === currentUrl.origin && isSameBasename) { + return url.pathname + url.search + url.hash; + } + } + return location; + } + function createClientSideRequest(history, location, signal, submission) { + let url = history.createURL(stripHashFromPath(location)).toString(); + let init = { + signal + }; + if (submission && isMutationMethod(submission.formMethod)) { + let { + formMethod, + formEncType + } = submission; + init.method = formMethod.toUpperCase(); + if (formEncType === "application/json") { + init.headers = new Headers({ + "Content-Type": formEncType + }); + init.body = JSON.stringify(submission.json); + } else if (formEncType === "text/plain") { + init.body = submission.text; + } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) { + init.body = convertFormDataToSearchParams(submission.formData); + } else { + init.body = submission.formData; + } + } + return new Request(url, init); + } + function convertFormDataToSearchParams(formData) { + let searchParams = new URLSearchParams(); + for (let [key, value] of formData.entries()) { + searchParams.append(key, typeof value === "string" ? value : value.name); + } + return searchParams; + } + function convertSearchParamsToFormData(searchParams) { + let formData = new FormData(); + for (let [key, value] of searchParams.entries()) { + formData.append(key, value); + } + return formData; + } + function processRouteLoaderData(matches, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling) { + let loaderData = {}; + let errors = null; + let statusCode; + let foundError = false; + let loaderHeaders = {}; + let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0; + matches.forEach((match) => { + if (!(match.route.id in results)) { + return; + } + let id = match.route.id; + let result = results[id]; + invariant2(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData"); + if (isErrorResult(result)) { + let error = result.error; + if (pendingError !== void 0) { + error = pendingError; + pendingError = void 0; + } + errors = errors || {}; + if (skipLoaderErrorBubbling) { + errors[id] = error; + } else { + let boundaryMatch = findNearestBoundary(matches, id); + if (errors[boundaryMatch.route.id] == null) { + errors[boundaryMatch.route.id] = error; + } + } + loaderData[id] = void 0; + if (!foundError) { + foundError = true; + statusCode = isRouteErrorResponse3(result.error) ? result.error.status : 500; + } + if (result.headers) { + loaderHeaders[id] = result.headers; + } + } else { + if (isDeferredResult(result)) { + activeDeferreds.set(id, result.deferredData); + loaderData[id] = result.deferredData.data; + if (result.statusCode != null && result.statusCode !== 200 && !foundError) { + statusCode = result.statusCode; + } + if (result.headers) { + loaderHeaders[id] = result.headers; + } + } else { + loaderData[id] = result.data; + if (result.statusCode && result.statusCode !== 200 && !foundError) { + statusCode = result.statusCode; + } + if (result.headers) { + loaderHeaders[id] = result.headers; + } + } + } + }); + if (pendingError !== void 0 && pendingActionResult) { + errors = { + [pendingActionResult[0]]: pendingError + }; + loaderData[pendingActionResult[0]] = void 0; + } + return { + loaderData, + errors, + statusCode: statusCode || 200, + loaderHeaders + }; + } + function processLoaderData(state, matches, matchesToLoad, results, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds) { + let { + loaderData, + errors + } = processRouteLoaderData( + matches, + results, + pendingActionResult, + activeDeferreds, + false + // This method is only called client side so we always want to bubble + ); + revalidatingFetchers.forEach((rf) => { + let { + key, + match, + controller + } = rf; + let result = fetcherResults[key]; + invariant2(result, "Did not find corresponding fetcher result"); + if (controller && controller.signal.aborted) { + return; + } else if (isErrorResult(result)) { + let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id); + if (!(errors && errors[boundaryMatch.route.id])) { + errors = _extends2({}, errors, { + [boundaryMatch.route.id]: result.error + }); + } + state.fetchers.delete(key); + } else if (isRedirectResult(result)) { + invariant2(false, "Unhandled fetcher revalidation redirect"); + } else if (isDeferredResult(result)) { + invariant2(false, "Unhandled fetcher deferred data"); + } else { + let doneFetcher = getDoneFetcher(result.data); + state.fetchers.set(key, doneFetcher); + } + }); + return { + loaderData, + errors + }; + } + function mergeLoaderData(loaderData, newLoaderData, matches, errors) { + let mergedLoaderData = _extends2({}, newLoaderData); + for (let match of matches) { + let id = match.route.id; + if (newLoaderData.hasOwnProperty(id)) { + if (newLoaderData[id] !== void 0) { + mergedLoaderData[id] = newLoaderData[id]; + } + } else if (loaderData[id] !== void 0 && match.route.loader) { + mergedLoaderData[id] = loaderData[id]; + } + if (errors && errors.hasOwnProperty(id)) { + break; + } + } + return mergedLoaderData; + } + function getActionDataForCommit(pendingActionResult) { + if (!pendingActionResult) { + return {}; + } + return isErrorResult(pendingActionResult[1]) ? { + // Clear out prior actionData on errors + actionData: {} + } : { + actionData: { + [pendingActionResult[0]]: pendingActionResult[1].data + } + }; + } + function findNearestBoundary(matches, routeId) { + let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches]; + return eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || matches[0]; + } + function getShortCircuitMatches(routes) { + let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || { + id: "__shim-error-route__" + }; + return { + matches: [{ + params: {}, + pathname: "", + pathnameBase: "", + route + }], + route + }; + } + function getInternalRouterError(status, _temp5) { + let { + pathname, + routeId, + method, + type, + message + } = _temp5 === void 0 ? {} : _temp5; + let statusText = "Unknown Server Error"; + let errorMessage = "Unknown @remix-run/router error"; + if (status === 400) { + statusText = "Bad Request"; + if (type === "route-discovery") { + errorMessage = 'Unable to match URL "' + pathname + '" - the `unstable_patchRoutesOnNavigation()` ' + ("function threw the following error:\n" + message); + } else if (method && pathname && routeId) { + errorMessage = "You made a " + method + ' request to "' + pathname + '" but ' + ('did not provide a `loader` for route "' + routeId + '", ') + "so there is no way to handle the request."; + } else if (type === "defer-action") { + errorMessage = "defer() is not supported in actions"; + } else if (type === "invalid-body") { + errorMessage = "Unable to encode submission body"; + } + } else if (status === 403) { + statusText = "Forbidden"; + errorMessage = 'Route "' + routeId + '" does not match URL "' + pathname + '"'; + } else if (status === 404) { + statusText = "Not Found"; + errorMessage = 'No route matches URL "' + pathname + '"'; + } else if (status === 405) { + statusText = "Method Not Allowed"; + if (method && pathname && routeId) { + errorMessage = "You made a " + method.toUpperCase() + ' request to "' + pathname + '" but ' + ('did not provide an `action` for route "' + routeId + '", ') + "so there is no way to handle the request."; + } else if (method) { + errorMessage = 'Invalid request method "' + method.toUpperCase() + '"'; + } + } + return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true); + } + function findRedirect(results) { + let entries = Object.entries(results); + for (let i2 = entries.length - 1; i2 >= 0; i2--) { + let [key, result] = entries[i2]; + if (isRedirectResult(result)) { + return { + key, + result + }; + } + } + } + function stripHashFromPath(path) { + let parsedPath = typeof path === "string" ? parsePath3(path) : path; + return createPath2(_extends2({}, parsedPath, { + hash: "" + })); + } + function isHashChangeOnly(a2, b) { + if (a2.pathname !== b.pathname || a2.search !== b.search) { + return false; + } + if (a2.hash === "") { + return b.hash !== ""; + } else if (a2.hash === b.hash) { + return true; + } else if (b.hash !== "") { + return true; + } + return false; + } + function isPromise(val) { + return typeof val === "object" && val != null && "then" in val; + } + function isDataStrategyResult(result) { + return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === ResultType.data || result.type === ResultType.error); + } + function isRedirectDataStrategyResultResult(result) { + return isResponse(result.result) && redirectStatusCodes.has(result.result.status); + } + function isDeferredResult(result) { + return result.type === ResultType.deferred; + } + function isErrorResult(result) { + return result.type === ResultType.error; + } + function isRedirectResult(result) { + return (result && result.type) === ResultType.redirect; + } + function isDataWithResponseInit(value) { + return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit"; + } + function isDeferredData(value) { + let deferred = value; + return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function"; + } + function isResponse(value) { + return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined"; + } + function isRedirectResponse(result) { + if (!isResponse(result)) { + return false; + } + let status = result.status; + let location = result.headers.get("Location"); + return status >= 300 && status <= 399 && location != null; + } + function isValidMethod(method) { + return validRequestMethods.has(method.toLowerCase()); + } + function isMutationMethod(method) { + return validMutationMethods.has(method.toLowerCase()); + } + async function resolveNavigationDeferredResults(matches, results, signal, currentMatches, currentLoaderData) { + let entries = Object.entries(results); + for (let index = 0; index < entries.length; index++) { + let [routeId, result] = entries[index]; + let match = matches.find((m) => (m == null ? void 0 : m.route.id) === routeId); + if (!match) { + continue; + } + let currentMatch = currentMatches.find((m) => m.route.id === match.route.id); + let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== void 0; + if (isDeferredResult(result) && isRevalidatingLoader) { + await resolveDeferredData(result, signal, false).then((result2) => { + if (result2) { + results[routeId] = result2; + } + }); + } + } + } + async function resolveFetcherDeferredResults(matches, results, revalidatingFetchers) { + for (let index = 0; index < revalidatingFetchers.length; index++) { + let { + key, + routeId, + controller + } = revalidatingFetchers[index]; + let result = results[key]; + let match = matches.find((m) => (m == null ? void 0 : m.route.id) === routeId); + if (!match) { + continue; + } + if (isDeferredResult(result)) { + invariant2(controller, "Expected an AbortController for revalidating fetcher deferred result"); + await resolveDeferredData(result, controller.signal, true).then((result2) => { + if (result2) { + results[key] = result2; + } + }); + } + } + } + async function resolveDeferredData(result, signal, unwrap) { + if (unwrap === void 0) { + unwrap = false; + } + let aborted = await result.deferredData.resolveData(signal); + if (aborted) { + return; + } + if (unwrap) { + try { + return { + type: ResultType.data, + data: result.deferredData.unwrappedData + }; + } catch (e2) { + return { + type: ResultType.error, + error: e2 + }; + } + } + return { + type: ResultType.data, + data: result.deferredData.data + }; + } + function hasNakedIndexQuery(search) { + return new URLSearchParams(search).getAll("index").some((v) => v === ""); + } + function getTargetMatch(matches, location) { + let search = typeof location === "string" ? parsePath3(location).search : location.search; + if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) { + return matches[matches.length - 1]; + } + let pathMatches = getPathContributingMatches(matches); + return pathMatches[pathMatches.length - 1]; + } + function getSubmissionFromNavigation(navigation) { + let { + formMethod, + formAction, + formEncType, + text, + formData, + json: json2 + } = navigation; + if (!formMethod || !formAction || !formEncType) { + return; + } + if (text != null) { + return { + formMethod, + formAction, + formEncType, + formData: void 0, + json: void 0, + text + }; + } else if (formData != null) { + return { + formMethod, + formAction, + formEncType, + formData, + json: void 0, + text: void 0 + }; + } else if (json2 !== void 0) { + return { + formMethod, + formAction, + formEncType, + formData: void 0, + json: json2, + text: void 0 + }; + } + } + function getLoadingNavigation(location, submission) { + if (submission) { + let navigation = { + state: "loading", + location, + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text + }; + return navigation; + } else { + let navigation = { + state: "loading", + location, + formMethod: void 0, + formAction: void 0, + formEncType: void 0, + formData: void 0, + json: void 0, + text: void 0 + }; + return navigation; + } + } + function getSubmittingNavigation(location, submission) { + let navigation = { + state: "submitting", + location, + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text + }; + return navigation; + } + function getLoadingFetcher(submission, data2) { + if (submission) { + let fetcher = { + state: "loading", + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text, + data: data2 + }; + return fetcher; + } else { + let fetcher = { + state: "loading", + formMethod: void 0, + formAction: void 0, + formEncType: void 0, + formData: void 0, + json: void 0, + text: void 0, + data: data2 + }; + return fetcher; + } + } + function getSubmittingFetcher(submission, existingFetcher) { + let fetcher = { + state: "submitting", + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text, + data: existingFetcher ? existingFetcher.data : void 0 + }; + return fetcher; + } + function getDoneFetcher(data2) { + let fetcher = { + state: "idle", + formMethod: void 0, + formAction: void 0, + formEncType: void 0, + formData: void 0, + json: void 0, + text: void 0, + data: data2 + }; + return fetcher; + } + function restoreAppliedTransitions(_window, transitions) { + try { + let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY); + if (sessionPositions) { + let json2 = JSON.parse(sessionPositions); + for (let [k2, v] of Object.entries(json2 || {})) { + if (v && Array.isArray(v)) { + transitions.set(k2, new Set(v || [])); + } + } + } + } catch (e2) { + } + } + function persistAppliedTransitions(_window, transitions) { + if (transitions.size > 0) { + let json2 = {}; + for (let [k2, v] of transitions) { + json2[k2] = [...v]; + } + try { + _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json2)); + } catch (error) { + warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ")."); + } + } + } + exports.AbortedDeferredError = AbortedDeferredError; + exports.Action = Action; + exports.IDLE_BLOCKER = IDLE_BLOCKER; + exports.IDLE_FETCHER = IDLE_FETCHER; + exports.IDLE_NAVIGATION = IDLE_NAVIGATION; + exports.UNSAFE_DEFERRED_SYMBOL = UNSAFE_DEFERRED_SYMBOL; + exports.UNSAFE_DeferredData = DeferredData; + exports.UNSAFE_ErrorResponseImpl = ErrorResponseImpl; + exports.UNSAFE_convertRouteMatchToUiMatch = convertRouteMatchToUiMatch; + exports.UNSAFE_convertRoutesToDataRoutes = convertRoutesToDataRoutes; + exports.UNSAFE_decodePath = decodePath; + exports.UNSAFE_getResolveToMatches = getResolveToMatches; + exports.UNSAFE_invariant = invariant2; + exports.UNSAFE_warning = warning; + exports.createBrowserHistory = createBrowserHistory; + exports.createHashHistory = createHashHistory; + exports.createMemoryHistory = createMemoryHistory; + exports.createPath = createPath2; + exports.createRouter = createRouter; + exports.createStaticHandler = createStaticHandler; + exports.defer = defer; + exports.generatePath = generatePath2; + exports.getStaticContextFromError = getStaticContextFromError; + exports.getToPathname = getToPathname; + exports.isDataWithResponseInit = isDataWithResponseInit; + exports.isDeferredData = isDeferredData; + exports.isRouteErrorResponse = isRouteErrorResponse3; + exports.joinPaths = joinPaths; + exports.json = json; + exports.matchPath = matchPath2; + exports.matchRoutes = matchRoutes4; + exports.normalizePathname = normalizePathname; + exports.parsePath = parsePath3; + exports.redirect = redirect2; + exports.redirectDocument = redirectDocument; + exports.replace = replace; + exports.resolvePath = resolvePath2; + exports.resolveTo = resolveTo; + exports.stripBasename = stripBasename; + exports.unstable_data = data; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/mode.js +var require_mode = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/mode.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var ServerMode = /* @__PURE__ */ function(ServerMode2) { + ServerMode2["Development"] = "development"; + ServerMode2["Production"] = "production"; + ServerMode2["Test"] = "test"; + return ServerMode2; + }({}); + function isServerMode(value) { + return value === ServerMode.Development || value === ServerMode.Production || value === ServerMode.Test; + } + exports.ServerMode = ServerMode; + exports.isServerMode = isServerMode; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/errors.js +var require_errors = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var router = require_router_cjs(); + var mode = require_mode(); + function sanitizeError(error, serverMode) { + if (error instanceof Error && serverMode !== mode.ServerMode.Development) { + let sanitized = new Error("Unexpected Server Error"); + sanitized.stack = void 0; + return sanitized; + } + return error; + } + function sanitizeErrors(errors, serverMode) { + return Object.entries(errors).reduce((acc, [routeId, error]) => { + return Object.assign(acc, { + [routeId]: sanitizeError(error, serverMode) + }); + }, {}); + } + function serializeError(error, serverMode) { + let sanitized = sanitizeError(error, serverMode); + return { + message: sanitized.message, + stack: sanitized.stack + }; + } + function serializeErrors(errors, serverMode) { + if (!errors) + return null; + let entries = Object.entries(errors); + let serialized = {}; + for (let [key, val] of entries) { + if (router.isRouteErrorResponse(val)) { + serialized[key] = { + ...val, + __type: "RouteErrorResponse" + }; + } else if (val instanceof Error) { + let sanitized = sanitizeError(val, serverMode); + serialized[key] = { + message: sanitized.message, + stack: sanitized.stack, + __type: "Error", + // If this is a subclass (i.e., ReferenceError), send up the type so we + // can re-create the same type during hydration. This will only apply + // in dev mode since all production errors are sanitized to normal + // Error instances + ...sanitized.name !== "Error" ? { + __subType: sanitized.name + } : {} + }; + } else { + serialized[key] = val; + } + } + return serialized; + } + exports.sanitizeError = sanitizeError; + exports.sanitizeErrors = sanitizeErrors; + exports.serializeError = serializeError; + exports.serializeErrors = serializeErrors; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/responses.js +var require_responses = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/responses.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var router = require_router_cjs(); + var errors = require_errors(); + var json = (data, init = {}) => { + return router.json(data, init); + }; + var defer = (data, init = {}) => { + return router.defer(data, init); + }; + var redirect2 = (url, init = 302) => { + return router.redirect(url, init); + }; + var replace = (url, init = 302) => { + return router.replace(url, init); + }; + var redirectDocument = (url, init = 302) => { + return router.redirectDocument(url, init); + }; + function isDeferredData(value) { + let deferred = value; + return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function"; + } + function isResponse(value) { + return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined"; + } + var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]); + function isRedirectStatusCode(statusCode) { + return redirectStatusCodes.has(statusCode); + } + function isRedirectResponse(response) { + return isRedirectStatusCode(response.status); + } + function isTrackedPromise(value) { + return value != null && typeof value.then === "function" && value._tracked === true; + } + var DEFERRED_VALUE_PLACEHOLDER_PREFIX = "__deferred_promise:"; + function createDeferredReadableStream(deferredData, signal, serverMode) { + let encoder = new TextEncoder(); + let stream = new ReadableStream({ + async start(controller) { + let criticalData = {}; + let preresolvedKeys = []; + for (let [key, value] of Object.entries(deferredData.data)) { + if (isTrackedPromise(value)) { + criticalData[key] = `${DEFERRED_VALUE_PLACEHOLDER_PREFIX}${key}`; + if (typeof value._data !== "undefined" || typeof value._error !== "undefined") { + preresolvedKeys.push(key); + } + } else { + criticalData[key] = value; + } + } + controller.enqueue(encoder.encode(JSON.stringify(criticalData) + "\n\n")); + for (let preresolvedKey of preresolvedKeys) { + enqueueTrackedPromise(controller, encoder, preresolvedKey, deferredData.data[preresolvedKey], serverMode); + } + let unsubscribe = deferredData.subscribe((aborted, settledKey) => { + if (settledKey) { + enqueueTrackedPromise(controller, encoder, settledKey, deferredData.data[settledKey], serverMode); + } + }); + await deferredData.resolveData(signal); + unsubscribe(); + controller.close(); + } + }); + return stream; + } + function enqueueTrackedPromise(controller, encoder, settledKey, promise, serverMode) { + if ("_error" in promise) { + controller.enqueue(encoder.encode("error:" + JSON.stringify({ + [settledKey]: promise._error instanceof Error ? errors.serializeError(promise._error, serverMode) : promise._error + }) + "\n\n")); + } else { + controller.enqueue(encoder.encode("data:" + JSON.stringify({ + [settledKey]: promise._data ?? null + }) + "\n\n")); + } + } + exports.createDeferredReadableStream = createDeferredReadableStream; + exports.defer = defer; + exports.isDeferredData = isDeferredData; + exports.isRedirectResponse = isRedirectResponse; + exports.isRedirectStatusCode = isRedirectStatusCode; + exports.isResponse = isResponse; + exports.json = json; + exports.redirect = redirect2; + exports.redirectDocument = redirectDocument; + exports.replace = replace; + } +}); + +// ../../../node_modules/.pnpm/turbo-stream@2.4.0/node_modules/turbo-stream/dist/utils.js +var require_utils = __commonJS({ + "../../../node_modules/.pnpm/turbo-stream@2.4.0/node_modules/turbo-stream/dist/utils.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createLineSplittingTransform = exports.Deferred = exports.TYPE_PREVIOUS_RESOLVED = exports.TYPE_URL = exports.TYPE_SYMBOL = exports.TYPE_SET = exports.TYPE_REGEXP = exports.TYPE_PROMISE = exports.TYPE_NULL_OBJECT = exports.TYPE_MAP = exports.TYPE_ERROR = exports.TYPE_DATE = exports.TYPE_BIGINT = exports.UNDEFINED = exports.POSITIVE_INFINITY = exports.NULL = exports.NEGATIVE_ZERO = exports.NEGATIVE_INFINITY = exports.NAN = exports.HOLE = void 0; + exports.HOLE = -1; + exports.NAN = -2; + exports.NEGATIVE_INFINITY = -3; + exports.NEGATIVE_ZERO = -4; + exports.NULL = -5; + exports.POSITIVE_INFINITY = -6; + exports.UNDEFINED = -7; + exports.TYPE_BIGINT = "B"; + exports.TYPE_DATE = "D"; + exports.TYPE_ERROR = "E"; + exports.TYPE_MAP = "M"; + exports.TYPE_NULL_OBJECT = "N"; + exports.TYPE_PROMISE = "P"; + exports.TYPE_REGEXP = "R"; + exports.TYPE_SET = "S"; + exports.TYPE_SYMBOL = "Y"; + exports.TYPE_URL = "U"; + exports.TYPE_PREVIOUS_RESOLVED = "Z"; + var Deferred = class { + promise; + resolve; + reject; + constructor() { + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } + }; + exports.Deferred = Deferred; + function createLineSplittingTransform() { + const decoder = new TextDecoder(); + let leftover = ""; + return new TransformStream({ + transform(chunk, controller) { + const str = decoder.decode(chunk, { stream: true }); + const parts = (leftover + str).split("\n"); + leftover = parts.pop() || ""; + for (const part of parts) { + controller.enqueue(part); + } + }, + flush(controller) { + if (leftover) { + controller.enqueue(leftover); + } + } + }); + } + exports.createLineSplittingTransform = createLineSplittingTransform; + } +}); + +// ../../../node_modules/.pnpm/turbo-stream@2.4.0/node_modules/turbo-stream/dist/flatten.js +var require_flatten = __commonJS({ + "../../../node_modules/.pnpm/turbo-stream@2.4.0/node_modules/turbo-stream/dist/flatten.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.flatten = void 0; + var utils_js_1 = require_utils(); + function flatten(input) { + const { indices } = this; + const existing = indices.get(input); + if (existing) + return [existing]; + if (input === void 0) + return utils_js_1.UNDEFINED; + if (input === null) + return utils_js_1.NULL; + if (Number.isNaN(input)) + return utils_js_1.NAN; + if (input === Number.POSITIVE_INFINITY) + return utils_js_1.POSITIVE_INFINITY; + if (input === Number.NEGATIVE_INFINITY) + return utils_js_1.NEGATIVE_INFINITY; + if (input === 0 && 1 / input < 0) + return utils_js_1.NEGATIVE_ZERO; + const index = this.index++; + indices.set(input, index); + stringify.call(this, input, index); + return index; + } + exports.flatten = flatten; + function stringify(input, index) { + const { deferred, plugins, postPlugins } = this; + const str = this.stringified; + const stack = [[input, index]]; + while (stack.length > 0) { + const [input2, index2] = stack.pop(); + const partsForObj = (obj) => Object.keys(obj).map((k2) => `"_${flatten.call(this, k2)}":${flatten.call(this, obj[k2])}`).join(","); + let error = null; + switch (typeof input2) { + case "boolean": + case "number": + case "string": + str[index2] = JSON.stringify(input2); + break; + case "bigint": + str[index2] = `["${utils_js_1.TYPE_BIGINT}","${input2}"]`; + break; + case "symbol": { + const keyFor = Symbol.keyFor(input2); + if (!keyFor) { + error = new Error("Cannot encode symbol unless created with Symbol.for()"); + } else { + str[index2] = `["${utils_js_1.TYPE_SYMBOL}",${JSON.stringify(keyFor)}]`; + } + break; + } + case "object": { + if (!input2) { + str[index2] = `${utils_js_1.NULL}`; + break; + } + const isArray = Array.isArray(input2); + let pluginHandled = false; + if (!isArray && plugins) { + for (const plugin of plugins) { + const pluginResult = plugin(input2); + if (Array.isArray(pluginResult)) { + pluginHandled = true; + const [pluginIdentifier, ...rest] = pluginResult; + str[index2] = `[${JSON.stringify(pluginIdentifier)}`; + if (rest.length > 0) { + str[index2] += `,${rest.map((v) => flatten.call(this, v)).join(",")}`; + } + str[index2] += "]"; + break; + } + } + } + if (!pluginHandled) { + let result = isArray ? "[" : "{"; + if (isArray) { + for (let i2 = 0; i2 < input2.length; i2++) + result += (i2 ? "," : "") + (i2 in input2 ? flatten.call(this, input2[i2]) : utils_js_1.HOLE); + str[index2] = `${result}]`; + } else if (input2 instanceof Date) { + str[index2] = `["${utils_js_1.TYPE_DATE}",${input2.getTime()}]`; + } else if (input2 instanceof URL) { + str[index2] = `["${utils_js_1.TYPE_URL}",${JSON.stringify(input2.href)}]`; + } else if (input2 instanceof RegExp) { + str[index2] = `["${utils_js_1.TYPE_REGEXP}",${JSON.stringify(input2.source)},${JSON.stringify(input2.flags)}]`; + } else if (input2 instanceof Set) { + if (input2.size > 0) { + str[index2] = `["${utils_js_1.TYPE_SET}",${[...input2].map((val) => flatten.call(this, val)).join(",")}]`; + } else { + str[index2] = `["${utils_js_1.TYPE_SET}"]`; + } + } else if (input2 instanceof Map) { + if (input2.size > 0) { + str[index2] = `["${utils_js_1.TYPE_MAP}",${[...input2].flatMap(([k2, v]) => [ + flatten.call(this, k2), + flatten.call(this, v) + ]).join(",")}]`; + } else { + str[index2] = `["${utils_js_1.TYPE_MAP}"]`; + } + } else if (input2 instanceof Promise) { + str[index2] = `["${utils_js_1.TYPE_PROMISE}",${index2}]`; + deferred[index2] = input2; + } else if (input2 instanceof Error) { + str[index2] = `["${utils_js_1.TYPE_ERROR}",${JSON.stringify(input2.message)}`; + if (input2.name !== "Error") { + str[index2] += `,${JSON.stringify(input2.name)}`; + } + str[index2] += "]"; + } else if (Object.getPrototypeOf(input2) === null) { + str[index2] = `["${utils_js_1.TYPE_NULL_OBJECT}",{${partsForObj(input2)}}]`; + } else if (isPlainObject(input2)) { + str[index2] = `{${partsForObj(input2)}}`; + } else { + error = new Error("Cannot encode object with prototype"); + } + } + break; + } + default: { + const isArray = Array.isArray(input2); + let pluginHandled = false; + if (!isArray && plugins) { + for (const plugin of plugins) { + const pluginResult = plugin(input2); + if (Array.isArray(pluginResult)) { + pluginHandled = true; + const [pluginIdentifier, ...rest] = pluginResult; + str[index2] = `[${JSON.stringify(pluginIdentifier)}`; + if (rest.length > 0) { + str[index2] += `,${rest.map((v) => flatten.call(this, v)).join(",")}`; + } + str[index2] += "]"; + break; + } + } + } + if (!pluginHandled) { + error = new Error("Cannot encode function or unexpected type"); + } + } + } + if (error) { + let pluginHandled = false; + if (postPlugins) { + for (const plugin of postPlugins) { + const pluginResult = plugin(input2); + if (Array.isArray(pluginResult)) { + pluginHandled = true; + const [pluginIdentifier, ...rest] = pluginResult; + str[index2] = `[${JSON.stringify(pluginIdentifier)}`; + if (rest.length > 0) { + str[index2] += `,${rest.map((v) => flatten.call(this, v)).join(",")}`; + } + str[index2] += "]"; + break; + } + } + } + if (!pluginHandled) { + throw error; + } + } + } + } + var objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0"); + function isPlainObject(thing) { + const proto = Object.getPrototypeOf(thing); + return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames; + } + } +}); + +// ../../../node_modules/.pnpm/turbo-stream@2.4.0/node_modules/turbo-stream/dist/unflatten.js +var require_unflatten = __commonJS({ + "../../../node_modules/.pnpm/turbo-stream@2.4.0/node_modules/turbo-stream/dist/unflatten.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.unflatten = void 0; + var utils_js_1 = require_utils(); + var globalObj = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : void 0; + function unflatten(parsed) { + const { hydrated, values } = this; + if (typeof parsed === "number") + return hydrate.call(this, parsed); + if (!Array.isArray(parsed) || !parsed.length) + throw new SyntaxError(); + const startIndex = values.length; + for (const value of parsed) { + values.push(value); + } + hydrated.length = values.length; + return hydrate.call(this, startIndex); + } + exports.unflatten = unflatten; + function hydrate(index) { + const { hydrated, values, deferred, plugins } = this; + let result; + const stack = [ + [ + index, + (v) => { + result = v; + } + ] + ]; + let postRun = []; + while (stack.length > 0) { + const [index2, set] = stack.pop(); + switch (index2) { + case utils_js_1.UNDEFINED: + set(void 0); + continue; + case utils_js_1.NULL: + set(null); + continue; + case utils_js_1.NAN: + set(NaN); + continue; + case utils_js_1.POSITIVE_INFINITY: + set(Infinity); + continue; + case utils_js_1.NEGATIVE_INFINITY: + set(-Infinity); + continue; + case utils_js_1.NEGATIVE_ZERO: + set(-0); + continue; + } + if (hydrated[index2]) { + set(hydrated[index2]); + continue; + } + const value = values[index2]; + if (!value || typeof value !== "object") { + hydrated[index2] = value; + set(value); + continue; + } + if (Array.isArray(value)) { + if (typeof value[0] === "string") { + const [type, b, c2] = value; + switch (type) { + case utils_js_1.TYPE_DATE: + set(hydrated[index2] = new Date(b)); + continue; + case utils_js_1.TYPE_URL: + set(hydrated[index2] = new URL(b)); + continue; + case utils_js_1.TYPE_BIGINT: + set(hydrated[index2] = BigInt(b)); + continue; + case utils_js_1.TYPE_REGEXP: + set(hydrated[index2] = new RegExp(b, c2)); + continue; + case utils_js_1.TYPE_SYMBOL: + set(hydrated[index2] = Symbol.for(b)); + continue; + case utils_js_1.TYPE_SET: + const newSet = /* @__PURE__ */ new Set(); + hydrated[index2] = newSet; + for (let i2 = 1; i2 < value.length; i2++) + stack.push([ + value[i2], + (v) => { + newSet.add(v); + } + ]); + set(newSet); + continue; + case utils_js_1.TYPE_MAP: + const map = /* @__PURE__ */ new Map(); + hydrated[index2] = map; + for (let i2 = 1; i2 < value.length; i2 += 2) { + const r = []; + stack.push([ + value[i2 + 1], + (v) => { + r[1] = v; + } + ]); + stack.push([ + value[i2], + (k2) => { + r[0] = k2; + } + ]); + postRun.push(() => { + map.set(r[0], r[1]); + }); + } + set(map); + continue; + case utils_js_1.TYPE_NULL_OBJECT: + const obj = /* @__PURE__ */ Object.create(null); + hydrated[index2] = obj; + for (const key of Object.keys(b).reverse()) { + const r = []; + stack.push([ + b[key], + (v) => { + r[1] = v; + } + ]); + stack.push([ + Number(key.slice(1)), + (k2) => { + r[0] = k2; + } + ]); + postRun.push(() => { + obj[r[0]] = r[1]; + }); + } + set(obj); + continue; + case utils_js_1.TYPE_PROMISE: + if (hydrated[b]) { + set(hydrated[index2] = hydrated[b]); + } else { + const d = new utils_js_1.Deferred(); + deferred[b] = d; + set(hydrated[index2] = d.promise); + } + continue; + case utils_js_1.TYPE_ERROR: + const [, message, errorType] = value; + let error = errorType && globalObj && globalObj[errorType] ? new globalObj[errorType](message) : new Error(message); + hydrated[index2] = error; + set(error); + continue; + case utils_js_1.TYPE_PREVIOUS_RESOLVED: + set(hydrated[index2] = hydrated[b]); + continue; + default: + if (Array.isArray(plugins)) { + const r = []; + const vals = value.slice(1); + for (let i2 = 0; i2 < vals.length; i2++) { + const v = vals[i2]; + stack.push([ + v, + (v2) => { + r[i2] = v2; + } + ]); + } + postRun.push(() => { + for (const plugin of plugins) { + const result2 = plugin(value[0], ...r); + if (result2) { + set(hydrated[index2] = result2.value); + return; + } + } + throw new SyntaxError(); + }); + continue; + } + throw new SyntaxError(); + } + } else { + const array = []; + hydrated[index2] = array; + for (let i2 = 0; i2 < value.length; i2++) { + const n2 = value[i2]; + if (n2 !== utils_js_1.HOLE) { + stack.push([ + n2, + (v) => { + array[i2] = v; + } + ]); + } + } + set(array); + continue; + } + } else { + const object = {}; + hydrated[index2] = object; + for (const key of Object.keys(value).reverse()) { + const r = []; + stack.push([ + value[key], + (v) => { + r[1] = v; + } + ]); + stack.push([ + Number(key.slice(1)), + (k2) => { + r[0] = k2; + } + ]); + postRun.push(() => { + object[r[0]] = r[1]; + }); + } + set(object); + continue; + } + } + while (postRun.length > 0) { + postRun.pop()(); + } + return result; + } + } +}); + +// ../../../node_modules/.pnpm/turbo-stream@2.4.0/node_modules/turbo-stream/dist/turbo-stream.js +var require_turbo_stream = __commonJS({ + "../../../node_modules/.pnpm/turbo-stream@2.4.0/node_modules/turbo-stream/dist/turbo-stream.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.encode = exports.decode = void 0; + var flatten_js_1 = require_flatten(); + var unflatten_js_1 = require_unflatten(); + var utils_js_1 = require_utils(); + async function decode(readable, options) { + const { plugins } = options ?? {}; + const done = new utils_js_1.Deferred(); + const reader = readable.pipeThrough((0, utils_js_1.createLineSplittingTransform)()).getReader(); + const decoder = { + values: [], + hydrated: [], + deferred: {}, + plugins + }; + const decoded = await decodeInitial.call(decoder, reader); + let donePromise = done.promise; + if (decoded.done) { + done.resolve(); + } else { + donePromise = decodeDeferred.call(decoder, reader).then(done.resolve).catch((reason) => { + for (const deferred of Object.values(decoder.deferred)) { + deferred.reject(reason); + } + done.reject(reason); + }); + } + return { + done: donePromise.then(() => reader.closed), + value: decoded.value + }; + } + exports.decode = decode; + async function decodeInitial(reader) { + const read = await reader.read(); + if (!read.value) { + throw new SyntaxError(); + } + let line; + try { + line = JSON.parse(read.value); + } catch (reason) { + throw new SyntaxError(); + } + return { + done: read.done, + value: unflatten_js_1.unflatten.call(this, line) + }; + } + async function decodeDeferred(reader) { + let read = await reader.read(); + while (!read.done) { + if (!read.value) + continue; + const line = read.value; + switch (line[0]) { + case utils_js_1.TYPE_PROMISE: { + const colonIndex = line.indexOf(":"); + const deferredId = Number(line.slice(1, colonIndex)); + const deferred = this.deferred[deferredId]; + if (!deferred) { + throw new Error(`Deferred ID ${deferredId} not found in stream`); + } + const lineData = line.slice(colonIndex + 1); + let jsonLine; + try { + jsonLine = JSON.parse(lineData); + } catch (reason) { + throw new SyntaxError(); + } + const value = unflatten_js_1.unflatten.call(this, jsonLine); + deferred.resolve(value); + break; + } + case utils_js_1.TYPE_ERROR: { + const colonIndex = line.indexOf(":"); + const deferredId = Number(line.slice(1, colonIndex)); + const deferred = this.deferred[deferredId]; + if (!deferred) { + throw new Error(`Deferred ID ${deferredId} not found in stream`); + } + const lineData = line.slice(colonIndex + 1); + let jsonLine; + try { + jsonLine = JSON.parse(lineData); + } catch (reason) { + throw new SyntaxError(); + } + const value = unflatten_js_1.unflatten.call(this, jsonLine); + deferred.reject(value); + break; + } + default: + throw new SyntaxError(); + } + read = await reader.read(); + } + } + function encode(input, options) { + const { plugins, postPlugins, signal } = options ?? {}; + const encoder = { + deferred: {}, + index: 0, + indices: /* @__PURE__ */ new Map(), + stringified: [], + plugins, + postPlugins, + signal + }; + const textEncoder = new TextEncoder(); + let lastSentIndex = 0; + const readable = new ReadableStream({ + async start(controller) { + const id = flatten_js_1.flatten.call(encoder, input); + if (Array.isArray(id)) { + throw new Error("This should never happen"); + } + if (id < 0) { + controller.enqueue(textEncoder.encode(`${id} +`)); + } else { + controller.enqueue(textEncoder.encode(`[${encoder.stringified.join(",")}] +`)); + lastSentIndex = encoder.stringified.length - 1; + } + const seenPromises = /* @__PURE__ */ new WeakSet(); + while (Object.keys(encoder.deferred).length > 0) { + for (const [deferredId, deferred] of Object.entries(encoder.deferred)) { + if (seenPromises.has(deferred)) + continue; + seenPromises.add(encoder.deferred[Number(deferredId)] = raceSignal(deferred, encoder.signal).then((resolved) => { + const id2 = flatten_js_1.flatten.call(encoder, resolved); + if (Array.isArray(id2)) { + controller.enqueue(textEncoder.encode(`${utils_js_1.TYPE_PROMISE}${deferredId}:[["${utils_js_1.TYPE_PREVIOUS_RESOLVED}",${id2[0]}]] +`)); + encoder.index++; + lastSentIndex++; + } else if (id2 < 0) { + controller.enqueue(textEncoder.encode(`${utils_js_1.TYPE_PROMISE}${deferredId}:${id2} +`)); + } else { + const values = encoder.stringified.slice(lastSentIndex + 1).join(","); + controller.enqueue(textEncoder.encode(`${utils_js_1.TYPE_PROMISE}${deferredId}:[${values}] +`)); + lastSentIndex = encoder.stringified.length - 1; + } + }, (reason) => { + if (!reason || typeof reason !== "object" || !(reason instanceof Error)) { + reason = new Error("An unknown error occurred"); + } + const id2 = flatten_js_1.flatten.call(encoder, reason); + if (Array.isArray(id2)) { + controller.enqueue(textEncoder.encode(`${utils_js_1.TYPE_ERROR}${deferredId}:[["${utils_js_1.TYPE_PREVIOUS_RESOLVED}",${id2[0]}]] +`)); + encoder.index++; + lastSentIndex++; + } else if (id2 < 0) { + controller.enqueue(textEncoder.encode(`${utils_js_1.TYPE_ERROR}${deferredId}:${id2} +`)); + } else { + const values = encoder.stringified.slice(lastSentIndex + 1).join(","); + controller.enqueue(textEncoder.encode(`${utils_js_1.TYPE_ERROR}${deferredId}:[${values}] +`)); + lastSentIndex = encoder.stringified.length - 1; + } + }).finally(() => { + delete encoder.deferred[Number(deferredId)]; + })); + } + await Promise.race(Object.values(encoder.deferred)); + } + await Promise.all(Object.values(encoder.deferred)); + controller.close(); + } + }); + return readable; + } + exports.encode = encode; + function raceSignal(promise, signal) { + if (!signal) + return promise; + if (signal.aborted) + return Promise.reject(signal.reason || new Error("Signal was aborted.")); + const abort = new Promise((resolve, reject) => { + signal.addEventListener("abort", (event) => { + reject(signal.reason || new Error("Signal was aborted.")); + }); + promise.then(resolve).catch(reject); + }); + abort.catch(() => { + }); + return Promise.race([abort, promise]); + } + } +}); + +// ../../../node_modules/.pnpm/set-cookie-parser@2.6.0/node_modules/set-cookie-parser/lib/set-cookie.js +var require_set_cookie = __commonJS({ + "../../../node_modules/.pnpm/set-cookie-parser@2.6.0/node_modules/set-cookie-parser/lib/set-cookie.js"(exports, module) { + "use strict"; + var defaultParseOptions = { + decodeValues: true, + map: false, + silent: false + }; + function isNonEmptyString(str) { + return typeof str === "string" && !!str.trim(); + } + function parseString(setCookieValue, options) { + var parts = setCookieValue.split(";").filter(isNonEmptyString); + var nameValuePairStr = parts.shift(); + var parsed = parseNameValuePair(nameValuePairStr); + var name = parsed.name; + var value = parsed.value; + options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; + try { + value = options.decodeValues ? decodeURIComponent(value) : value; + } catch (e2) { + console.error( + "set-cookie-parser encountered an error while decoding a cookie with value '" + value + "'. Set options.decodeValues to false to disable this feature.", + e2 + ); + } + var cookie = { + name, + value + }; + parts.forEach(function(part) { + var sides = part.split("="); + var key = sides.shift().trimLeft().toLowerCase(); + var value2 = sides.join("="); + if (key === "expires") { + cookie.expires = new Date(value2); + } else if (key === "max-age") { + cookie.maxAge = parseInt(value2, 10); + } else if (key === "secure") { + cookie.secure = true; + } else if (key === "httponly") { + cookie.httpOnly = true; + } else if (key === "samesite") { + cookie.sameSite = value2; + } else { + cookie[key] = value2; + } + }); + return cookie; + } + function parseNameValuePair(nameValuePairStr) { + var name = ""; + var value = ""; + var nameValueArr = nameValuePairStr.split("="); + if (nameValueArr.length > 1) { + name = nameValueArr.shift(); + value = nameValueArr.join("="); + } else { + value = nameValuePairStr; + } + return { name, value }; + } + function parse(input, options) { + options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; + if (!input) { + if (!options.map) { + return []; + } else { + return {}; + } + } + if (input.headers) { + if (typeof input.headers.getSetCookie === "function") { + input = input.headers.getSetCookie(); + } else if (input.headers["set-cookie"]) { + input = input.headers["set-cookie"]; + } else { + var sch = input.headers[Object.keys(input.headers).find(function(key) { + return key.toLowerCase() === "set-cookie"; + })]; + if (!sch && input.headers.cookie && !options.silent) { + console.warn( + "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." + ); + } + input = sch; + } + } + if (!Array.isArray(input)) { + input = [input]; + } + options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; + if (!options.map) { + return input.filter(isNonEmptyString).map(function(str) { + return parseString(str, options); + }); + } else { + var cookies = {}; + return input.filter(isNonEmptyString).reduce(function(cookies2, str) { + var cookie = parseString(str, options); + cookies2[cookie.name] = cookie; + return cookies2; + }, cookies); + } + } + function splitCookiesString(cookiesString) { + if (Array.isArray(cookiesString)) { + return cookiesString; + } + if (typeof cookiesString !== "string") { + return []; + } + var cookiesStrings = []; + var pos = 0; + var start; + var ch; + var lastComma; + var nextStart; + var cookiesSeparatorFound; + function skipWhitespace() { + while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) { + pos += 1; + } + return pos < cookiesString.length; + } + function notSpecialChar() { + ch = cookiesString.charAt(pos); + return ch !== "=" && ch !== ";" && ch !== ","; + } + while (pos < cookiesString.length) { + start = pos; + cookiesSeparatorFound = false; + while (skipWhitespace()) { + ch = cookiesString.charAt(pos); + if (ch === ",") { + lastComma = pos; + pos += 1; + skipWhitespace(); + nextStart = pos; + while (pos < cookiesString.length && notSpecialChar()) { + pos += 1; + } + if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") { + cookiesSeparatorFound = true; + pos = nextStart; + cookiesStrings.push(cookiesString.substring(start, lastComma)); + start = pos; + } else { + pos = lastComma + 1; + } + } else { + pos += 1; + } + } + if (!cookiesSeparatorFound || pos >= cookiesString.length) { + cookiesStrings.push(cookiesString.substring(start, cookiesString.length)); + } + } + return cookiesStrings; + } + module.exports = parse; + module.exports.parse = parse; + module.exports.parseString = parseString; + module.exports.splitCookiesString = splitCookiesString; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/headers.js +var require_headers = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/headers.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var setCookieParser = require_set_cookie(); + function getDocumentHeaders(build, context) { + let boundaryIdx = context.errors ? context.matches.findIndex((m) => context.errors[m.route.id]) : -1; + let matches = boundaryIdx >= 0 ? context.matches.slice(0, boundaryIdx + 1) : context.matches; + let errorHeaders; + if (boundaryIdx >= 0) { + let { + actionHeaders, + actionData, + loaderHeaders, + loaderData + } = context; + context.matches.slice(boundaryIdx).some((match) => { + let id = match.route.id; + if (actionHeaders[id] && (!actionData || actionData[id] === void 0)) { + errorHeaders = actionHeaders[id]; + } else if (loaderHeaders[id] && loaderData[id] === void 0) { + errorHeaders = loaderHeaders[id]; + } + return errorHeaders != null; + }); + } + return matches.reduce((parentHeaders, match, idx) => { + let { + id + } = match.route; + let routeModule = build.routes[id].module; + let loaderHeaders = context.loaderHeaders[id] || new Headers(); + let actionHeaders = context.actionHeaders[id] || new Headers(); + let includeErrorHeaders = errorHeaders != void 0 && idx === matches.length - 1; + let includeErrorCookies = includeErrorHeaders && errorHeaders !== loaderHeaders && errorHeaders !== actionHeaders; + if (routeModule.headers == null) { + let headers2 = new Headers(parentHeaders); + if (includeErrorCookies) { + prependCookies(errorHeaders, headers2); + } + prependCookies(actionHeaders, headers2); + prependCookies(loaderHeaders, headers2); + return headers2; + } + let headers = new Headers(routeModule.headers ? typeof routeModule.headers === "function" ? routeModule.headers({ + loaderHeaders, + parentHeaders, + actionHeaders, + errorHeaders: includeErrorHeaders ? errorHeaders : void 0 + }) : routeModule.headers : void 0); + if (includeErrorCookies) { + prependCookies(errorHeaders, headers); + } + prependCookies(actionHeaders, headers); + prependCookies(loaderHeaders, headers); + prependCookies(parentHeaders, headers); + return headers; + }, new Headers()); + } + function prependCookies(parentHeaders, childHeaders) { + let parentSetCookieString = parentHeaders.get("Set-Cookie"); + if (parentSetCookieString) { + let cookies = setCookieParser.splitCookiesString(parentSetCookieString); + cookies.forEach((cookie) => { + childHeaders.append("Set-Cookie", cookie); + }); + } + } + exports.getDocumentHeaders = getDocumentHeaders; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/single-fetch.js +var require_single_fetch = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/single-fetch.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var router = require_router_cjs(); + var turboStream = require_turbo_stream(); + var errors = require_errors(); + var headers = require_headers(); + var mode = require_mode(); + var responses = require_responses(); + var SingleFetchRedirectSymbol = Symbol("SingleFetchRedirect"); + var SINGLE_FETCH_REDIRECT_STATUS = 202; + function getSingleFetchDataStrategy({ + isActionDataRequest, + loadRouteIds + } = {}) { + return async ({ + request, + matches + }) => { + if (isActionDataRequest && request.method === "GET") { + return {}; + } + let matchesToLoad = loadRouteIds ? matches.filter((m) => loadRouteIds.includes(m.route.id)) : matches; + let results = await Promise.all(matchesToLoad.map((match) => match.resolve())); + return results.reduce((acc, result, i2) => Object.assign(acc, { + [matchesToLoad[i2].route.id]: result + }), {}); + }; + } + async function singleFetchAction(build, serverMode, staticHandler, request, handlerUrl, loadContext, handleError) { + try { + let handlerRequest = new Request(handlerUrl, { + method: request.method, + body: request.body, + headers: request.headers, + signal: request.signal, + ...request.body ? { + duplex: "half" + } : void 0 + }); + let result = await staticHandler.query(handlerRequest, { + requestContext: loadContext, + skipLoaderErrorBubbling: true, + unstable_dataStrategy: getSingleFetchDataStrategy({ + isActionDataRequest: true + }) + }); + if (responses.isResponse(result)) { + return { + result: getSingleFetchRedirect(result.status, result.headers, build.basename), + headers: result.headers, + status: SINGLE_FETCH_REDIRECT_STATUS + }; + } + let context = result; + let headers$1 = headers.getDocumentHeaders(build, context); + if (responses.isRedirectStatusCode(context.statusCode) && headers$1.has("Location")) { + return { + result: getSingleFetchRedirect(context.statusCode, headers$1, build.basename), + headers: headers$1, + status: SINGLE_FETCH_REDIRECT_STATUS + }; + } + if (context.errors) { + Object.values(context.errors).forEach((err) => { + if (!router.isRouteErrorResponse(err) || err.error) { + handleError(err); + } + }); + context.errors = errors.sanitizeErrors(context.errors, serverMode); + } + let singleFetchResult; + if (context.errors) { + singleFetchResult = { + error: Object.values(context.errors)[0] + }; + } else { + singleFetchResult = { + data: Object.values(context.actionData || {})[0] + }; + } + return { + result: singleFetchResult, + headers: headers$1, + status: context.statusCode + }; + } catch (error) { + handleError(error); + return { + result: { + error + }, + headers: new Headers(), + status: 500 + }; + } + } + async function singleFetchLoaders(build, serverMode, staticHandler, request, handlerUrl, loadContext, handleError) { + try { + var _URL$searchParams$get; + let handlerRequest = new Request(handlerUrl, { + headers: request.headers, + signal: request.signal + }); + let loadRouteIds = ((_URL$searchParams$get = new URL(request.url).searchParams.get("_routes")) === null || _URL$searchParams$get === void 0 ? void 0 : _URL$searchParams$get.split(",")) || void 0; + let result = await staticHandler.query(handlerRequest, { + requestContext: loadContext, + skipLoaderErrorBubbling: true, + unstable_dataStrategy: getSingleFetchDataStrategy({ + loadRouteIds + }) + }); + if (responses.isResponse(result)) { + return { + result: { + [SingleFetchRedirectSymbol]: getSingleFetchRedirect(result.status, result.headers, build.basename) + }, + headers: result.headers, + status: SINGLE_FETCH_REDIRECT_STATUS + }; + } + let context = result; + let headers$1 = headers.getDocumentHeaders(build, context); + if (responses.isRedirectStatusCode(context.statusCode) && headers$1.has("Location")) { + return { + result: { + [SingleFetchRedirectSymbol]: getSingleFetchRedirect(context.statusCode, headers$1, build.basename) + }, + headers: headers$1, + status: SINGLE_FETCH_REDIRECT_STATUS + }; + } + if (context.errors) { + Object.values(context.errors).forEach((err) => { + if (!router.isRouteErrorResponse(err) || err.error) { + handleError(err); + } + }); + context.errors = errors.sanitizeErrors(context.errors, serverMode); + } + let results = {}; + let loadedMatches = loadRouteIds ? context.matches.filter((m) => m.route.loader && loadRouteIds.includes(m.route.id)) : context.matches; + loadedMatches.forEach((m) => { + var _context$loaderData, _context$errors; + let data2 = (_context$loaderData = context.loaderData) === null || _context$loaderData === void 0 ? void 0 : _context$loaderData[m.route.id]; + let error = (_context$errors = context.errors) === null || _context$errors === void 0 ? void 0 : _context$errors[m.route.id]; + if (error !== void 0) { + results[m.route.id] = { + error + }; + } else if (data2 !== void 0) { + results[m.route.id] = { + data: data2 + }; + } + }); + return { + result: results, + headers: headers$1, + status: context.statusCode + }; + } catch (error) { + handleError(error); + return { + result: { + root: { + error + } + }, + headers: new Headers(), + status: 500 + }; + } + } + function getSingleFetchRedirect(status, headers2, basename) { + let redirect2 = headers2.get("Location"); + if (basename) { + redirect2 = router.stripBasename(redirect2, basename) || redirect2; + } + return { + redirect: redirect2, + status, + revalidate: ( + // Technically X-Remix-Revalidate isn't needed here - that was an implementation + // detail of ?_data requests as our way to tell the front end to revalidate when + // we didn't have a response body to include that information in. + // With single fetch, we tell the front end via this revalidate boolean field. + // However, we're respecting it for now because it may be something folks have + // used in their own responses + // TODO(v3): Consider removing or making this official public API + headers2.has("X-Remix-Revalidate") || headers2.has("Set-Cookie") + ), + reload: headers2.has("X-Remix-Reload-Document"), + replace: headers2.has("X-Remix-Replace") + }; + } + function encodeViaTurboStream(data2, requestSignal, streamTimeout, serverMode) { + let controller = new AbortController(); + let timeoutId = setTimeout(() => controller.abort(new Error("Server Timeout")), typeof streamTimeout === "number" ? streamTimeout : 4950); + requestSignal.addEventListener("abort", () => clearTimeout(timeoutId)); + return turboStream.encode(data2, { + signal: controller.signal, + plugins: [(value) => { + if (value instanceof Error) { + let { + name, + message, + stack + } = serverMode === mode.ServerMode.Production ? errors.sanitizeError(value, serverMode) : value; + return ["SanitizedError", name, message, stack]; + } + if (value instanceof router.UNSAFE_ErrorResponseImpl) { + let { + data: data3, + status, + statusText + } = value; + return ["ErrorResponse", data3, status, statusText]; + } + if (value && typeof value === "object" && SingleFetchRedirectSymbol in value) { + return ["SingleFetchRedirect", value[SingleFetchRedirectSymbol]]; + } + }], + postPlugins: [(value) => { + if (!value) + return; + if (typeof value !== "object") + return; + return ["SingleFetchClassInstance", Object.fromEntries(Object.entries(value))]; + }, () => ["SingleFetchFallback"]] + }); + } + function data(value, init) { + return router.unstable_data(value, init); + } + exports.SINGLE_FETCH_REDIRECT_STATUS = SINGLE_FETCH_REDIRECT_STATUS; + exports.SingleFetchRedirectSymbol = SingleFetchRedirectSymbol; + exports.data = data; + exports.encodeViaTurboStream = encodeViaTurboStream; + exports.getSingleFetchDataStrategy = getSingleFetchDataStrategy; + exports.getSingleFetchRedirect = getSingleFetchRedirect; + exports.singleFetchAction = singleFetchAction; + exports.singleFetchLoaders = singleFetchLoaders; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/entry.js +var require_entry = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/entry.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + function createEntryRouteModules(manifest) { + return Object.keys(manifest).reduce((memo, routeId) => { + memo[routeId] = manifest[routeId].module; + return memo; + }, {}); + } + exports.createEntryRouteModules = createEntryRouteModules; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/invariant.js +var require_invariant = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/invariant.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + function invariant2(value, message) { + if (value === false || value === null || typeof value === "undefined") { + console.error("The following error is a bug in Remix; please open an issue! https://github.com/remix-run/remix/issues/new"); + throw new Error(message); + } + } + exports["default"] = invariant2; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/routeMatching.js +var require_routeMatching = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/routeMatching.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var router = require_router_cjs(); + function matchServerRoutes(routes, pathname, basename) { + let matches = router.matchRoutes(routes, pathname, basename); + if (!matches) + return null; + return matches.map((match) => ({ + params: match.params, + pathname: match.pathname, + route: match.route + })); + } + exports.matchServerRoutes = matchServerRoutes; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/data.js +var require_data = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/data.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var responses = require_responses(); + async function callRouteAction({ + loadContext, + action, + params, + request, + routeId, + singleFetch + }) { + let result = await action({ + request: singleFetch ? stripRoutesParam(stripIndexParam(request)) : stripDataParam(stripIndexParam(request)), + context: loadContext, + params + }); + if (result === void 0) { + throw new Error(`You defined an action for route "${routeId}" but didn't return anything from your \`action\` function. Please return a value or \`null\`.`); + } + if (singleFetch) { + return result; + } + return responses.isResponse(result) ? result : responses.json(result); + } + async function callRouteLoader({ + loadContext, + loader, + params, + request, + routeId, + singleFetch + }) { + let result = await loader({ + request: singleFetch ? stripRoutesParam(stripIndexParam(request)) : stripDataParam(stripIndexParam(request)), + context: loadContext, + params + }); + if (result === void 0) { + throw new Error(`You defined a loader for route "${routeId}" but didn't return anything from your \`loader\` function. Please return a value or \`null\`.`); + } + if (responses.isDeferredData(result)) { + if (result.init && responses.isRedirectStatusCode(result.init.status || 200)) { + return responses.redirect(new Headers(result.init.headers).get("Location"), result.init); + } + return result; + } + if (singleFetch) { + return result; + } + return responses.isResponse(result) ? result : responses.json(result); + } + function stripIndexParam(request) { + let url = new URL(request.url); + let indexValues = url.searchParams.getAll("index"); + url.searchParams.delete("index"); + let indexValuesToKeep = []; + for (let indexValue of indexValues) { + if (indexValue) { + indexValuesToKeep.push(indexValue); + } + } + for (let toKeep of indexValuesToKeep) { + url.searchParams.append("index", toKeep); + } + let init = { + method: request.method, + body: request.body, + headers: request.headers, + signal: request.signal + }; + if (init.body) { + init.duplex = "half"; + } + return new Request(url.href, init); + } + function stripDataParam(request) { + let url = new URL(request.url); + url.searchParams.delete("_data"); + let init = { + method: request.method, + body: request.body, + headers: request.headers, + signal: request.signal + }; + if (init.body) { + init.duplex = "half"; + } + return new Request(url.href, init); + } + function stripRoutesParam(request) { + let url = new URL(request.url); + url.searchParams.delete("_routes"); + let init = { + method: request.method, + body: request.body, + headers: request.headers, + signal: request.signal + }; + if (init.body) { + init.duplex = "half"; + } + return new Request(url.href, init); + } + exports.callRouteAction = callRouteAction; + exports.callRouteLoader = callRouteLoader; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/routes.js +var require_routes = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/routes.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var data = require_data(); + function groupRoutesByParentId2(manifest) { + let routes = {}; + Object.values(manifest).forEach((route) => { + let parentId = route.parentId || ""; + if (!routes[parentId]) { + routes[parentId] = []; + } + routes[parentId].push(route); + }); + return routes; + } + function createRoutes(manifest, parentId = "", routesByParentId = groupRoutesByParentId2(manifest)) { + return (routesByParentId[parentId] || []).map((route) => ({ + ...route, + children: createRoutes(manifest, route.id, routesByParentId) + })); + } + function createStaticHandlerDataRoutes(manifest, future, parentId = "", routesByParentId = groupRoutesByParentId2(manifest)) { + return (routesByParentId[parentId] || []).map((route) => { + let commonRoute = { + // Always include root due to default boundaries + hasErrorBoundary: route.id === "root" || route.module.ErrorBoundary != null, + id: route.id, + path: route.path, + loader: route.module.loader ? ( + // Need to use RR's version here to permit the optional context even + // though we know it'll always be provided in remix + (args, dataStrategyCtx) => data.callRouteLoader({ + request: args.request, + params: args.params, + loadContext: args.context, + loader: route.module.loader, + routeId: route.id, + singleFetch: future.unstable_singleFetch === true + }) + ) : void 0, + action: route.module.action ? (args, dataStrategyCtx) => data.callRouteAction({ + request: args.request, + params: args.params, + loadContext: args.context, + action: route.module.action, + routeId: route.id, + singleFetch: future.unstable_singleFetch === true + }) : void 0, + handle: route.module.handle + }; + return route.index ? { + index: true, + ...commonRoute + } : { + caseSensitive: route.caseSensitive, + children: createStaticHandlerDataRoutes(manifest, future, route.id, routesByParentId), + ...commonRoute + }; + }); + } + exports.createRoutes = createRoutes; + exports.createStaticHandlerDataRoutes = createStaticHandlerDataRoutes; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/markup.js +var require_markup = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/markup.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var ESCAPE_LOOKUP2 = { + "&": "\\u0026", + ">": "\\u003e", + "<": "\\u003c", + "\u2028": "\\u2028", + "\u2029": "\\u2029" + }; + var ESCAPE_REGEX2 = /[&><\u2028\u2029]/g; + function escapeHtml2(html) { + return html.replace(ESCAPE_REGEX2, (match) => ESCAPE_LOOKUP2[match]); + } + exports.escapeHtml = escapeHtml2; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/serverHandoff.js +var require_serverHandoff = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/serverHandoff.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var markup = require_markup(); + function createServerHandoffString(serverHandoff) { + return markup.escapeHtml(JSON.stringify(serverHandoff)); + } + exports.createServerHandoffString = createServerHandoffString; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/dev.js +var require_dev = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/dev.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + async function broadcastDevReady(build, origin) { + origin ??= process.env.REMIX_DEV_ORIGIN; + if (!origin) + throw Error("Dev server origin not set"); + let url = new URL(origin); + url.pathname = "ping"; + let response = await fetch(url.href, { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify({ + buildHash: build.assets.version + }) + }).catch((error) => { + console.error(`Could not reach Remix dev server at ${url}`); + throw error; + }); + if (!response.ok) { + console.error(`Could not reach Remix dev server at ${url} (${response.status})`); + throw Error(await response.text()); + } + } + function logDevReady2(build) { + console.log(`[REMIX DEV] ${build.assets.version} ready`); + } + var globalDevServerHooksKey = "__remix_devServerHooks"; + function setDevServerHooks(devServerHooks) { + globalThis[globalDevServerHooksKey] = devServerHooks; + } + function getDevServerHooks() { + return globalThis[globalDevServerHooksKey]; + } + exports.broadcastDevReady = broadcastDevReady; + exports.getDevServerHooks = getDevServerHooks; + exports.logDevReady = logDevReady2; + exports.setDevServerHooks = setDevServerHooks; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/deprecations.js +var require_deprecations = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/deprecations.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + function resourceRouteJsonWarning(type, routeId) { + return `\u26A0\uFE0F REMIX FUTURE CHANGE: Resource routes will no longer be able to return raw JavaScript objects in v3 when Single Fetch becomes the default. You can prepare for this change at your convenience by wrapping the data returned from your \`${type}\` function in the \`${routeId}\` route with \`json()\`. For instructions on making this change see https://remix.run/docs/en/v2.9.2/guides/single-fetch#resource-routes`; + } + exports.resourceRouteJsonWarning = resourceRouteJsonWarning; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/server.js +var require_server = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/server.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var router = require_router_cjs(); + var entry = require_entry(); + var errors = require_errors(); + var headers = require_headers(); + var invariant2 = require_invariant(); + var mode = require_mode(); + var routeMatching = require_routeMatching(); + var routes = require_routes(); + var responses = require_responses(); + var serverHandoff = require_serverHandoff(); + var dev = require_dev(); + var singleFetch = require_single_fetch(); + var deprecations = require_deprecations(); + function derive(build, mode$1) { + var _build$future, _build$future2; + let routes$1 = routes.createRoutes(build.routes); + let dataRoutes = routes.createStaticHandlerDataRoutes(build.routes, build.future); + let serverMode = mode.isServerMode(mode$1) ? mode$1 : mode.ServerMode.Production; + let staticHandler = router.createStaticHandler(dataRoutes, { + basename: build.basename, + future: { + v7_relativeSplatPath: ((_build$future = build.future) === null || _build$future === void 0 ? void 0 : _build$future.v3_relativeSplatPath) === true, + v7_throwAbortReason: ((_build$future2 = build.future) === null || _build$future2 === void 0 ? void 0 : _build$future2.v3_throwAbortReason) === true + } + }); + let errorHandler2 = build.entry.module.handleError || ((error, { + request + }) => { + if (serverMode !== mode.ServerMode.Test && !request.signal.aborted) { + console.error( + // @ts-expect-error This is "private" from users but intended for internal use + router.isRouteErrorResponse(error) && error.error ? error.error : error + ); + } + }); + return { + routes: routes$1, + dataRoutes, + serverMode, + staticHandler, + errorHandler: errorHandler2 + }; + } + var createRequestHandler2 = (build, mode$1) => { + let _build; + let routes2; + let serverMode; + let staticHandler; + let errorHandler2; + return async function requestHandler(request, loadContext = {}) { + console.log("create request handler"); + _build = typeof build === "function" ? await build() : build; + mode$1 ??= _build.mode; + if (typeof build === "function") { + let derived = derive(_build, mode$1); + routes2 = derived.routes; + serverMode = derived.serverMode; + staticHandler = derived.staticHandler; + errorHandler2 = derived.errorHandler; + } else if (!routes2 || !serverMode || !staticHandler || !errorHandler2) { + let derived = derive(_build, mode$1); + routes2 = derived.routes; + serverMode = derived.serverMode; + staticHandler = derived.staticHandler; + errorHandler2 = derived.errorHandler; + } + let url = new URL(request.url); + let params = {}; + let handleError = (error) => { + if (mode$1 === mode.ServerMode.Development) { + var _getDevServerHooks, _getDevServerHooks$pr; + (_getDevServerHooks = dev.getDevServerHooks()) === null || _getDevServerHooks === void 0 ? void 0 : (_getDevServerHooks$pr = _getDevServerHooks.processRequestError) === null || _getDevServerHooks$pr === void 0 ? void 0 : _getDevServerHooks$pr.call(_getDevServerHooks, error); + } + errorHandler2(error, { + context: loadContext, + params, + request + }); + }; + let manifestUrl = `${_build.basename ?? "/"}/__manifest`.replace(/\/+/g, "/"); + if (url.pathname === manifestUrl) { + try { + let res = await handleManifestRequest(_build, routes2, url); + return res; + } catch (e2) { + handleError(e2); + return new Response("Unknown Server Error", { + status: 500 + }); + } + } + let matches = routeMatching.matchServerRoutes(routes2, url.pathname, _build.basename); + if (matches && matches.length > 0) { + Object.assign(params, matches[0].params); + } + let response; + if (url.searchParams.has("_data")) { + if (_build.future.unstable_singleFetch) { + handleError(new Error("Warning: Single fetch-enabled apps should not be making ?_data requests, this is likely to break in the future")); + } + let routeId = url.searchParams.get("_data"); + response = await handleDataRequest(serverMode, _build, staticHandler, routeId, request, loadContext, handleError); + if (_build.entry.module.handleDataRequest) { + response = await _build.entry.module.handleDataRequest(response, { + context: loadContext, + params, + request + }); + if (responses.isRedirectResponse(response)) { + response = createRemixRedirectResponse(response, _build.basename); + } + } + } else if (_build.future.unstable_singleFetch && url.pathname.endsWith(".data")) { + let handlerUrl = new URL(request.url); + handlerUrl.pathname = handlerUrl.pathname.replace(/\.data$/, "").replace(/^\/_root$/, "/"); + let singleFetchMatches = routeMatching.matchServerRoutes(routes2, handlerUrl.pathname, _build.basename); + response = await handleSingleFetchRequest(serverMode, _build, staticHandler, request, handlerUrl, loadContext, handleError); + if (_build.entry.module.handleDataRequest) { + response = await _build.entry.module.handleDataRequest(response, { + context: loadContext, + params: singleFetchMatches ? singleFetchMatches[0].params : {}, + request + }); + if (responses.isRedirectResponse(response)) { + let result = singleFetch.getSingleFetchRedirect(response.status, response.headers, _build.basename); + if (request.method === "GET") { + result = { + [singleFetch.SingleFetchRedirectSymbol]: result + }; + } + let headers2 = new Headers(response.headers); + headers2.set("Content-Type", "text/x-script"); + return new Response(singleFetch.encodeViaTurboStream(result, request.signal, _build.entry.module.streamTimeout, serverMode), { + status: singleFetch.SINGLE_FETCH_REDIRECT_STATUS, + headers: headers2 + }); + } + } + } else if (matches && matches[matches.length - 1].route.module.default == null && matches[matches.length - 1].route.module.ErrorBoundary == null) { + response = await handleResourceRequest(serverMode, _build, staticHandler, matches.slice(-1)[0].route.id, request, loadContext, handleError); + } else { + var _getDevServerHooks2, _getDevServerHooks2$g; + let criticalCss = mode$1 === mode.ServerMode.Development ? await ((_getDevServerHooks2 = dev.getDevServerHooks()) === null || _getDevServerHooks2 === void 0 ? void 0 : (_getDevServerHooks2$g = _getDevServerHooks2.getCriticalCss) === null || _getDevServerHooks2$g === void 0 ? void 0 : _getDevServerHooks2$g.call(_getDevServerHooks2, _build, url.pathname)) : void 0; + response = await handleDocumentRequest(serverMode, _build, staticHandler, request, loadContext, handleError, criticalCss); + } + if (request.method === "HEAD") { + return new Response(null, { + headers: response.headers, + status: response.status, + statusText: response.statusText + }); + } + return response; + }; + }; + async function handleManifestRequest(build, routes2, url) { + let patches = {}; + if (url.searchParams.has("p")) { + for (let path of url.searchParams.getAll("p")) { + let matches = routeMatching.matchServerRoutes(routes2, path, build.basename); + if (matches) { + for (let match of matches) { + let routeId = match.route.id; + patches[routeId] = build.assets.routes[routeId]; + } + } + } + return responses.json(patches, { + headers: { + "Cache-Control": "public, max-age=31536000, immutable" + } + }); + } + return new Response("Invalid Request", { + status: 400 + }); + } + async function handleDataRequest(serverMode, build, staticHandler, routeId, request, loadContext, handleError) { + try { + let response = await staticHandler.queryRoute(request, { + routeId, + requestContext: loadContext + }); + if (responses.isRedirectResponse(response)) { + return createRemixRedirectResponse(response, build.basename); + } + if (router.UNSAFE_DEFERRED_SYMBOL in response) { + let deferredData = response[router.UNSAFE_DEFERRED_SYMBOL]; + let body = responses.createDeferredReadableStream(deferredData, request.signal, serverMode); + let init = deferredData.init || {}; + let headers2 = new Headers(init.headers); + headers2.set("Content-Type", "text/remix-deferred"); + headers2.set("X-Remix-Response", "yes"); + init.headers = headers2; + return new Response(body, init); + } + response = safelySetHeader(response, "X-Remix-Response", "yes"); + return response; + } catch (error) { + if (responses.isResponse(error)) { + let response = safelySetHeader(error, "X-Remix-Catch", "yes"); + return response; + } + if (router.isRouteErrorResponse(error)) { + handleError(error); + return errorResponseToJson(error, serverMode); + } + let errorInstance = error instanceof Error || error instanceof DOMException ? error : new Error("Unexpected Server Error"); + handleError(errorInstance); + return router.json(errors.serializeError(errorInstance, serverMode), { + status: 500, + headers: { + "X-Remix-Error": "yes" + } + }); + } + } + async function handleSingleFetchRequest(serverMode, build, staticHandler, request, handlerUrl, loadContext, handleError) { + let { + result, + headers: headers2, + status + } = request.method !== "GET" ? await singleFetch.singleFetchAction(build, serverMode, staticHandler, request, handlerUrl, loadContext, handleError) : await singleFetch.singleFetchLoaders(build, serverMode, staticHandler, request, handlerUrl, loadContext, handleError); + let resultHeaders = new Headers(headers2); + resultHeaders.set("X-Remix-Response", "yes"); + if (status === 304) { + return new Response(null, { + status: 304, + headers: resultHeaders + }); + } + resultHeaders.set("Content-Type", "text/x-script"); + return new Response(singleFetch.encodeViaTurboStream(result, request.signal, build.entry.module.streamTimeout, serverMode), { + status: status || 200, + headers: resultHeaders + }); + } + async function handleDocumentRequest(serverMode, build, staticHandler, request, loadContext, handleError, criticalCss) { + let context; + try { + context = await staticHandler.query(request, { + requestContext: loadContext + }); + } catch (error) { + handleError(error); + return new Response(null, { + status: 500 + }); + } + if (responses.isResponse(context)) { + return context; + } + let headers$1 = headers.getDocumentHeaders(build, context); + if (context.statusCode === 304) { + return new Response(null, { + status: 304, + headers: headers$1 + }); + } + if (context.errors) { + Object.values(context.errors).forEach((err) => { + if (!router.isRouteErrorResponse(err) || err.error) { + handleError(err); + } + }); + context.errors = errors.sanitizeErrors(context.errors, serverMode); + } + let state = { + loaderData: context.loaderData, + actionData: context.actionData, + errors: errors.serializeErrors(context.errors, serverMode) + }; + let entryContext = { + manifest: build.assets, + routeModules: entry.createEntryRouteModules(build.routes), + staticHandlerContext: context, + criticalCss, + serverHandoffString: serverHandoff.createServerHandoffString({ + basename: build.basename, + criticalCss, + future: build.future, + isSpaMode: build.isSpaMode, + ...!build.future.unstable_singleFetch ? { + state + } : null + }), + ...build.future.unstable_singleFetch ? { + serverHandoffStream: singleFetch.encodeViaTurboStream(state, request.signal, build.entry.module.streamTimeout, serverMode), + renderMeta: {} + } : null, + future: build.future, + isSpaMode: build.isSpaMode, + serializeError: (err) => errors.serializeError(err, serverMode) + }; + let handleDocumentRequestFunction = build.entry.module.default; + try { + return await handleDocumentRequestFunction(request, context.statusCode, headers$1, entryContext, loadContext); + } catch (error) { + handleError(error); + let errorForSecondRender = error; + if (responses.isResponse(error)) { + try { + let data = await unwrapResponse(error); + errorForSecondRender = new router.UNSAFE_ErrorResponseImpl(error.status, error.statusText, data); + } catch (e2) { + } + } + context = router.getStaticContextFromError(staticHandler.dataRoutes, context, errorForSecondRender); + if (context.errors) { + context.errors = errors.sanitizeErrors(context.errors, serverMode); + } + let state2 = { + loaderData: context.loaderData, + actionData: context.actionData, + errors: errors.serializeErrors(context.errors, serverMode) + }; + entryContext = { + ...entryContext, + staticHandlerContext: context, + serverHandoffString: serverHandoff.createServerHandoffString({ + basename: build.basename, + future: build.future, + isSpaMode: build.isSpaMode, + ...!build.future.unstable_singleFetch ? { + state: state2 + } : null + }), + ...build.future.unstable_singleFetch ? { + serverHandoffStream: singleFetch.encodeViaTurboStream(state2, request.signal, build.entry.module.streamTimeout, serverMode), + renderMeta: {} + } : null + }; + try { + return await handleDocumentRequestFunction(request, context.statusCode, headers$1, entryContext, loadContext); + } catch (error2) { + handleError(error2); + return returnLastResortErrorResponse(error2, serverMode); + } + } + } + async function handleResourceRequest(serverMode, build, staticHandler, routeId, request, loadContext, handleError) { + try { + let response = await staticHandler.queryRoute(request, { + routeId, + requestContext: loadContext + }); + if (typeof response === "object" && response !== null) { + invariant2["default"](!(router.UNSAFE_DEFERRED_SYMBOL in response), `You cannot return a \`defer()\` response from a Resource Route. Did you forget to export a default UI component from the "${routeId}" route?`); + } + if (build.future.unstable_singleFetch && !responses.isResponse(response)) { + console.warn(deprecations.resourceRouteJsonWarning(request.method === "GET" ? "loader" : "action", routeId)); + response = responses.json(response); + } + invariant2["default"](responses.isResponse(response), "Expected a Response to be returned from queryRoute"); + return response; + } catch (error) { + if (responses.isResponse(error)) { + let response = safelySetHeader(error, "X-Remix-Catch", "yes"); + return response; + } + if (router.isRouteErrorResponse(error)) { + if (error) { + handleError(error); + } + return errorResponseToJson(error, serverMode); + } + handleError(error); + return returnLastResortErrorResponse(error, serverMode); + } + } + function errorResponseToJson(errorResponse, serverMode) { + return router.json(errors.serializeError( + // @ts-expect-error This is "private" from users but intended for internal use + errorResponse.error || new Error("Unexpected Server Error"), + serverMode + ), { + status: errorResponse.status, + statusText: errorResponse.statusText, + headers: { + "X-Remix-Error": "yes" + } + }); + } + function returnLastResortErrorResponse(error, serverMode) { + let message = "Unexpected Server Error"; + if (serverMode !== mode.ServerMode.Production) { + message += ` + +${String(error)}`; + } + return new Response(message, { + status: 500, + headers: { + "Content-Type": "text/plain" + } + }); + } + function unwrapResponse(response) { + let contentType = response.headers.get("Content-Type"); + return contentType && /\bapplication\/json\b/.test(contentType) ? response.body == null ? null : response.json() : response.text(); + } + function createRemixRedirectResponse(response, basename) { + let headers2 = new Headers(response.headers); + let redirectUrl = headers2.get("Location"); + headers2.set("X-Remix-Redirect", basename ? router.stripBasename(redirectUrl, basename) || redirectUrl : redirectUrl); + headers2.set("X-Remix-Status", String(response.status)); + headers2.delete("Location"); + if (response.headers.get("Set-Cookie") !== null) { + headers2.set("X-Remix-Revalidate", "yes"); + } + return new Response(null, { + status: 204, + headers: headers2 + }); + } + function safelySetHeader(response, name, value) { + let headers2 = new Headers(response.headers); + headers2.set(name, value); + return new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers: headers2, + duplex: response.body ? "half" : void 0 + }); + } + exports.createRequestHandler = createRequestHandler2; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/sessions.js +var require_sessions = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/sessions.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var cookies = require_cookies(); + var warnings = require_warnings(); + function flash(name) { + return `__flash_${name}__`; + } + var createSession = (initialData = {}, id = "") => { + let map = new Map(Object.entries(initialData)); + return { + get id() { + return id; + }, + get data() { + return Object.fromEntries(map); + }, + has(name) { + return map.has(name) || map.has(flash(name)); + }, + get(name) { + if (map.has(name)) + return map.get(name); + let flashName = flash(name); + if (map.has(flashName)) { + let value = map.get(flashName); + map.delete(flashName); + return value; + } + return void 0; + }, + set(name, value) { + map.set(name, value); + }, + flash(name, value) { + map.set(flash(name), value); + }, + unset(name) { + map.delete(name); + } + }; + }; + var isSession = (object) => { + return object != null && typeof object.id === "string" && typeof object.data !== "undefined" && typeof object.has === "function" && typeof object.get === "function" && typeof object.set === "function" && typeof object.flash === "function" && typeof object.unset === "function"; + }; + var createSessionStorageFactory = (createCookie) => ({ + cookie: cookieArg, + createData, + readData, + updateData, + deleteData + }) => { + let cookie = cookies.isCookie(cookieArg) ? cookieArg : createCookie((cookieArg === null || cookieArg === void 0 ? void 0 : cookieArg.name) || "__session", cookieArg); + warnOnceAboutSigningSessionCookie(cookie); + return { + async getSession(cookieHeader, options) { + let id = cookieHeader && await cookie.parse(cookieHeader, options); + let data = id && await readData(id); + return createSession(data || {}, id || ""); + }, + async commitSession(session, options) { + let { + id, + data + } = session; + let expires = (options === null || options === void 0 ? void 0 : options.maxAge) != null ? new Date(Date.now() + options.maxAge * 1e3) : (options === null || options === void 0 ? void 0 : options.expires) != null ? options.expires : cookie.expires; + if (id) { + await updateData(id, data, expires); + } else { + id = await createData(data, expires); + } + return cookie.serialize(id, options); + }, + async destroySession(session, options) { + await deleteData(session.id); + return cookie.serialize("", { + ...options, + maxAge: void 0, + expires: /* @__PURE__ */ new Date(0) + }); + } + }; + }; + function warnOnceAboutSigningSessionCookie(cookie) { + warnings.warnOnce(cookie.isSigned, `The "${cookie.name}" cookie is not signed, but session cookies should be signed to prevent tampering on the client before they are sent back to the server. See https://remix.run/utils/cookies#signing-cookies for more information.`); + } + exports.createSession = createSession; + exports.createSessionStorageFactory = createSessionStorageFactory; + exports.isSession = isSession; + exports.warnOnceAboutSigningSessionCookie = warnOnceAboutSigningSessionCookie; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/sessions/cookieStorage.js +var require_cookieStorage = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/sessions/cookieStorage.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var cookies = require_cookies(); + var sessions = require_sessions(); + var createCookieSessionStorageFactory = (createCookie) => ({ + cookie: cookieArg + } = {}) => { + let cookie = cookies.isCookie(cookieArg) ? cookieArg : createCookie((cookieArg === null || cookieArg === void 0 ? void 0 : cookieArg.name) || "__session", cookieArg); + sessions.warnOnceAboutSigningSessionCookie(cookie); + return { + async getSession(cookieHeader, options) { + return sessions.createSession(cookieHeader && await cookie.parse(cookieHeader, options) || {}); + }, + async commitSession(session, options) { + let serializedCookie = await cookie.serialize(session.data, options); + if (serializedCookie.length > 4096) { + throw new Error("Cookie length will exceed browser maximum. Length: " + serializedCookie.length); + } + return serializedCookie; + }, + async destroySession(_session, options) { + return cookie.serialize("", { + ...options, + maxAge: void 0, + expires: /* @__PURE__ */ new Date(0) + }); + } + }; + }; + exports.createCookieSessionStorageFactory = createCookieSessionStorageFactory; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/sessions/memoryStorage.js +var require_memoryStorage = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/sessions/memoryStorage.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var createMemorySessionStorageFactory = (createSessionStorage) => ({ + cookie + } = {}) => { + let map = /* @__PURE__ */ new Map(); + return createSessionStorage({ + cookie, + async createData(data, expires) { + let id = Math.random().toString(36).substring(2, 10); + map.set(id, { + data, + expires + }); + return id; + }, + async readData(id) { + if (map.has(id)) { + let { + data, + expires + } = map.get(id); + if (!expires || expires > /* @__PURE__ */ new Date()) { + return data; + } + if (expires) + map.delete(id); + } + return null; + }, + async updateData(id, data, expires) { + map.set(id, { + data, + expires + }); + }, + async deleteData(id) { + map.delete(id); + } + }); + }; + exports.createMemorySessionStorageFactory = createMemorySessionStorageFactory; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/upload/errors.js +var require_errors2 = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/upload/errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var MaxPartSizeExceededError = class extends Error { + constructor(field, maxBytes) { + super(`Field "${field}" exceeded upload size of ${maxBytes} bytes.`); + this.field = field; + this.maxBytes = maxBytes; + } + }; + exports.MaxPartSizeExceededError = MaxPartSizeExceededError; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/upload/memoryUploadHandler.js +var require_memoryUploadHandler = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/upload/memoryUploadHandler.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var errors = require_errors2(); + function createMemoryUploadHandler({ + filter, + maxPartSize = 3e6 + } = {}) { + return async ({ + filename, + contentType, + name, + data + }) => { + if (filter && !await filter({ + filename, + contentType, + name + })) { + return void 0; + } + let size = 0; + let chunks = []; + for await (let chunk of data) { + size += chunk.byteLength; + if (size > maxPartSize) { + throw new errors.MaxPartSizeExceededError(name, maxPartSize); + } + chunks.push(chunk); + } + if (typeof filename === "string") { + return new File(chunks, filename, { + type: contentType + }); + } + return await new Blob(chunks, { + type: contentType + }).text(); + }; + } + exports.createMemoryUploadHandler = createMemoryUploadHandler; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/index.js +var require_dist = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+server-runtime@2.12.0_typescript@5.6.2/node_modules/@remix-run/server-runtime/dist/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var cookies = require_cookies(); + var formData = require_formData(); + var responses = require_responses(); + var singleFetch = require_single_fetch(); + var server = require_server(); + var sessions = require_sessions(); + var cookieStorage = require_cookieStorage(); + var memoryStorage = require_memoryStorage(); + var memoryUploadHandler = require_memoryUploadHandler(); + var errors = require_errors2(); + var dev = require_dev(); + exports.createCookieFactory = cookies.createCookieFactory; + exports.isCookie = cookies.isCookie; + exports.unstable_composeUploadHandlers = formData.composeUploadHandlers; + exports.unstable_parseMultipartFormData = formData.parseMultipartFormData; + exports.defer = responses.defer; + exports.json = responses.json; + exports.redirect = responses.redirect; + exports.redirectDocument = responses.redirectDocument; + exports.replace = responses.replace; + exports.UNSAFE_SingleFetchRedirectSymbol = singleFetch.SingleFetchRedirectSymbol; + exports.unstable_data = singleFetch.data; + exports.createRequestHandler = server.createRequestHandler; + exports.createSession = sessions.createSession; + exports.createSessionStorageFactory = sessions.createSessionStorageFactory; + exports.isSession = sessions.isSession; + exports.createCookieSessionStorageFactory = cookieStorage.createCookieSessionStorageFactory; + exports.createMemorySessionStorageFactory = memoryStorage.createMemorySessionStorageFactory; + exports.unstable_createMemoryUploadHandler = memoryUploadHandler.createMemoryUploadHandler; + exports.MaxPartSizeExceededError = errors.MaxPartSizeExceededError; + exports.broadcastDevReady = dev.broadcastDevReady; + exports.logDevReady = dev.logDevReady; + exports.unstable_setDevServerHooks = dev.setDevServerHooks; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+cloudflare@2.12.0_@cloudflare+workers-types@4.20240909.0_typescript@5.6.2/node_modules/@remix-run/cloudflare/dist/crypto.js +var require_crypto = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+cloudflare@2.12.0_@cloudflare+workers-types@4.20240909.0_typescript@5.6.2/node_modules/@remix-run/cloudflare/dist/crypto.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var encoder = new TextEncoder(); + var sign = async (value, secret) => { + let key = await createKey(secret, ["sign"]); + let data = encoder.encode(value); + let signature = await crypto.subtle.sign("HMAC", key, data); + let hash = btoa(String.fromCharCode(...new Uint8Array(signature))).replace(/=+$/, ""); + return value + "." + hash; + }; + var unsign = async (signed, secret) => { + let index = signed.lastIndexOf("."); + let value = signed.slice(0, index); + let hash = signed.slice(index + 1); + let key = await createKey(secret, ["verify"]); + let data = encoder.encode(value); + let signature = byteStringToUint8Array(atob(hash)); + let valid = await crypto.subtle.verify("HMAC", key, signature, data); + return valid ? value : false; + }; + async function createKey(secret, usages) { + let key = await crypto.subtle.importKey("raw", encoder.encode(secret), { + name: "HMAC", + hash: "SHA-256" + }, false, usages); + return key; + } + function byteStringToUint8Array(byteString) { + let array = new Uint8Array(byteString.length); + for (let i2 = 0; i2 < byteString.length; i2++) { + array[i2] = byteString.charCodeAt(i2); + } + return array; + } + exports.sign = sign; + exports.unsign = unsign; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+cloudflare@2.12.0_@cloudflare+workers-types@4.20240909.0_typescript@5.6.2/node_modules/@remix-run/cloudflare/dist/implementations.js +var require_implementations = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+cloudflare@2.12.0_@cloudflare+workers-types@4.20240909.0_typescript@5.6.2/node_modules/@remix-run/cloudflare/dist/implementations.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var serverRuntime = require_dist(); + var crypto2 = require_crypto(); + var createCookie = serverRuntime.createCookieFactory({ + sign: crypto2.sign, + unsign: crypto2.unsign + }); + var createCookieSessionStorage2 = serverRuntime.createCookieSessionStorageFactory(createCookie); + var createSessionStorage = serverRuntime.createSessionStorageFactory(createCookie); + var createMemorySessionStorage = serverRuntime.createMemorySessionStorageFactory(createSessionStorage); + exports.createCookie = createCookie; + exports.createCookieSessionStorage = createCookieSessionStorage2; + exports.createMemorySessionStorage = createMemorySessionStorage; + exports.createSessionStorage = createSessionStorage; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+cloudflare@2.12.0_@cloudflare+workers-types@4.20240909.0_typescript@5.6.2/node_modules/@remix-run/cloudflare/dist/sessions/workersKVStorage.js +var require_workersKVStorage = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+cloudflare@2.12.0_@cloudflare+workers-types@4.20240909.0_typescript@5.6.2/node_modules/@remix-run/cloudflare/dist/sessions/workersKVStorage.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var implementations = require_implementations(); + function createWorkersKVSessionStorage2({ + cookie, + kv + }) { + return implementations.createSessionStorage({ + cookie, + async createData(data, expires) { + while (true) { + let randomBytes = new Uint8Array(8); + crypto.getRandomValues(randomBytes); + let id = [...randomBytes].map((x) => x.toString(16).padStart(2, "0")).join(""); + if (await kv.get(id, "json")) { + continue; + } + await kv.put(id, JSON.stringify(data), { + expiration: expires ? Math.round(expires.getTime() / 1e3) : void 0 + }); + return id; + } + }, + async readData(id) { + let session = await kv.get(id); + if (!session) { + return null; + } + return JSON.parse(session); + }, + async updateData(id, data, expires) { + await kv.put(id, JSON.stringify(data), { + expiration: expires ? Math.round(expires.getTime() / 1e3) : void 0 + }); + }, + async deleteData(id) { + await kv.delete(id); + } + }); + } + exports.createWorkersKVSessionStorage = createWorkersKVSessionStorage2; + } +}); + +// ../../../node_modules/.pnpm/@remix-run+cloudflare@2.12.0_@cloudflare+workers-types@4.20240909.0_typescript@5.6.2/node_modules/@remix-run/cloudflare/dist/index.js +var require_dist2 = __commonJS({ + "../../../node_modules/.pnpm/@remix-run+cloudflare@2.12.0_@cloudflare+workers-types@4.20240909.0_typescript@5.6.2/node_modules/@remix-run/cloudflare/dist/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var workersKVStorage = require_workersKVStorage(); + var implementations = require_implementations(); + var serverRuntime = require_dist(); + exports.createWorkersKVSessionStorage = workersKVStorage.createWorkersKVSessionStorage; + exports.createCookie = implementations.createCookie; + exports.createCookieSessionStorage = implementations.createCookieSessionStorage; + exports.createMemorySessionStorage = implementations.createMemorySessionStorage; + exports.createSessionStorage = implementations.createSessionStorage; + Object.defineProperty(exports, "MaxPartSizeExceededError", { + enumerable: true, + get: function() { + return serverRuntime.MaxPartSizeExceededError; + } + }); + Object.defineProperty(exports, "broadcastDevReady", { + enumerable: true, + get: function() { + return serverRuntime.broadcastDevReady; + } + }); + Object.defineProperty(exports, "createRequestHandler", { + enumerable: true, + get: function() { + return serverRuntime.createRequestHandler; + } + }); + Object.defineProperty(exports, "createSession", { + enumerable: true, + get: function() { + return serverRuntime.createSession; + } + }); + Object.defineProperty(exports, "defer", { + enumerable: true, + get: function() { + return serverRuntime.defer; + } + }); + Object.defineProperty(exports, "isCookie", { + enumerable: true, + get: function() { + return serverRuntime.isCookie; + } + }); + Object.defineProperty(exports, "isSession", { + enumerable: true, + get: function() { + return serverRuntime.isSession; + } + }); + Object.defineProperty(exports, "json", { + enumerable: true, + get: function() { + return serverRuntime.json; + } + }); + Object.defineProperty(exports, "logDevReady", { + enumerable: true, + get: function() { + return serverRuntime.logDevReady; + } + }); + Object.defineProperty(exports, "redirect", { + enumerable: true, + get: function() { + return serverRuntime.redirect; + } + }); + Object.defineProperty(exports, "redirectDocument", { + enumerable: true, + get: function() { + return serverRuntime.redirectDocument; + } + }); + Object.defineProperty(exports, "replace", { + enumerable: true, + get: function() { + return serverRuntime.replace; + } + }); + Object.defineProperty(exports, "unstable_composeUploadHandlers", { + enumerable: true, + get: function() { + return serverRuntime.unstable_composeUploadHandlers; + } + }); + Object.defineProperty(exports, "unstable_createMemoryUploadHandler", { + enumerable: true, + get: function() { + return serverRuntime.unstable_createMemoryUploadHandler; + } + }); + Object.defineProperty(exports, "unstable_data", { + enumerable: true, + get: function() { + return serverRuntime.unstable_data; + } + }); + Object.defineProperty(exports, "unstable_parseMultipartFormData", { + enumerable: true, + get: function() { + return serverRuntime.unstable_parseMultipartFormData; + } + }); + } +}); + +// ../../../node_modules/.pnpm/timestring@6.0.0/node_modules/timestring/index.js +var require_timestring = __commonJS({ + "../../../node_modules/.pnpm/timestring@6.0.0/node_modules/timestring/index.js"(exports, module) { + module.exports = parseTimestring; + var DEFAULT_OPTS = { + hoursPerDay: 24, + daysPerWeek: 7, + weeksPerMonth: 4, + monthsPerYear: 12, + daysPerYear: 365.25 + }; + var UNIT_MAP = { + ms: ["ms", "milli", "millisecond", "milliseconds"], + s: ["s", "sec", "secs", "second", "seconds"], + m: ["m", "min", "mins", "minute", "minutes"], + h: ["h", "hr", "hrs", "hour", "hours"], + d: ["d", "day", "days"], + w: ["w", "week", "weeks"], + mth: ["mon", "mth", "mths", "month", "months"], + y: ["y", "yr", "yrs", "year", "years"] + }; + function parseTimestring(string, returnUnit, opts) { + opts = Object.assign({}, DEFAULT_OPTS, opts || {}); + let totalSeconds = 0; + let unitValues = getUnitValues(opts); + let groups = string.toLowerCase().replace(/[^.\w+-]+/g, "").match(/[-+]?[0-9.]+[a-z]+/g); + if (groups === null) { + throw new Error(`The string [${string}] could not be parsed by timestring`); + } + groups.forEach((group) => { + let value = group.match(/[0-9.]+/g)[0]; + let unit = group.match(/[a-z]+/g)[0]; + totalSeconds += getSeconds(value, unit, unitValues); + }); + if (returnUnit) { + return convert(totalSeconds, returnUnit, unitValues); + } + return totalSeconds; + } + function getUnitValues(opts) { + let unitValues = { + ms: 1e-3, + s: 1, + m: 60, + h: 3600 + }; + unitValues.d = opts.hoursPerDay * unitValues.h; + unitValues.w = opts.daysPerWeek * unitValues.d; + unitValues.mth = opts.daysPerYear / opts.monthsPerYear * unitValues.d; + unitValues.y = opts.daysPerYear * unitValues.d; + return unitValues; + } + function getUnitKey(unit) { + for (let key of Object.keys(UNIT_MAP)) { + if (UNIT_MAP[key].indexOf(unit) > -1) { + return key; + } + } + throw new Error(`The unit [${unit}] is not supported by timestring`); + } + function getSeconds(value, unit, unitValues) { + return value * unitValues[getUnitKey(unit)]; + } + function convert(value, unit, unitValues) { + return value / unitValues[getUnitKey(unit)]; + } + } +}); + +// ../../../node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.development.js +var require_react_development = __commonJS({ + "../../../node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.development.js"(exports, module) { + "use strict"; + if (true) { + (function() { + "use strict"; + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); + } + var ReactVersion = "18.3.1"; + var REACT_ELEMENT_TYPE = Symbol.for("react.element"); + var REACT_PORTAL_TYPE = Symbol.for("react.portal"); + var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); + var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); + var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); + var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); + var REACT_CONTEXT_TYPE = Symbol.for("react.context"); + var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); + var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); + var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); + var REACT_MEMO_TYPE = Symbol.for("react.memo"); + var REACT_LAZY_TYPE = Symbol.for("react.lazy"); + var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); + var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = "@@iterator"; + function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== "object") { + return null; + } + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === "function") { + return maybeIterator; + } + return null; + } + var ReactCurrentDispatcher = { + /** + * @internal + * @type {ReactComponent} + */ + current: null + }; + var ReactCurrentBatchConfig = { + transition: null + }; + var ReactCurrentActQueue = { + current: null, + // Used to reproduce behavior of `batchedUpdates` in legacy mode. + isBatchingLegacy: false, + didScheduleLegacyUpdate: false + }; + var ReactCurrentOwner = { + /** + * @internal + * @type {ReactComponent} + */ + current: null + }; + var ReactDebugCurrentFrame = {}; + var currentExtraStackFrame = null; + function setExtraStackFrame(stack) { + { + currentExtraStackFrame = stack; + } + } + { + ReactDebugCurrentFrame.setExtraStackFrame = function(stack) { + { + currentExtraStackFrame = stack; + } + }; + ReactDebugCurrentFrame.getCurrentStack = null; + ReactDebugCurrentFrame.getStackAddendum = function() { + var stack = ""; + if (currentExtraStackFrame) { + stack += currentExtraStackFrame; + } + var impl = ReactDebugCurrentFrame.getCurrentStack; + if (impl) { + stack += impl() || ""; + } + return stack; + }; + } + var enableScopeAPI = false; + var enableCacheElement = false; + var enableTransitionTracing = false; + var enableLegacyHidden = false; + var enableDebugTracing = false; + var ReactSharedInternals = { + ReactCurrentDispatcher, + ReactCurrentBatchConfig, + ReactCurrentOwner + }; + { + ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; + ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; + } + function warn(format) { + { + { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + printWarning("warn", format, args); + } + } + } + function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + printWarning("error", format, args); + } + } + } + function printWarning(level, format, args) { + { + var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame2.getStackAddendum(); + if (stack !== "") { + format += "%s"; + args = args.concat([stack]); + } + var argsWithFormat = args.map(function(item) { + return String(item); + }); + argsWithFormat.unshift("Warning: " + format); + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + } + var didWarnStateUpdateForUnmountedComponent = {}; + function warnNoop(publicInstance, callerName) { + { + var _constructor = publicInstance.constructor; + var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass"; + var warningKey = componentName + "." + callerName; + if (didWarnStateUpdateForUnmountedComponent[warningKey]) { + return; + } + error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName); + didWarnStateUpdateForUnmountedComponent[warningKey] = true; + } + } + var ReactNoopUpdateQueue = { + /** + * Checks whether or not this composite component is mounted. + * @param {ReactClass} publicInstance The instance we want to test. + * @return {boolean} True if mounted, false otherwise. + * @protected + * @final + */ + isMounted: function(publicInstance) { + return false; + }, + /** + * Forces an update. This should only be invoked when it is known with + * certainty that we are **not** in a DOM transaction. + * + * You may want to call this when you know that some deeper aspect of the + * component's state has changed but `setState` was not called. + * + * This will not invoke `shouldComponentUpdate`, but it will invoke + * `componentWillUpdate` and `componentDidUpdate`. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {?function} callback Called after component is updated. + * @param {?string} callerName name of the calling function in the public API. + * @internal + */ + enqueueForceUpdate: function(publicInstance, callback, callerName) { + warnNoop(publicInstance, "forceUpdate"); + }, + /** + * Replaces all of the state. Always use this or `setState` to mutate state. + * You should treat `this.state` as immutable. + * + * There is no guarantee that `this.state` will be immediately updated, so + * accessing `this.state` after calling this method may return the old value. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} completeState Next state. + * @param {?function} callback Called after component is updated. + * @param {?string} callerName name of the calling function in the public API. + * @internal + */ + enqueueReplaceState: function(publicInstance, completeState, callback, callerName) { + warnNoop(publicInstance, "replaceState"); + }, + /** + * Sets a subset of the state. This only exists because _pendingState is + * internal. This provides a merging strategy that is not available to deep + * properties which is confusing. TODO: Expose pendingState or don't use it + * during the merge. + * + * @param {ReactClass} publicInstance The instance that should rerender. + * @param {object} partialState Next partial state to be merged with state. + * @param {?function} callback Called after component is updated. + * @param {?string} Name of the calling function in the public API. + * @internal + */ + enqueueSetState: function(publicInstance, partialState, callback, callerName) { + warnNoop(publicInstance, "setState"); + } + }; + var assign = Object.assign; + var emptyObject = {}; + { + Object.freeze(emptyObject); + } + function Component2(props, context, updater) { + this.props = props; + this.context = context; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + Component2.prototype.isReactComponent = {}; + Component2.prototype.setState = function(partialState, callback) { + if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null) { + throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables."); + } + this.updater.enqueueSetState(this, partialState, callback, "setState"); + }; + Component2.prototype.forceUpdate = function(callback) { + this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); + }; + { + var deprecatedAPIs = { + isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."], + replaceState: ["replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."] + }; + var defineDeprecationWarning = function(methodName, info) { + Object.defineProperty(Component2.prototype, methodName, { + get: function() { + warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]); + return void 0; + } + }); + }; + for (var fnName in deprecatedAPIs) { + if (deprecatedAPIs.hasOwnProperty(fnName)) { + defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); + } + } + } + function ComponentDummy() { + } + ComponentDummy.prototype = Component2.prototype; + function PureComponent(props, context, updater) { + this.props = props; + this.context = context; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); + pureComponentPrototype.constructor = PureComponent; + assign(pureComponentPrototype, Component2.prototype); + pureComponentPrototype.isPureReactComponent = true; + function createRef() { + var refObject = { + current: null + }; + { + Object.seal(refObject); + } + return refObject; + } + var isArrayImpl = Array.isArray; + function isArray(a2) { + return isArrayImpl(a2); + } + function typeName(value) { + { + var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; + return type; + } + } + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e2) { + return true; + } + } + } + function testStringCoercion(value) { + return "" + value; + } + function checkKeyStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); + return testStringCoercion(value); + } + } + } + function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + if (displayName) { + return displayName; + } + var functionName = innerType.displayName || innerType.name || ""; + return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; + } + function getContextName(type) { + return type.displayName || "Context"; + } + function getComponentNameFromType(type) { + if (type == null) { + return null; + } + { + if (typeof type.tag === "number") { + error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); + } + } + if (typeof type === "function") { + return type.displayName || type.name || null; + } + if (typeof type === "string") { + return type; + } + switch (type) { + case REACT_FRAGMENT_TYPE: + return "Fragment"; + case REACT_PORTAL_TYPE: + return "Portal"; + case REACT_PROFILER_TYPE: + return "Profiler"; + case REACT_STRICT_MODE_TYPE: + return "StrictMode"; + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + } + if (typeof type === "object") { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + ".Consumer"; + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + ".Provider"; + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, "ForwardRef"); + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + if (outerName !== null) { + return outerName; + } + return getComponentNameFromType(type.type) || "Memo"; + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } + } + } + return null; + } + var hasOwnProperty = Object.prototype.hasOwnProperty; + var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true + }; + var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; + { + didWarnAboutStringRefs = {}; + } + function hasValidRef(config) { + { + if (hasOwnProperty.call(config, "ref")) { + var getter = Object.getOwnPropertyDescriptor(config, "ref").get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.ref !== void 0; + } + function hasValidKey(config) { + { + if (hasOwnProperty.call(config, "key")) { + var getter = Object.getOwnPropertyDescriptor(config, "key").get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.key !== void 0; + } + function defineKeyPropWarningGetter(props, displayName) { + var warnAboutAccessingKey = function() { + { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); + } + } + }; + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, "key", { + get: warnAboutAccessingKey, + configurable: true + }); + } + function defineRefPropWarningGetter(props, displayName) { + var warnAboutAccessingRef = function() { + { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); + } + } + }; + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, "ref", { + get: warnAboutAccessingRef, + configurable: true + }); + } + function warnIfStringRefCannotBeAutoConverted(config) { + { + if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { + var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); + if (!didWarnAboutStringRefs[componentName]) { + error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); + didWarnAboutStringRefs[componentName] = true; + } + } + } + } + var ReactElement = function(type, key, ref, self2, source, owner, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type, + key, + ref, + props, + // Record the component responsible for creating this element. + _owner: owner + }; + { + element._store = {}; + Object.defineProperty(element._store, "validated", { + configurable: false, + enumerable: false, + writable: true, + value: false + }); + Object.defineProperty(element, "_self", { + configurable: false, + enumerable: false, + writable: false, + value: self2 + }); + Object.defineProperty(element, "_source", { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } + } + return element; + }; + function createElement9(type, config, children) { + var propName; + var props = {}; + var key = null; + var ref = null; + var self2 = null; + var source = null; + if (config != null) { + if (hasValidRef(config)) { + ref = config.ref; + { + warnIfStringRefCannotBeAutoConverted(config); + } + } + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + key = "" + config.key; + } + self2 = config.__self === void 0 ? null : config.__self; + source = config.__source === void 0 ? null : config.__source; + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; + } + } + } + var childrenLength = arguments.length - 2; + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + for (var i2 = 0; i2 < childrenLength; i2++) { + childArray[i2] = arguments[i2 + 2]; + } + { + if (Object.freeze) { + Object.freeze(childArray); + } + } + props.children = childArray; + } + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + for (propName in defaultProps) { + if (props[propName] === void 0) { + props[propName] = defaultProps[propName]; + } + } + } + { + if (key || ref) { + var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type; + if (key) { + defineKeyPropWarningGetter(props, displayName); + } + if (ref) { + defineRefPropWarningGetter(props, displayName); + } + } + } + return ReactElement(type, key, ref, self2, source, ReactCurrentOwner.current, props); + } + function cloneAndReplaceKey(oldElement, newKey) { + var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); + return newElement; + } + function cloneElement(element, config, children) { + if (element === null || element === void 0) { + throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); + } + var propName; + var props = assign({}, element.props); + var key = element.key; + var ref = element.ref; + var self2 = element._self; + var source = element._source; + var owner = element._owner; + if (config != null) { + if (hasValidRef(config)) { + ref = config.ref; + owner = ReactCurrentOwner.current; + } + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + key = "" + config.key; + } + var defaultProps; + if (element.type && element.type.defaultProps) { + defaultProps = element.type.defaultProps; + } + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + if (config[propName] === void 0 && defaultProps !== void 0) { + props[propName] = defaultProps[propName]; + } else { + props[propName] = config[propName]; + } + } + } + } + var childrenLength = arguments.length - 2; + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + for (var i2 = 0; i2 < childrenLength; i2++) { + childArray[i2] = arguments[i2 + 2]; + } + props.children = childArray; + } + return ReactElement(element.type, key, ref, self2, source, owner, props); + } + function isValidElement(object) { + return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } + var SEPARATOR = "."; + var SUBSEPARATOR = ":"; + function escape2(key) { + var escapeRegex = /[=:]/g; + var escaperLookup = { + "=": "=0", + ":": "=2" + }; + var escapedString = key.replace(escapeRegex, function(match) { + return escaperLookup[match]; + }); + return "$" + escapedString; + } + var didWarnAboutMaps = false; + var userProvidedKeyEscapeRegex = /\/+/g; + function escapeUserProvidedKey(text) { + return text.replace(userProvidedKeyEscapeRegex, "$&/"); + } + function getElementKey(element, index) { + if (typeof element === "object" && element !== null && element.key != null) { + { + checkKeyStringCoercion(element.key); + } + return escape2("" + element.key); + } + return index.toString(36); + } + function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { + var type = typeof children; + if (type === "undefined" || type === "boolean") { + children = null; + } + var invokeCallback = false; + if (children === null) { + invokeCallback = true; + } else { + switch (type) { + case "string": + case "number": + invokeCallback = true; + break; + case "object": + switch (children.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + invokeCallback = true; + } + } + } + if (invokeCallback) { + var _child = children; + var mappedChild = callback(_child); + var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; + if (isArray(mappedChild)) { + var escapedChildKey = ""; + if (childKey != null) { + escapedChildKey = escapeUserProvidedKey(childKey) + "/"; + } + mapIntoArray(mappedChild, array, escapedChildKey, "", function(c2) { + return c2; + }); + } else if (mappedChild != null) { + if (isValidElement(mappedChild)) { + { + if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { + checkKeyStringCoercion(mappedChild.key); + } + } + mappedChild = cloneAndReplaceKey( + mappedChild, + // Keep both the (mapped) and old keys if they differ, just as + // traverseAllChildren used to do for objects as children + escapedPrefix + // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key + (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? ( + // $FlowFixMe Flow incorrectly thinks existing element's key can be a number + // eslint-disable-next-line react-internal/safe-string-coercion + escapeUserProvidedKey("" + mappedChild.key) + "/" + ) : "") + childKey + ); + } + array.push(mappedChild); + } + return 1; + } + var child; + var nextName; + var subtreeCount = 0; + var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR; + if (isArray(children)) { + for (var i2 = 0; i2 < children.length; i2++) { + child = children[i2]; + nextName = nextNamePrefix + getElementKey(child, i2); + subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); + } + } else { + var iteratorFn = getIteratorFn(children); + if (typeof iteratorFn === "function") { + var iterableChildren = children; + { + if (iteratorFn === iterableChildren.entries) { + if (!didWarnAboutMaps) { + warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."); + } + didWarnAboutMaps = true; + } + } + var iterator = iteratorFn.call(iterableChildren); + var step; + var ii = 0; + while (!(step = iterator.next()).done) { + child = step.value; + nextName = nextNamePrefix + getElementKey(child, ii++); + subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); + } + } else if (type === "object") { + var childrenString = String(children); + throw new Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). If you meant to render a collection of children, use an array instead."); + } + } + return subtreeCount; + } + function mapChildren(children, func, context) { + if (children == null) { + return children; + } + var result = []; + var count = 0; + mapIntoArray(children, result, "", "", function(child) { + return func.call(context, child, count++); + }); + return result; + } + function countChildren(children) { + var n2 = 0; + mapChildren(children, function() { + n2++; + }); + return n2; + } + function forEachChildren(children, forEachFunc, forEachContext) { + mapChildren(children, function() { + forEachFunc.apply(this, arguments); + }, forEachContext); + } + function toArray(children) { + return mapChildren(children, function(child) { + return child; + }) || []; + } + function onlyChild(children) { + if (!isValidElement(children)) { + throw new Error("React.Children.only expected to receive a single React element child."); + } + return children; + } + function createContext3(defaultValue) { + var context = { + $$typeof: REACT_CONTEXT_TYPE, + // As a workaround to support multiple concurrent renderers, we categorize + // some renderers as primary and others as secondary. We only expect + // there to be two concurrent renderers at most: React Native (primary) and + // Fabric (secondary); React DOM (primary) and React ART (secondary). + // Secondary renderers store their context values on separate fields. + _currentValue: defaultValue, + _currentValue2: defaultValue, + // Used to track how many concurrent renderers this context currently + // supports within in a single renderer. Such as parallel server rendering. + _threadCount: 0, + // These are circular + Provider: null, + Consumer: null, + // Add these to use same hidden class in VM as ServerContext + _defaultValue: null, + _globalName: null + }; + context.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context + }; + var hasWarnedAboutUsingNestedContextConsumers = false; + var hasWarnedAboutUsingConsumerProvider = false; + var hasWarnedAboutDisplayNameOnConsumer = false; + { + var Consumer = { + $$typeof: REACT_CONTEXT_TYPE, + _context: context + }; + Object.defineProperties(Consumer, { + Provider: { + get: function() { + if (!hasWarnedAboutUsingConsumerProvider) { + hasWarnedAboutUsingConsumerProvider = true; + error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); + } + return context.Provider; + }, + set: function(_Provider) { + context.Provider = _Provider; + } + }, + _currentValue: { + get: function() { + return context._currentValue; + }, + set: function(_currentValue) { + context._currentValue = _currentValue; + } + }, + _currentValue2: { + get: function() { + return context._currentValue2; + }, + set: function(_currentValue2) { + context._currentValue2 = _currentValue2; + } + }, + _threadCount: { + get: function() { + return context._threadCount; + }, + set: function(_threadCount) { + context._threadCount = _threadCount; + } + }, + Consumer: { + get: function() { + if (!hasWarnedAboutUsingNestedContextConsumers) { + hasWarnedAboutUsingNestedContextConsumers = true; + error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); + } + return context.Consumer; + } + }, + displayName: { + get: function() { + return context.displayName; + }, + set: function(displayName) { + if (!hasWarnedAboutDisplayNameOnConsumer) { + warn("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName); + hasWarnedAboutDisplayNameOnConsumer = true; + } + } + } + }); + context.Consumer = Consumer; + } + { + context._currentRenderer = null; + context._currentRenderer2 = null; + } + return context; + } + var Uninitialized = -1; + var Pending = 0; + var Resolved = 1; + var Rejected = 2; + function lazyInitializer(payload) { + if (payload._status === Uninitialized) { + var ctor = payload._result; + var thenable = ctor(); + thenable.then(function(moduleObject2) { + if (payload._status === Pending || payload._status === Uninitialized) { + var resolved = payload; + resolved._status = Resolved; + resolved._result = moduleObject2; + } + }, function(error2) { + if (payload._status === Pending || payload._status === Uninitialized) { + var rejected = payload; + rejected._status = Rejected; + rejected._result = error2; + } + }); + if (payload._status === Uninitialized) { + var pending = payload; + pending._status = Pending; + pending._result = thenable; + } + } + if (payload._status === Resolved) { + var moduleObject = payload._result; + { + if (moduleObject === void 0) { + error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?", moduleObject); + } + } + { + if (!("default" in moduleObject)) { + error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); + } + } + return moduleObject.default; + } else { + throw payload._result; + } + } + function lazy(ctor) { + var payload = { + // We use these fields to store the result. + _status: Uninitialized, + _result: ctor + }; + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: payload, + _init: lazyInitializer + }; + { + var defaultProps; + var propTypes; + Object.defineProperties(lazyType, { + defaultProps: { + configurable: true, + get: function() { + return defaultProps; + }, + set: function(newDefaultProps) { + error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); + defaultProps = newDefaultProps; + Object.defineProperty(lazyType, "defaultProps", { + enumerable: true + }); + } + }, + propTypes: { + configurable: true, + get: function() { + return propTypes; + }, + set: function(newPropTypes) { + error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); + propTypes = newPropTypes; + Object.defineProperty(lazyType, "propTypes", { + enumerable: true + }); + } + } + }); + } + return lazyType; + } + function forwardRef2(render) { + { + if (render != null && render.$$typeof === REACT_MEMO_TYPE) { + error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."); + } else if (typeof render !== "function") { + error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render); + } else { + if (render.length !== 0 && render.length !== 2) { + error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."); + } + } + if (render != null) { + if (render.defaultProps != null || render.propTypes != null) { + error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?"); + } + } + } + var elementType = { + $$typeof: REACT_FORWARD_REF_TYPE, + render + }; + { + var ownName; + Object.defineProperty(elementType, "displayName", { + enumerable: false, + configurable: true, + get: function() { + return ownName; + }, + set: function(name) { + ownName = name; + if (!render.name && !render.displayName) { + render.displayName = name; + } + } + }); + } + return elementType; + } + var REACT_MODULE_REFERENCE; + { + REACT_MODULE_REFERENCE = Symbol.for("react.module.reference"); + } + function isValidElementType(type) { + if (typeof type === "string" || typeof type === "function") { + return true; + } + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { + return true; + } + if (typeof type === "object" && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== void 0) { + return true; + } + } + return false; + } + function memo(type, compare) { + { + if (!isValidElementType(type)) { + error("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type); + } + } + var elementType = { + $$typeof: REACT_MEMO_TYPE, + type, + compare: compare === void 0 ? null : compare + }; + { + var ownName; + Object.defineProperty(elementType, "displayName", { + enumerable: false, + configurable: true, + get: function() { + return ownName; + }, + set: function(name) { + ownName = name; + if (!type.name && !type.displayName) { + type.displayName = name; + } + } + }); + } + return elementType; + } + function resolveDispatcher() { + var dispatcher = ReactCurrentDispatcher.current; + { + if (dispatcher === null) { + error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); + } + } + return dispatcher; + } + function useContext3(Context2) { + var dispatcher = resolveDispatcher(); + { + if (Context2._context !== void 0) { + var realContext = Context2._context; + if (realContext.Consumer === Context2) { + error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"); + } else if (realContext.Provider === Context2) { + error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?"); + } + } + } + return dispatcher.useContext(Context2); + } + function useState2(initialState) { + var dispatcher = resolveDispatcher(); + return dispatcher.useState(initialState); + } + function useReducer2(reducer, initialArg, init) { + var dispatcher = resolveDispatcher(); + return dispatcher.useReducer(reducer, initialArg, init); + } + function useRef3(initialValue) { + var dispatcher = resolveDispatcher(); + return dispatcher.useRef(initialValue); + } + function useEffect4(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useEffect(create, deps); + } + function useInsertionEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useInsertionEffect(create, deps); + } + function useLayoutEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useLayoutEffect(create, deps); + } + function useCallback2(callback, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useCallback(callback, deps); + } + function useMemo3(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useMemo(create, deps); + } + function useImperativeHandle(ref, create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useImperativeHandle(ref, create, deps); + } + function useDebugValue2(value, formatterFn) { + { + var dispatcher = resolveDispatcher(); + return dispatcher.useDebugValue(value, formatterFn); + } + } + function useTransition() { + var dispatcher = resolveDispatcher(); + return dispatcher.useTransition(); + } + function useDeferredValue(value) { + var dispatcher = resolveDispatcher(); + return dispatcher.useDeferredValue(value); + } + function useId() { + var dispatcher = resolveDispatcher(); + return dispatcher.useId(); + } + function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + var dispatcher = resolveDispatcher(); + return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); + } + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; + function disabledLog() { + } + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + } + disabledDepth++; + } + } + function reenableLogs() { + { + disabledDepth--; + if (disabledDepth === 0) { + var props = { + configurable: true, + enumerable: true, + writable: true + }; + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + } + if (disabledDepth < 0) { + error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); + } + } + } + var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === void 0) { + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ""; + } + } + return "\n" + prefix + name; + } + } + var reentry = false; + var componentFrameCache; + { + var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + } + function describeNativeComponentFrame(fn, construct) { + if (!fn || reentry) { + return ""; + } + { + var frame = componentFrameCache.get(fn); + if (frame !== void 0) { + return frame; + } + } + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = void 0; + var previousDispatcher; + { + previousDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = null; + disableLogs(); + } + try { + if (construct) { + var Fake = function() { + throw Error(); + }; + Object.defineProperty(Fake.prototype, "props", { + set: function() { + throw Error(); + } + }); + if (typeof Reflect === "object" && Reflect.construct) { + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + fn(); + } + } catch (sample) { + if (sample && control && typeof sample.stack === "string") { + var sampleLines = sample.stack.split("\n"); + var controlLines = control.stack.split("\n"); + var s = sampleLines.length - 1; + var c2 = controlLines.length - 1; + while (s >= 1 && c2 >= 0 && sampleLines[s] !== controlLines[c2]) { + c2--; + } + for (; s >= 1 && c2 >= 0; s--, c2--) { + if (sampleLines[s] !== controlLines[c2]) { + if (s !== 1 || c2 !== 1) { + do { + s--; + c2--; + if (c2 < 0 || sampleLines[s] !== controlLines[c2]) { + var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); + if (fn.displayName && _frame.includes("")) { + _frame = _frame.replace("", fn.displayName); + } + { + if (typeof fn === "function") { + componentFrameCache.set(fn, _frame); + } + } + return _frame; + } + } while (s >= 1 && c2 >= 0); + } + break; + } + } + } + } finally { + reentry = false; + { + ReactCurrentDispatcher$1.current = previousDispatcher; + reenableLogs(); + } + Error.prepareStackTrace = previousPrepareStackTrace; + } + var name = fn ? fn.displayName || fn.name : ""; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; + { + if (typeof fn === "function") { + componentFrameCache.set(fn, syntheticFrame); + } + } + return syntheticFrame; + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } + } + function shouldConstruct(Component3) { + var prototype = Component3.prototype; + return !!(prototype && prototype.isReactComponent); + } + function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + if (type == null) { + return ""; + } + if (typeof type === "function") { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + if (typeof type === "string") { + return describeBuiltInComponentFrame(type); + } + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame("Suspense"); + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame("SuspenseList"); + } + if (typeof type === "object") { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + case REACT_MEMO_TYPE: + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) { + } + } + } + } + return ""; + } + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + } + } + function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + var has = Function.call.bind(hasOwnProperty); + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; + try { + if (typeof typeSpecs[typeSpecName] !== "function") { + var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); + err.name = "Invariant Violation"; + throw err; + } + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); + } catch (ex) { + error$1 = ex; + } + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1); + setCurrentlyValidatingElement(null); + } + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + error("Failed %s type: %s", location, error$1.message); + setCurrentlyValidatingElement(null); + } + } + } + } + } + function setCurrentlyValidatingElement$1(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + setExtraStackFrame(stack); + } else { + setExtraStackFrame(null); + } + } + } + var propTypesMisspellWarningShown; + { + propTypesMisspellWarningShown = false; + } + function getDeclarationErrorAddendum() { + if (ReactCurrentOwner.current) { + var name = getComponentNameFromType(ReactCurrentOwner.current.type); + if (name) { + return "\n\nCheck the render method of `" + name + "`."; + } + } + return ""; + } + function getSourceInfoErrorAddendum(source) { + if (source !== void 0) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ""); + var lineNumber = source.lineNumber; + return "\n\nCheck your code at " + fileName + ":" + lineNumber + "."; + } + return ""; + } + function getSourceInfoErrorAddendumForProps(elementProps) { + if (elementProps !== null && elementProps !== void 0) { + return getSourceInfoErrorAddendum(elementProps.__source); + } + return ""; + } + var ownerHasKeyUseWarning = {}; + function getCurrentComponentErrorInfo(parentType) { + var info = getDeclarationErrorAddendum(); + if (!info) { + var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name; + if (parentName) { + info = "\n\nCheck the top-level render call using <" + parentName + ">."; + } + } + return info; + } + function validateExplicitKey(element, parentType) { + if (!element._store || element._store.validated || element.key != null) { + return; + } + element._store.validated = true; + var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { + return; + } + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; + var childOwner = ""; + if (element && element._owner && element._owner !== ReactCurrentOwner.current) { + childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; + } + { + setCurrentlyValidatingElement$1(element); + error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); + setCurrentlyValidatingElement$1(null); + } + } + function validateChildKeys(node, parentType) { + if (typeof node !== "object") { + return; + } + if (isArray(node)) { + for (var i2 = 0; i2 < node.length; i2++) { + var child = node[i2]; + if (isValidElement(child)) { + validateExplicitKey(child, parentType); + } + } + } else if (isValidElement(node)) { + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + if (typeof iteratorFn === "function") { + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + while (!(step = iterator.next()).done) { + if (isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } + } + } + } + } + } + function validatePropTypes(element) { + { + var type = element.type; + if (type === null || type === void 0 || typeof type === "string") { + return; + } + var propTypes; + if (typeof type === "function") { + propTypes = type.propTypes; + } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + type.$$typeof === REACT_MEMO_TYPE)) { + propTypes = type.propTypes; + } else { + return; + } + if (propTypes) { + var name = getComponentNameFromType(type); + checkPropTypes(propTypes, element.props, "prop", name, element); + } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) { + propTypesMisspellWarningShown = true; + var _name = getComponentNameFromType(type); + error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown"); + } + if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) { + error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); + } + } + } + function validateFragmentProps(fragment) { + { + var keys = Object.keys(fragment.props); + for (var i2 = 0; i2 < keys.length; i2++) { + var key = keys[i2]; + if (key !== "children" && key !== "key") { + setCurrentlyValidatingElement$1(fragment); + error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); + setCurrentlyValidatingElement$1(null); + break; + } + } + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + error("Invalid attribute `ref` supplied to `React.Fragment`."); + setCurrentlyValidatingElement$1(null); + } + } + } + function createElementWithValidation(type, props, children) { + var validType = isValidElementType(type); + if (!validType) { + var info = ""; + if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) { + info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; + } + var sourceInfo = getSourceInfoErrorAddendumForProps(props); + if (sourceInfo) { + info += sourceInfo; + } else { + info += getDeclarationErrorAddendum(); + } + var typeString; + if (type === null) { + typeString = "null"; + } else if (isArray(type)) { + typeString = "array"; + } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) { + typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />"; + info = " Did you accidentally export a JSX literal instead of a component?"; + } else { + typeString = typeof type; + } + { + error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); + } + } + var element = createElement9.apply(this, arguments); + if (element == null) { + return element; + } + if (validType) { + for (var i2 = 2; i2 < arguments.length; i2++) { + validateChildKeys(arguments[i2], type); + } + } + if (type === REACT_FRAGMENT_TYPE) { + validateFragmentProps(element); + } else { + validatePropTypes(element); + } + return element; + } + var didWarnAboutDeprecatedCreateFactory = false; + function createFactoryWithValidation(type) { + var validatedFactory = createElementWithValidation.bind(null, type); + validatedFactory.type = type; + { + if (!didWarnAboutDeprecatedCreateFactory) { + didWarnAboutDeprecatedCreateFactory = true; + warn("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead."); + } + Object.defineProperty(validatedFactory, "type", { + enumerable: false, + get: function() { + warn("Factory.type is deprecated. Access the class directly before passing it to createFactory."); + Object.defineProperty(this, "type", { + value: type + }); + return type; + } + }); + } + return validatedFactory; + } + function cloneElementWithValidation(element, props, children) { + var newElement = cloneElement.apply(this, arguments); + for (var i2 = 2; i2 < arguments.length; i2++) { + validateChildKeys(arguments[i2], newElement.type); + } + validatePropTypes(newElement); + return newElement; + } + function startTransition(scope, options) { + var prevTransition = ReactCurrentBatchConfig.transition; + ReactCurrentBatchConfig.transition = {}; + var currentTransition = ReactCurrentBatchConfig.transition; + { + ReactCurrentBatchConfig.transition._updatedFibers = /* @__PURE__ */ new Set(); + } + try { + scope(); + } finally { + ReactCurrentBatchConfig.transition = prevTransition; + { + if (prevTransition === null && currentTransition._updatedFibers) { + var updatedFibersCount = currentTransition._updatedFibers.size; + if (updatedFibersCount > 10) { + warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."); + } + currentTransition._updatedFibers.clear(); + } + } + } + } + var didWarnAboutMessageChannel = false; + var enqueueTaskImpl = null; + function enqueueTask(task) { + if (enqueueTaskImpl === null) { + try { + var requireString = ("require" + Math.random()).slice(0, 7); + var nodeRequire = module && module[requireString]; + enqueueTaskImpl = nodeRequire.call(module, "timers").setImmediate; + } catch (_err) { + enqueueTaskImpl = function(callback) { + { + if (didWarnAboutMessageChannel === false) { + didWarnAboutMessageChannel = true; + if (typeof MessageChannel === "undefined") { + error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."); + } + } + } + var channel = new MessageChannel(); + channel.port1.onmessage = callback; + channel.port2.postMessage(void 0); + }; + } + } + return enqueueTaskImpl(task); + } + var actScopeDepth = 0; + var didWarnNoAwaitAct = false; + function act(callback) { + { + var prevActScopeDepth = actScopeDepth; + actScopeDepth++; + if (ReactCurrentActQueue.current === null) { + ReactCurrentActQueue.current = []; + } + var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; + var result; + try { + ReactCurrentActQueue.isBatchingLegacy = true; + result = callback(); + if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { + var queue = ReactCurrentActQueue.current; + if (queue !== null) { + ReactCurrentActQueue.didScheduleLegacyUpdate = false; + flushActQueue(queue); + } + } + } catch (error2) { + popActScope(prevActScopeDepth); + throw error2; + } finally { + ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; + } + if (result !== null && typeof result === "object" && typeof result.then === "function") { + var thenableResult = result; + var wasAwaited = false; + var thenable = { + then: function(resolve, reject) { + wasAwaited = true; + thenableResult.then(function(returnValue2) { + popActScope(prevActScopeDepth); + if (actScopeDepth === 0) { + recursivelyFlushAsyncActWork(returnValue2, resolve, reject); + } else { + resolve(returnValue2); + } + }, function(error2) { + popActScope(prevActScopeDepth); + reject(error2); + }); + } + }; + { + if (!didWarnNoAwaitAct && typeof Promise !== "undefined") { + Promise.resolve().then(function() { + }).then(function() { + if (!wasAwaited) { + didWarnNoAwaitAct = true; + error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"); + } + }); + } + } + return thenable; + } else { + var returnValue = result; + popActScope(prevActScopeDepth); + if (actScopeDepth === 0) { + var _queue = ReactCurrentActQueue.current; + if (_queue !== null) { + flushActQueue(_queue); + ReactCurrentActQueue.current = null; + } + var _thenable = { + then: function(resolve, reject) { + if (ReactCurrentActQueue.current === null) { + ReactCurrentActQueue.current = []; + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } else { + resolve(returnValue); + } + } + }; + return _thenable; + } else { + var _thenable2 = { + then: function(resolve, reject) { + resolve(returnValue); + } + }; + return _thenable2; + } + } + } + } + function popActScope(prevActScopeDepth) { + { + if (prevActScopeDepth !== actScopeDepth - 1) { + error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "); + } + actScopeDepth = prevActScopeDepth; + } + } + function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { + { + var queue = ReactCurrentActQueue.current; + if (queue !== null) { + try { + flushActQueue(queue); + enqueueTask(function() { + if (queue.length === 0) { + ReactCurrentActQueue.current = null; + resolve(returnValue); + } else { + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } + }); + } catch (error2) { + reject(error2); + } + } else { + resolve(returnValue); + } + } + } + var isFlushing = false; + function flushActQueue(queue) { + { + if (!isFlushing) { + isFlushing = true; + var i2 = 0; + try { + for (; i2 < queue.length; i2++) { + var callback = queue[i2]; + do { + callback = callback(true); + } while (callback !== null); + } + queue.length = 0; + } catch (error2) { + queue = queue.slice(i2 + 1); + throw error2; + } finally { + isFlushing = false; + } + } + } + } + var createElement$1 = createElementWithValidation; + var cloneElement$1 = cloneElementWithValidation; + var createFactory2 = createFactoryWithValidation; + var Children = { + map: mapChildren, + forEach: forEachChildren, + count: countChildren, + toArray, + only: onlyChild + }; + exports.Children = Children; + exports.Component = Component2; + exports.Fragment = REACT_FRAGMENT_TYPE; + exports.Profiler = REACT_PROFILER_TYPE; + exports.PureComponent = PureComponent; + exports.StrictMode = REACT_STRICT_MODE_TYPE; + exports.Suspense = REACT_SUSPENSE_TYPE; + exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; + exports.act = act; + exports.cloneElement = cloneElement$1; + exports.createContext = createContext3; + exports.createElement = createElement$1; + exports.createFactory = createFactory2; + exports.createRef = createRef; + exports.forwardRef = forwardRef2; + exports.isValidElement = isValidElement; + exports.lazy = lazy; + exports.memo = memo; + exports.startTransition = startTransition; + exports.unstable_act = act; + exports.useCallback = useCallback2; + exports.useContext = useContext3; + exports.useDebugValue = useDebugValue2; + exports.useDeferredValue = useDeferredValue; + exports.useEffect = useEffect4; + exports.useId = useId; + exports.useImperativeHandle = useImperativeHandle; + exports.useInsertionEffect = useInsertionEffect; + exports.useLayoutEffect = useLayoutEffect; + exports.useMemo = useMemo3; + exports.useReducer = useReducer2; + exports.useRef = useRef3; + exports.useState = useState2; + exports.useSyncExternalStore = useSyncExternalStore; + exports.useTransition = useTransition; + exports.version = ReactVersion; + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); + } + })(); + } + } +}); + +// ../../../node_modules/.pnpm/react@18.3.1/node_modules/react/index.js +var require_react = __commonJS({ + "../../../node_modules/.pnpm/react@18.3.1/node_modules/react/index.js"(exports, module) { + "use strict"; + if (false) { + module.exports = null; + } else { + module.exports = require_react_development(); + } + } +}); + +// ../../../node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.development.js +var require_react_jsx_runtime_development = __commonJS({ + "../../../node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.development.js"(exports) { + "use strict"; + if (true) { + (function() { + "use strict"; + var React9 = require_react(); + var REACT_ELEMENT_TYPE = Symbol.for("react.element"); + var REACT_PORTAL_TYPE = Symbol.for("react.portal"); + var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); + var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); + var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); + var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); + var REACT_CONTEXT_TYPE = Symbol.for("react.context"); + var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); + var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); + var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); + var REACT_MEMO_TYPE = Symbol.for("react.memo"); + var REACT_LAZY_TYPE = Symbol.for("react.lazy"); + var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); + var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = "@@iterator"; + function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== "object") { + return null; + } + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === "function") { + return maybeIterator; + } + return null; + } + var ReactSharedInternals = React9.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + printWarning("error", format, args); + } + } + } + function printWarning(level, format, args) { + { + var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame2.getStackAddendum(); + if (stack !== "") { + format += "%s"; + args = args.concat([stack]); + } + var argsWithFormat = args.map(function(item) { + return String(item); + }); + argsWithFormat.unshift("Warning: " + format); + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + } + var enableScopeAPI = false; + var enableCacheElement = false; + var enableTransitionTracing = false; + var enableLegacyHidden = false; + var enableDebugTracing = false; + var REACT_MODULE_REFERENCE; + { + REACT_MODULE_REFERENCE = Symbol.for("react.module.reference"); + } + function isValidElementType(type) { + if (typeof type === "string" || typeof type === "function") { + return true; + } + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { + return true; + } + if (typeof type === "object" && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== void 0) { + return true; + } + } + return false; + } + function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + if (displayName) { + return displayName; + } + var functionName = innerType.displayName || innerType.name || ""; + return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; + } + function getContextName(type) { + return type.displayName || "Context"; + } + function getComponentNameFromType(type) { + if (type == null) { + return null; + } + { + if (typeof type.tag === "number") { + error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); + } + } + if (typeof type === "function") { + return type.displayName || type.name || null; + } + if (typeof type === "string") { + return type; + } + switch (type) { + case REACT_FRAGMENT_TYPE: + return "Fragment"; + case REACT_PORTAL_TYPE: + return "Portal"; + case REACT_PROFILER_TYPE: + return "Profiler"; + case REACT_STRICT_MODE_TYPE: + return "StrictMode"; + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + } + if (typeof type === "object") { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + ".Consumer"; + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + ".Provider"; + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, "ForwardRef"); + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + if (outerName !== null) { + return outerName; + } + return getComponentNameFromType(type.type) || "Memo"; + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } + } + } + return null; + } + var assign = Object.assign; + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; + function disabledLog() { + } + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + } + disabledDepth++; + } + } + function reenableLogs() { + { + disabledDepth--; + if (disabledDepth === 0) { + var props = { + configurable: true, + enumerable: true, + writable: true + }; + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + } + if (disabledDepth < 0) { + error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); + } + } + } + var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === void 0) { + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ""; + } + } + return "\n" + prefix + name; + } + } + var reentry = false; + var componentFrameCache; + { + var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + } + function describeNativeComponentFrame(fn, construct) { + if (!fn || reentry) { + return ""; + } + { + var frame = componentFrameCache.get(fn); + if (frame !== void 0) { + return frame; + } + } + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = void 0; + var previousDispatcher; + { + previousDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = null; + disableLogs(); + } + try { + if (construct) { + var Fake = function() { + throw Error(); + }; + Object.defineProperty(Fake.prototype, "props", { + set: function() { + throw Error(); + } + }); + if (typeof Reflect === "object" && Reflect.construct) { + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + fn(); + } + } catch (sample) { + if (sample && control && typeof sample.stack === "string") { + var sampleLines = sample.stack.split("\n"); + var controlLines = control.stack.split("\n"); + var s = sampleLines.length - 1; + var c2 = controlLines.length - 1; + while (s >= 1 && c2 >= 0 && sampleLines[s] !== controlLines[c2]) { + c2--; + } + for (; s >= 1 && c2 >= 0; s--, c2--) { + if (sampleLines[s] !== controlLines[c2]) { + if (s !== 1 || c2 !== 1) { + do { + s--; + c2--; + if (c2 < 0 || sampleLines[s] !== controlLines[c2]) { + var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); + if (fn.displayName && _frame.includes("")) { + _frame = _frame.replace("", fn.displayName); + } + { + if (typeof fn === "function") { + componentFrameCache.set(fn, _frame); + } + } + return _frame; + } + } while (s >= 1 && c2 >= 0); + } + break; + } + } + } + } finally { + reentry = false; + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } + Error.prepareStackTrace = previousPrepareStackTrace; + } + var name = fn ? fn.displayName || fn.name : ""; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; + { + if (typeof fn === "function") { + componentFrameCache.set(fn, syntheticFrame); + } + } + return syntheticFrame; + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } + } + function shouldConstruct(Component2) { + var prototype = Component2.prototype; + return !!(prototype && prototype.isReactComponent); + } + function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + if (type == null) { + return ""; + } + if (typeof type === "function") { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + if (typeof type === "string") { + return describeBuiltInComponentFrame(type); + } + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame("Suspense"); + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame("SuspenseList"); + } + if (typeof type === "object") { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + case REACT_MEMO_TYPE: + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) { + } + } + } + } + return ""; + } + var hasOwnProperty = Object.prototype.hasOwnProperty; + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame.setExtraStackFrame(null); + } + } + } + function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + var has = Function.call.bind(hasOwnProperty); + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; + try { + if (typeof typeSpecs[typeSpecName] !== "function") { + var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); + err.name = "Invariant Violation"; + throw err; + } + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); + } catch (ex) { + error$1 = ex; + } + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1); + setCurrentlyValidatingElement(null); + } + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + error("Failed %s type: %s", location, error$1.message); + setCurrentlyValidatingElement(null); + } + } + } + } + } + var isArrayImpl = Array.isArray; + function isArray(a2) { + return isArrayImpl(a2); + } + function typeName(value) { + { + var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; + return type; + } + } + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e2) { + return true; + } + } + } + function testStringCoercion(value) { + return "" + value; + } + function checkKeyStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); + return testStringCoercion(value); + } + } + } + var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; + var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true + }; + var specialPropKeyWarningShown; + var specialPropRefWarningShown; + var didWarnAboutStringRefs; + { + didWarnAboutStringRefs = {}; + } + function hasValidRef(config) { + { + if (hasOwnProperty.call(config, "ref")) { + var getter = Object.getOwnPropertyDescriptor(config, "ref").get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.ref !== void 0; + } + function hasValidKey(config) { + { + if (hasOwnProperty.call(config, "key")) { + var getter = Object.getOwnPropertyDescriptor(config, "key").get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.key !== void 0; + } + function warnIfStringRefCannotBeAutoConverted(config, self2) { + { + if (typeof config.ref === "string" && ReactCurrentOwner.current && self2 && ReactCurrentOwner.current.stateNode !== self2) { + var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); + if (!didWarnAboutStringRefs[componentName]) { + error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref); + didWarnAboutStringRefs[componentName] = true; + } + } + } + } + function defineKeyPropWarningGetter(props, displayName) { + { + var warnAboutAccessingKey = function() { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); + } + }; + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, "key", { + get: warnAboutAccessingKey, + configurable: true + }); + } + } + function defineRefPropWarningGetter(props, displayName) { + { + var warnAboutAccessingRef = function() { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); + } + }; + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, "ref", { + get: warnAboutAccessingRef, + configurable: true + }); + } + } + var ReactElement = function(type, key, ref, self2, source, owner, props) { + var element = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: REACT_ELEMENT_TYPE, + // Built-in properties that belong on the element + type, + key, + ref, + props, + // Record the component responsible for creating this element. + _owner: owner + }; + { + element._store = {}; + Object.defineProperty(element._store, "validated", { + configurable: false, + enumerable: false, + writable: true, + value: false + }); + Object.defineProperty(element, "_self", { + configurable: false, + enumerable: false, + writable: false, + value: self2 + }); + Object.defineProperty(element, "_source", { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } + } + return element; + }; + function jsxDEV(type, config, maybeKey, source, self2) { + { + var propName; + var props = {}; + var key = null; + var ref = null; + if (maybeKey !== void 0) { + { + checkKeyStringCoercion(maybeKey); + } + key = "" + maybeKey; + } + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + key = "" + config.key; + } + if (hasValidRef(config)) { + ref = config.ref; + warnIfStringRefCannotBeAutoConverted(config, self2); + } + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; + } + } + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + for (propName in defaultProps) { + if (props[propName] === void 0) { + props[propName] = defaultProps[propName]; + } + } + } + if (key || ref) { + var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type; + if (key) { + defineKeyPropWarningGetter(props, displayName); + } + if (ref) { + defineRefPropWarningGetter(props, displayName); + } + } + return ReactElement(type, key, ref, self2, source, ReactCurrentOwner.current, props); + } + } + var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; + var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement$1(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + } + } + var propTypesMisspellWarningShown; + { + propTypesMisspellWarningShown = false; + } + function isValidElement(object) { + { + return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } + } + function getDeclarationErrorAddendum() { + { + if (ReactCurrentOwner$1.current) { + var name = getComponentNameFromType(ReactCurrentOwner$1.current.type); + if (name) { + return "\n\nCheck the render method of `" + name + "`."; + } + } + return ""; + } + } + function getSourceInfoErrorAddendum(source) { + { + if (source !== void 0) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ""); + var lineNumber = source.lineNumber; + return "\n\nCheck your code at " + fileName + ":" + lineNumber + "."; + } + return ""; + } + } + var ownerHasKeyUseWarning = {}; + function getCurrentComponentErrorInfo(parentType) { + { + var info = getDeclarationErrorAddendum(); + if (!info) { + var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name; + if (parentName) { + info = "\n\nCheck the top-level render call using <" + parentName + ">."; + } + } + return info; + } + } + function validateExplicitKey(element, parentType) { + { + if (!element._store || element._store.validated || element.key != null) { + return; + } + element._store.validated = true; + var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { + return; + } + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; + var childOwner = ""; + if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) { + childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; + } + setCurrentlyValidatingElement$1(element); + error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); + setCurrentlyValidatingElement$1(null); + } + } + function validateChildKeys(node, parentType) { + { + if (typeof node !== "object") { + return; + } + if (isArray(node)) { + for (var i2 = 0; i2 < node.length; i2++) { + var child = node[i2]; + if (isValidElement(child)) { + validateExplicitKey(child, parentType); + } + } + } else if (isValidElement(node)) { + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + if (typeof iteratorFn === "function") { + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + while (!(step = iterator.next()).done) { + if (isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } + } + } + } + } + } + } + function validatePropTypes(element) { + { + var type = element.type; + if (type === null || type === void 0 || typeof type === "string") { + return; + } + var propTypes; + if (typeof type === "function") { + propTypes = type.propTypes; + } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + type.$$typeof === REACT_MEMO_TYPE)) { + propTypes = type.propTypes; + } else { + return; + } + if (propTypes) { + var name = getComponentNameFromType(type); + checkPropTypes(propTypes, element.props, "prop", name, element); + } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) { + propTypesMisspellWarningShown = true; + var _name = getComponentNameFromType(type); + error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown"); + } + if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) { + error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); + } + } + } + function validateFragmentProps(fragment) { + { + var keys = Object.keys(fragment.props); + for (var i2 = 0; i2 < keys.length; i2++) { + var key = keys[i2]; + if (key !== "children" && key !== "key") { + setCurrentlyValidatingElement$1(fragment); + error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); + setCurrentlyValidatingElement$1(null); + break; + } + } + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + error("Invalid attribute `ref` supplied to `React.Fragment`."); + setCurrentlyValidatingElement$1(null); + } + } + } + var didWarnAboutKeySpread = {}; + function jsxWithValidation(type, props, key, isStaticChildren, source, self2) { + { + var validType = isValidElementType(type); + if (!validType) { + var info = ""; + if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) { + info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; + } + var sourceInfo = getSourceInfoErrorAddendum(source); + if (sourceInfo) { + info += sourceInfo; + } else { + info += getDeclarationErrorAddendum(); + } + var typeString; + if (type === null) { + typeString = "null"; + } else if (isArray(type)) { + typeString = "array"; + } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) { + typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />"; + info = " Did you accidentally export a JSX literal instead of a component?"; + } else { + typeString = typeof type; + } + error("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); + } + var element = jsxDEV(type, props, key, source, self2); + if (element == null) { + return element; + } + if (validType) { + var children = props.children; + if (children !== void 0) { + if (isStaticChildren) { + if (isArray(children)) { + for (var i2 = 0; i2 < children.length; i2++) { + validateChildKeys(children[i2], type); + } + if (Object.freeze) { + Object.freeze(children); + } + } else { + error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."); + } + } else { + validateChildKeys(children, type); + } + } + } + { + if (hasOwnProperty.call(props, "key")) { + var componentName = getComponentNameFromType(type); + var keys = Object.keys(props).filter(function(k2) { + return k2 !== "key"; + }); + var beforeExample = keys.length > 0 ? "{key: someKey, " + keys.join(": ..., ") + ": ...}" : "{key: someKey}"; + if (!didWarnAboutKeySpread[componentName + beforeExample]) { + var afterExample = keys.length > 0 ? "{" + keys.join(": ..., ") + ": ...}" : "{}"; + error('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName); + didWarnAboutKeySpread[componentName + beforeExample] = true; + } + } + } + if (type === REACT_FRAGMENT_TYPE) { + validateFragmentProps(element); + } else { + validatePropTypes(element); + } + return element; + } + } + function jsxWithValidationStatic(type, props, key) { + { + return jsxWithValidation(type, props, key, true); + } + } + function jsxWithValidationDynamic(type, props, key) { + { + return jsxWithValidation(type, props, key, false); + } + } + var jsx = jsxWithValidationDynamic; + var jsxs = jsxWithValidationStatic; + exports.Fragment = REACT_FRAGMENT_TYPE; + exports.jsx = jsx; + exports.jsxs = jsxs; + })(); + } + } +}); + +// ../../../node_modules/.pnpm/react@18.3.1/node_modules/react/jsx-runtime.js +var require_jsx_runtime = __commonJS({ + "../../../node_modules/.pnpm/react@18.3.1/node_modules/react/jsx-runtime.js"(exports, module) { + "use strict"; + if (false) { + module.exports = null; + } else { + module.exports = require_react_jsx_runtime_development(); + } + } +}); + +// ../../../node_modules/.pnpm/scheduler@0.23.2/node_modules/scheduler/cjs/scheduler.development.js +var require_scheduler_development = __commonJS({ + "../../../node_modules/.pnpm/scheduler@0.23.2/node_modules/scheduler/cjs/scheduler.development.js"(exports) { + "use strict"; + if (true) { + (function() { + "use strict"; + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); + } + var enableSchedulerDebugging = false; + var enableProfiling = false; + var frameYieldMs = 5; + function push(heap, node) { + var index = heap.length; + heap.push(node); + siftUp(heap, node, index); + } + function peek(heap) { + return heap.length === 0 ? null : heap[0]; + } + function pop(heap) { + if (heap.length === 0) { + return null; + } + var first = heap[0]; + var last = heap.pop(); + if (last !== first) { + heap[0] = last; + siftDown(heap, last, 0); + } + return first; + } + function siftUp(heap, node, i2) { + var index = i2; + while (index > 0) { + var parentIndex = index - 1 >>> 1; + var parent = heap[parentIndex]; + if (compare(parent, node) > 0) { + heap[parentIndex] = node; + heap[index] = parent; + index = parentIndex; + } else { + return; + } + } + } + function siftDown(heap, node, i2) { + var index = i2; + var length = heap.length; + var halfLength = length >>> 1; + while (index < halfLength) { + var leftIndex = (index + 1) * 2 - 1; + var left = heap[leftIndex]; + var rightIndex = leftIndex + 1; + var right = heap[rightIndex]; + if (compare(left, node) < 0) { + if (rightIndex < length && compare(right, left) < 0) { + heap[index] = right; + heap[rightIndex] = node; + index = rightIndex; + } else { + heap[index] = left; + heap[leftIndex] = node; + index = leftIndex; + } + } else if (rightIndex < length && compare(right, node) < 0) { + heap[index] = right; + heap[rightIndex] = node; + index = rightIndex; + } else { + return; + } + } + } + function compare(a2, b) { + var diff = a2.sortIndex - b.sortIndex; + return diff !== 0 ? diff : a2.id - b.id; + } + var ImmediatePriority = 1; + var UserBlockingPriority = 2; + var NormalPriority = 3; + var LowPriority = 4; + var IdlePriority = 5; + function markTaskErrored(task, ms) { + } + var hasPerformanceNow = typeof performance === "object" && typeof performance.now === "function"; + if (hasPerformanceNow) { + var localPerformance = performance; + exports.unstable_now = function() { + return localPerformance.now(); + }; + } else { + var localDate = Date; + var initialTime = localDate.now(); + exports.unstable_now = function() { + return localDate.now() - initialTime; + }; + } + var maxSigned31BitInt = 1073741823; + var IMMEDIATE_PRIORITY_TIMEOUT = -1; + var USER_BLOCKING_PRIORITY_TIMEOUT = 250; + var NORMAL_PRIORITY_TIMEOUT = 5e3; + var LOW_PRIORITY_TIMEOUT = 1e4; + var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; + var taskQueue = []; + var timerQueue = []; + var taskIdCounter = 1; + var currentTask = null; + var currentPriorityLevel = NormalPriority; + var isPerformingWork = false; + var isHostCallbackScheduled = false; + var isHostTimeoutScheduled = false; + var localSetTimeout = typeof setTimeout === "function" ? setTimeout : null; + var localClearTimeout = typeof clearTimeout === "function" ? clearTimeout : null; + var localSetImmediate = typeof setImmediate !== "undefined" ? setImmediate : null; + var isInputPending = typeof navigator !== "undefined" && navigator.scheduling !== void 0 && navigator.scheduling.isInputPending !== void 0 ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; + function advanceTimers(currentTime) { + var timer = peek(timerQueue); + while (timer !== null) { + if (timer.callback === null) { + pop(timerQueue); + } else if (timer.startTime <= currentTime) { + pop(timerQueue); + timer.sortIndex = timer.expirationTime; + push(taskQueue, timer); + } else { + return; + } + timer = peek(timerQueue); + } + } + function handleTimeout(currentTime) { + isHostTimeoutScheduled = false; + advanceTimers(currentTime); + if (!isHostCallbackScheduled) { + if (peek(taskQueue) !== null) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } else { + var firstTimer = peek(timerQueue); + if (firstTimer !== null) { + requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); + } + } + } + } + function flushWork(hasTimeRemaining, initialTime2) { + isHostCallbackScheduled = false; + if (isHostTimeoutScheduled) { + isHostTimeoutScheduled = false; + cancelHostTimeout(); + } + isPerformingWork = true; + var previousPriorityLevel = currentPriorityLevel; + try { + if (enableProfiling) { + try { + return workLoop(hasTimeRemaining, initialTime2); + } catch (error) { + if (currentTask !== null) { + var currentTime = exports.unstable_now(); + markTaskErrored(currentTask, currentTime); + currentTask.isQueued = false; + } + throw error; + } + } else { + return workLoop(hasTimeRemaining, initialTime2); + } + } finally { + currentTask = null; + currentPriorityLevel = previousPriorityLevel; + isPerformingWork = false; + } + } + function workLoop(hasTimeRemaining, initialTime2) { + var currentTime = initialTime2; + advanceTimers(currentTime); + currentTask = peek(taskQueue); + while (currentTask !== null && !enableSchedulerDebugging) { + if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { + break; + } + var callback = currentTask.callback; + if (typeof callback === "function") { + currentTask.callback = null; + currentPriorityLevel = currentTask.priorityLevel; + var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; + var continuationCallback = callback(didUserCallbackTimeout); + currentTime = exports.unstable_now(); + if (typeof continuationCallback === "function") { + currentTask.callback = continuationCallback; + } else { + if (currentTask === peek(taskQueue)) { + pop(taskQueue); + } + } + advanceTimers(currentTime); + } else { + pop(taskQueue); + } + currentTask = peek(taskQueue); + } + if (currentTask !== null) { + return true; + } else { + var firstTimer = peek(timerQueue); + if (firstTimer !== null) { + requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); + } + return false; + } + } + function unstable_runWithPriority(priorityLevel, eventHandler) { + switch (priorityLevel) { + case ImmediatePriority: + case UserBlockingPriority: + case NormalPriority: + case LowPriority: + case IdlePriority: + break; + default: + priorityLevel = NormalPriority; + } + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = priorityLevel; + try { + return eventHandler(); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + } + function unstable_next(eventHandler) { + var priorityLevel; + switch (currentPriorityLevel) { + case ImmediatePriority: + case UserBlockingPriority: + case NormalPriority: + priorityLevel = NormalPriority; + break; + default: + priorityLevel = currentPriorityLevel; + break; + } + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = priorityLevel; + try { + return eventHandler(); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + } + function unstable_wrapCallback(callback) { + var parentPriorityLevel = currentPriorityLevel; + return function() { + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = parentPriorityLevel; + try { + return callback.apply(this, arguments); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + }; + } + function unstable_scheduleCallback(priorityLevel, callback, options) { + var currentTime = exports.unstable_now(); + var startTime2; + if (typeof options === "object" && options !== null) { + var delay = options.delay; + if (typeof delay === "number" && delay > 0) { + startTime2 = currentTime + delay; + } else { + startTime2 = currentTime; + } + } else { + startTime2 = currentTime; + } + var timeout; + switch (priorityLevel) { + case ImmediatePriority: + timeout = IMMEDIATE_PRIORITY_TIMEOUT; + break; + case UserBlockingPriority: + timeout = USER_BLOCKING_PRIORITY_TIMEOUT; + break; + case IdlePriority: + timeout = IDLE_PRIORITY_TIMEOUT; + break; + case LowPriority: + timeout = LOW_PRIORITY_TIMEOUT; + break; + case NormalPriority: + default: + timeout = NORMAL_PRIORITY_TIMEOUT; + break; + } + var expirationTime = startTime2 + timeout; + var newTask = { + id: taskIdCounter++, + callback, + priorityLevel, + startTime: startTime2, + expirationTime, + sortIndex: -1 + }; + if (startTime2 > currentTime) { + newTask.sortIndex = startTime2; + push(timerQueue, newTask); + if (peek(taskQueue) === null && newTask === peek(timerQueue)) { + if (isHostTimeoutScheduled) { + cancelHostTimeout(); + } else { + isHostTimeoutScheduled = true; + } + requestHostTimeout(handleTimeout, startTime2 - currentTime); + } + } else { + newTask.sortIndex = expirationTime; + push(taskQueue, newTask); + if (!isHostCallbackScheduled && !isPerformingWork) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } + } + return newTask; + } + function unstable_pauseExecution() { + } + function unstable_continueExecution() { + if (!isHostCallbackScheduled && !isPerformingWork) { + isHostCallbackScheduled = true; + requestHostCallback(flushWork); + } + } + function unstable_getFirstCallbackNode() { + return peek(taskQueue); + } + function unstable_cancelCallback(task) { + task.callback = null; + } + function unstable_getCurrentPriorityLevel() { + return currentPriorityLevel; + } + var isMessageLoopRunning = false; + var scheduledHostCallback = null; + var taskTimeoutID = -1; + var frameInterval = frameYieldMs; + var startTime = -1; + function shouldYieldToHost() { + var timeElapsed = exports.unstable_now() - startTime; + if (timeElapsed < frameInterval) { + return false; + } + return true; + } + function requestPaint() { + } + function forceFrameRate(fps) { + if (fps < 0 || fps > 125) { + console["error"]("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"); + return; + } + if (fps > 0) { + frameInterval = Math.floor(1e3 / fps); + } else { + frameInterval = frameYieldMs; + } + } + var performWorkUntilDeadline = function() { + if (scheduledHostCallback !== null) { + var currentTime = exports.unstable_now(); + startTime = currentTime; + var hasTimeRemaining = true; + var hasMoreWork = true; + try { + hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); + } finally { + if (hasMoreWork) { + schedulePerformWorkUntilDeadline(); + } else { + isMessageLoopRunning = false; + scheduledHostCallback = null; + } + } + } else { + isMessageLoopRunning = false; + } + }; + var schedulePerformWorkUntilDeadline; + if (typeof localSetImmediate === "function") { + schedulePerformWorkUntilDeadline = function() { + localSetImmediate(performWorkUntilDeadline); + }; + } else if (typeof MessageChannel !== "undefined") { + var channel = new MessageChannel(); + var port = channel.port2; + channel.port1.onmessage = performWorkUntilDeadline; + schedulePerformWorkUntilDeadline = function() { + port.postMessage(null); + }; + } else { + schedulePerformWorkUntilDeadline = function() { + localSetTimeout(performWorkUntilDeadline, 0); + }; + } + function requestHostCallback(callback) { + scheduledHostCallback = callback; + if (!isMessageLoopRunning) { + isMessageLoopRunning = true; + schedulePerformWorkUntilDeadline(); + } + } + function requestHostTimeout(callback, ms) { + taskTimeoutID = localSetTimeout(function() { + callback(exports.unstable_now()); + }, ms); + } + function cancelHostTimeout() { + localClearTimeout(taskTimeoutID); + taskTimeoutID = -1; + } + var unstable_requestPaint = requestPaint; + var unstable_Profiling = null; + exports.unstable_IdlePriority = IdlePriority; + exports.unstable_ImmediatePriority = ImmediatePriority; + exports.unstable_LowPriority = LowPriority; + exports.unstable_NormalPriority = NormalPriority; + exports.unstable_Profiling = unstable_Profiling; + exports.unstable_UserBlockingPriority = UserBlockingPriority; + exports.unstable_cancelCallback = unstable_cancelCallback; + exports.unstable_continueExecution = unstable_continueExecution; + exports.unstable_forceFrameRate = forceFrameRate; + exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; + exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; + exports.unstable_next = unstable_next; + exports.unstable_pauseExecution = unstable_pauseExecution; + exports.unstable_requestPaint = unstable_requestPaint; + exports.unstable_runWithPriority = unstable_runWithPriority; + exports.unstable_scheduleCallback = unstable_scheduleCallback; + exports.unstable_shouldYield = shouldYieldToHost; + exports.unstable_wrapCallback = unstable_wrapCallback; + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); + } + })(); + } + } +}); + +// ../../../node_modules/.pnpm/scheduler@0.23.2/node_modules/scheduler/index.js +var require_scheduler = __commonJS({ + "../../../node_modules/.pnpm/scheduler@0.23.2/node_modules/scheduler/index.js"(exports, module) { + "use strict"; + if (false) { + module.exports = null; + } else { + module.exports = require_scheduler_development(); + } + } +}); + +// ../../../node_modules/.pnpm/react-dom@18.3.1_react@18.3.1/node_modules/react-dom/cjs/react-dom.development.js +var require_react_dom_development = __commonJS({ + "../../../node_modules/.pnpm/react-dom@18.3.1_react@18.3.1/node_modules/react-dom/cjs/react-dom.development.js"(exports) { + "use strict"; + if (true) { + (function() { + "use strict"; + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); + } + var React9 = require_react(); + var Scheduler = require_scheduler(); + var ReactSharedInternals = React9.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + var suppressWarning = false; + function setSuppressWarning(newSuppressWarning) { + { + suppressWarning = newSuppressWarning; + } + } + function warn(format) { + { + if (!suppressWarning) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + printWarning("warn", format, args); + } + } + } + function error(format) { + { + if (!suppressWarning) { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + printWarning("error", format, args); + } + } + } + function printWarning(level, format, args) { + { + var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame2.getStackAddendum(); + if (stack !== "") { + format += "%s"; + args = args.concat([stack]); + } + var argsWithFormat = args.map(function(item) { + return String(item); + }); + argsWithFormat.unshift("Warning: " + format); + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + } + var FunctionComponent = 0; + var ClassComponent = 1; + var IndeterminateComponent = 2; + var HostRoot = 3; + var HostPortal = 4; + var HostComponent = 5; + var HostText = 6; + var Fragment4 = 7; + var Mode = 8; + var ContextConsumer = 9; + var ContextProvider = 10; + var ForwardRef = 11; + var Profiler = 12; + var SuspenseComponent = 13; + var MemoComponent = 14; + var SimpleMemoComponent = 15; + var LazyComponent = 16; + var IncompleteClassComponent = 17; + var DehydratedFragment = 18; + var SuspenseListComponent = 19; + var ScopeComponent = 21; + var OffscreenComponent = 22; + var LegacyHiddenComponent = 23; + var CacheComponent = 24; + var TracingMarkerComponent = 25; + var enableClientRenderFallbackOnTextMismatch = true; + var enableNewReconciler = false; + var enableLazyContextPropagation = false; + var enableLegacyHidden = false; + var enableSuspenseAvoidThisFallback = false; + var disableCommentsAsDOMContainers = true; + var enableCustomElementPropertySupport = false; + var warnAboutStringRefs = true; + var enableSchedulingProfiler = true; + var enableProfilerTimer = true; + var enableProfilerCommitHooks = true; + var allNativeEvents = /* @__PURE__ */ new Set(); + var registrationNameDependencies = {}; + var possibleRegistrationNames = {}; + function registerTwoPhaseEvent(registrationName, dependencies) { + registerDirectEvent(registrationName, dependencies); + registerDirectEvent(registrationName + "Capture", dependencies); + } + function registerDirectEvent(registrationName, dependencies) { + { + if (registrationNameDependencies[registrationName]) { + error("EventRegistry: More than one plugin attempted to publish the same registration name, `%s`.", registrationName); + } + } + registrationNameDependencies[registrationName] = dependencies; + { + var lowerCasedName = registrationName.toLowerCase(); + possibleRegistrationNames[lowerCasedName] = registrationName; + if (registrationName === "onDoubleClick") { + possibleRegistrationNames.ondblclick = registrationName; + } + } + for (var i2 = 0; i2 < dependencies.length; i2++) { + allNativeEvents.add(dependencies[i2]); + } + } + var canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"); + var hasOwnProperty = Object.prototype.hasOwnProperty; + function typeName(value) { + { + var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; + return type; + } + } + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e2) { + return true; + } + } + } + function testStringCoercion(value) { + return "" + value; + } + function checkAttributeStringCoercion(value, attributeName) { + { + if (willCoercionThrow(value)) { + error("The provided `%s` attribute is an unsupported type %s. This value must be coerced to a string before before using it here.", attributeName, typeName(value)); + return testStringCoercion(value); + } + } + } + function checkKeyStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); + return testStringCoercion(value); + } + } + } + function checkPropStringCoercion(value, propName) { + { + if (willCoercionThrow(value)) { + error("The provided `%s` prop is an unsupported type %s. This value must be coerced to a string before before using it here.", propName, typeName(value)); + return testStringCoercion(value); + } + } + } + function checkCSSPropertyStringCoercion(value, propName) { + { + if (willCoercionThrow(value)) { + error("The provided `%s` CSS property is an unsupported type %s. This value must be coerced to a string before before using it here.", propName, typeName(value)); + return testStringCoercion(value); + } + } + } + function checkHtmlStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error("The provided HTML markup uses a value of unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); + return testStringCoercion(value); + } + } + } + function checkFormFieldValueStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error("Form field values (value, checked, defaultValue, or defaultChecked props) must be strings, not %s. This value must be coerced to a string before before using it here.", typeName(value)); + return testStringCoercion(value); + } + } + } + var RESERVED = 0; + var STRING = 1; + var BOOLEANISH_STRING = 2; + var BOOLEAN = 3; + var OVERLOADED_BOOLEAN = 4; + var NUMERIC = 5; + var POSITIVE_NUMERIC = 6; + var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; + var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; + var VALID_ATTRIBUTE_NAME_REGEX = new RegExp("^[" + ATTRIBUTE_NAME_START_CHAR + "][" + ATTRIBUTE_NAME_CHAR + "]*$"); + var illegalAttributeNameCache = {}; + var validatedAttributeNameCache = {}; + function isAttributeNameSafe(attributeName) { + if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) { + return true; + } + if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) { + return false; + } + if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { + validatedAttributeNameCache[attributeName] = true; + return true; + } + illegalAttributeNameCache[attributeName] = true; + { + error("Invalid attribute name: `%s`", attributeName); + } + return false; + } + function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) { + if (propertyInfo !== null) { + return propertyInfo.type === RESERVED; + } + if (isCustomComponentTag) { + return false; + } + if (name.length > 2 && (name[0] === "o" || name[0] === "O") && (name[1] === "n" || name[1] === "N")) { + return true; + } + return false; + } + function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { + if (propertyInfo !== null && propertyInfo.type === RESERVED) { + return false; + } + switch (typeof value) { + case "function": + case "symbol": + return true; + case "boolean": { + if (isCustomComponentTag) { + return false; + } + if (propertyInfo !== null) { + return !propertyInfo.acceptsBooleans; + } else { + var prefix2 = name.toLowerCase().slice(0, 5); + return prefix2 !== "data-" && prefix2 !== "aria-"; + } + } + default: + return false; + } + } + function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) { + if (value === null || typeof value === "undefined") { + return true; + } + if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) { + return true; + } + if (isCustomComponentTag) { + return false; + } + if (propertyInfo !== null) { + switch (propertyInfo.type) { + case BOOLEAN: + return !value; + case OVERLOADED_BOOLEAN: + return value === false; + case NUMERIC: + return isNaN(value); + case POSITIVE_NUMERIC: + return isNaN(value) || value < 1; + } + } + return false; + } + function getPropertyInfo(name) { + return properties.hasOwnProperty(name) ? properties[name] : null; + } + function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL2, removeEmptyString) { + this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; + this.attributeName = attributeName; + this.attributeNamespace = attributeNamespace; + this.mustUseProperty = mustUseProperty; + this.propertyName = name; + this.type = type; + this.sanitizeURL = sanitizeURL2; + this.removeEmptyString = removeEmptyString; + } + var properties = {}; + var reservedProps = [ + "children", + "dangerouslySetInnerHTML", + // TODO: This prevents the assignment of defaultValue to regular + // elements (not just inputs). Now that ReactDOMInput assigns to the + // defaultValue property -- do we need this? + "defaultValue", + "defaultChecked", + "innerHTML", + "suppressContentEditableWarning", + "suppressHydrationWarning", + "style" + ]; + reservedProps.forEach(function(name) { + properties[name] = new PropertyInfoRecord( + name, + RESERVED, + false, + // mustUseProperty + name, + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(_ref) { + var name = _ref[0], attributeName = _ref[1]; + properties[name] = new PropertyInfoRecord( + name, + STRING, + false, + // mustUseProperty + attributeName, + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(name) { + properties[name] = new PropertyInfoRecord( + name, + BOOLEANISH_STRING, + false, + // mustUseProperty + name.toLowerCase(), + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(name) { + properties[name] = new PropertyInfoRecord( + name, + BOOLEANISH_STRING, + false, + // mustUseProperty + name, + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + [ + "allowFullScreen", + "async", + // Note: there is a special case that prevents it from being written to the DOM + // on the client side because the browsers are inconsistent. Instead we call focus(). + "autoFocus", + "autoPlay", + "controls", + "default", + "defer", + "disabled", + "disablePictureInPicture", + "disableRemotePlayback", + "formNoValidate", + "hidden", + "loop", + "noModule", + "noValidate", + "open", + "playsInline", + "readOnly", + "required", + "reversed", + "scoped", + "seamless", + // Microdata + "itemScope" + ].forEach(function(name) { + properties[name] = new PropertyInfoRecord( + name, + BOOLEAN, + false, + // mustUseProperty + name.toLowerCase(), + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + [ + "checked", + // Note: `option.selected` is not updated if `select.multiple` is + // disabled with `removeAttribute`. We have special logic for handling this. + "multiple", + "muted", + "selected" + // NOTE: if you add a camelCased prop to this list, + // you'll need to set attributeName to name.toLowerCase() + // instead in the assignment below. + ].forEach(function(name) { + properties[name] = new PropertyInfoRecord( + name, + BOOLEAN, + true, + // mustUseProperty + name, + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + [ + "capture", + "download" + // NOTE: if you add a camelCased prop to this list, + // you'll need to set attributeName to name.toLowerCase() + // instead in the assignment below. + ].forEach(function(name) { + properties[name] = new PropertyInfoRecord( + name, + OVERLOADED_BOOLEAN, + false, + // mustUseProperty + name, + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + [ + "cols", + "rows", + "size", + "span" + // NOTE: if you add a camelCased prop to this list, + // you'll need to set attributeName to name.toLowerCase() + // instead in the assignment below. + ].forEach(function(name) { + properties[name] = new PropertyInfoRecord( + name, + POSITIVE_NUMERIC, + false, + // mustUseProperty + name, + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + ["rowSpan", "start"].forEach(function(name) { + properties[name] = new PropertyInfoRecord( + name, + NUMERIC, + false, + // mustUseProperty + name.toLowerCase(), + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + var CAMELIZE = /[\-\:]([a-z])/g; + var capitalize = function(token) { + return token[1].toUpperCase(); + }; + [ + "accent-height", + "alignment-baseline", + "arabic-form", + "baseline-shift", + "cap-height", + "clip-path", + "clip-rule", + "color-interpolation", + "color-interpolation-filters", + "color-profile", + "color-rendering", + "dominant-baseline", + "enable-background", + "fill-opacity", + "fill-rule", + "flood-color", + "flood-opacity", + "font-family", + "font-size", + "font-size-adjust", + "font-stretch", + "font-style", + "font-variant", + "font-weight", + "glyph-name", + "glyph-orientation-horizontal", + "glyph-orientation-vertical", + "horiz-adv-x", + "horiz-origin-x", + "image-rendering", + "letter-spacing", + "lighting-color", + "marker-end", + "marker-mid", + "marker-start", + "overline-position", + "overline-thickness", + "paint-order", + "panose-1", + "pointer-events", + "rendering-intent", + "shape-rendering", + "stop-color", + "stop-opacity", + "strikethrough-position", + "strikethrough-thickness", + "stroke-dasharray", + "stroke-dashoffset", + "stroke-linecap", + "stroke-linejoin", + "stroke-miterlimit", + "stroke-opacity", + "stroke-width", + "text-anchor", + "text-decoration", + "text-rendering", + "underline-position", + "underline-thickness", + "unicode-bidi", + "unicode-range", + "units-per-em", + "v-alphabetic", + "v-hanging", + "v-ideographic", + "v-mathematical", + "vector-effect", + "vert-adv-y", + "vert-origin-x", + "vert-origin-y", + "word-spacing", + "writing-mode", + "xmlns:xlink", + "x-height" + // NOTE: if you add a camelCased prop to this list, + // you'll need to set attributeName to name.toLowerCase() + // instead in the assignment below. + ].forEach(function(attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord( + name, + STRING, + false, + // mustUseProperty + attributeName, + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + [ + "xlink:actuate", + "xlink:arcrole", + "xlink:role", + "xlink:show", + "xlink:title", + "xlink:type" + // NOTE: if you add a camelCased prop to this list, + // you'll need to set attributeName to name.toLowerCase() + // instead in the assignment below. + ].forEach(function(attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord( + name, + STRING, + false, + // mustUseProperty + attributeName, + "http://www.w3.org/1999/xlink", + false, + // sanitizeURL + false + ); + }); + [ + "xml:base", + "xml:lang", + "xml:space" + // NOTE: if you add a camelCased prop to this list, + // you'll need to set attributeName to name.toLowerCase() + // instead in the assignment below. + ].forEach(function(attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord( + name, + STRING, + false, + // mustUseProperty + attributeName, + "http://www.w3.org/XML/1998/namespace", + false, + // sanitizeURL + false + ); + }); + ["tabIndex", "crossOrigin"].forEach(function(attributeName) { + properties[attributeName] = new PropertyInfoRecord( + attributeName, + STRING, + false, + // mustUseProperty + attributeName.toLowerCase(), + // attributeName + null, + // attributeNamespace + false, + // sanitizeURL + false + ); + }); + var xlinkHref = "xlinkHref"; + properties[xlinkHref] = new PropertyInfoRecord( + "xlinkHref", + STRING, + false, + // mustUseProperty + "xlink:href", + "http://www.w3.org/1999/xlink", + true, + // sanitizeURL + false + ); + ["src", "href", "action", "formAction"].forEach(function(attributeName) { + properties[attributeName] = new PropertyInfoRecord( + attributeName, + STRING, + false, + // mustUseProperty + attributeName.toLowerCase(), + // attributeName + null, + // attributeNamespace + true, + // sanitizeURL + true + ); + }); + var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; + var didWarn = false; + function sanitizeURL(url) { + { + if (!didWarn && isJavaScriptProtocol.test(url)) { + didWarn = true; + error("A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed %s.", JSON.stringify(url)); + } + } + } + function getValueForProperty(node, name, expected, propertyInfo) { + { + if (propertyInfo.mustUseProperty) { + var propertyName = propertyInfo.propertyName; + return node[propertyName]; + } else { + { + checkAttributeStringCoercion(expected, name); + } + if (propertyInfo.sanitizeURL) { + sanitizeURL("" + expected); + } + var attributeName = propertyInfo.attributeName; + var stringValue = null; + if (propertyInfo.type === OVERLOADED_BOOLEAN) { + if (node.hasAttribute(attributeName)) { + var value = node.getAttribute(attributeName); + if (value === "") { + return true; + } + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + return value; + } + if (value === "" + expected) { + return expected; + } + return value; + } + } else if (node.hasAttribute(attributeName)) { + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + return node.getAttribute(attributeName); + } + if (propertyInfo.type === BOOLEAN) { + return expected; + } + stringValue = node.getAttribute(attributeName); + } + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + return stringValue === null ? expected : stringValue; + } else if (stringValue === "" + expected) { + return expected; + } else { + return stringValue; + } + } + } + } + function getValueForAttribute(node, name, expected, isCustomComponentTag) { + { + if (!isAttributeNameSafe(name)) { + return; + } + if (!node.hasAttribute(name)) { + return expected === void 0 ? void 0 : null; + } + var value = node.getAttribute(name); + { + checkAttributeStringCoercion(expected, name); + } + if (value === "" + expected) { + return expected; + } + return value; + } + } + function setValueForProperty(node, name, value, isCustomComponentTag) { + var propertyInfo = getPropertyInfo(name); + if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { + return; + } + if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) { + value = null; + } + if (isCustomComponentTag || propertyInfo === null) { + if (isAttributeNameSafe(name)) { + var _attributeName = name; + if (value === null) { + node.removeAttribute(_attributeName); + } else { + { + checkAttributeStringCoercion(value, name); + } + node.setAttribute(_attributeName, "" + value); + } + } + return; + } + var mustUseProperty = propertyInfo.mustUseProperty; + if (mustUseProperty) { + var propertyName = propertyInfo.propertyName; + if (value === null) { + var type = propertyInfo.type; + node[propertyName] = type === BOOLEAN ? false : ""; + } else { + node[propertyName] = value; + } + return; + } + var attributeName = propertyInfo.attributeName, attributeNamespace = propertyInfo.attributeNamespace; + if (value === null) { + node.removeAttribute(attributeName); + } else { + var _type = propertyInfo.type; + var attributeValue; + if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) { + attributeValue = ""; + } else { + { + { + checkAttributeStringCoercion(value, attributeName); + } + attributeValue = "" + value; + } + if (propertyInfo.sanitizeURL) { + sanitizeURL(attributeValue.toString()); + } + } + if (attributeNamespace) { + node.setAttributeNS(attributeNamespace, attributeName, attributeValue); + } else { + node.setAttribute(attributeName, attributeValue); + } + } + } + var REACT_ELEMENT_TYPE = Symbol.for("react.element"); + var REACT_PORTAL_TYPE = Symbol.for("react.portal"); + var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); + var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); + var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); + var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); + var REACT_CONTEXT_TYPE = Symbol.for("react.context"); + var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); + var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); + var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); + var REACT_MEMO_TYPE = Symbol.for("react.memo"); + var REACT_LAZY_TYPE = Symbol.for("react.lazy"); + var REACT_SCOPE_TYPE = Symbol.for("react.scope"); + var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for("react.debug_trace_mode"); + var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); + var REACT_LEGACY_HIDDEN_TYPE = Symbol.for("react.legacy_hidden"); + var REACT_CACHE_TYPE = Symbol.for("react.cache"); + var REACT_TRACING_MARKER_TYPE = Symbol.for("react.tracing_marker"); + var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = "@@iterator"; + function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== "object") { + return null; + } + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + if (typeof maybeIterator === "function") { + return maybeIterator; + } + return null; + } + var assign = Object.assign; + var disabledDepth = 0; + var prevLog; + var prevInfo; + var prevWarn; + var prevError; + var prevGroup; + var prevGroupCollapsed; + var prevGroupEnd; + function disabledLog() { + } + disabledLog.__reactDisabledLog = true; + function disableLogs() { + { + if (disabledDepth === 0) { + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + } + disabledDepth++; + } + } + function reenableLogs() { + { + disabledDepth--; + if (disabledDepth === 0) { + var props = { + configurable: true, + enumerable: true, + writable: true + }; + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + } + if (disabledDepth < 0) { + error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); + } + } + } + var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === void 0) { + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ""; + } + } + return "\n" + prefix + name; + } + } + var reentry = false; + var componentFrameCache; + { + var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); + } + function describeNativeComponentFrame(fn, construct) { + if (!fn || reentry) { + return ""; + } + { + var frame = componentFrameCache.get(fn); + if (frame !== void 0) { + return frame; + } + } + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = void 0; + var previousDispatcher; + { + previousDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = null; + disableLogs(); + } + try { + if (construct) { + var Fake = function() { + throw Error(); + }; + Object.defineProperty(Fake.prototype, "props", { + set: function() { + throw Error(); + } + }); + if (typeof Reflect === "object" && Reflect.construct) { + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + fn(); + } + } catch (sample) { + if (sample && control && typeof sample.stack === "string") { + var sampleLines = sample.stack.split("\n"); + var controlLines = control.stack.split("\n"); + var s = sampleLines.length - 1; + var c2 = controlLines.length - 1; + while (s >= 1 && c2 >= 0 && sampleLines[s] !== controlLines[c2]) { + c2--; + } + for (; s >= 1 && c2 >= 0; s--, c2--) { + if (sampleLines[s] !== controlLines[c2]) { + if (s !== 1 || c2 !== 1) { + do { + s--; + c2--; + if (c2 < 0 || sampleLines[s] !== controlLines[c2]) { + var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); + if (fn.displayName && _frame.includes("")) { + _frame = _frame.replace("", fn.displayName); + } + { + if (typeof fn === "function") { + componentFrameCache.set(fn, _frame); + } + } + return _frame; + } + } while (s >= 1 && c2 >= 0); + } + break; + } + } + } + } finally { + reentry = false; + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } + Error.prepareStackTrace = previousPrepareStackTrace; + } + var name = fn ? fn.displayName || fn.name : ""; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; + { + if (typeof fn === "function") { + componentFrameCache.set(fn, syntheticFrame); + } + } + return syntheticFrame; + } + function describeClassComponentFrame(ctor, source, ownerFn) { + { + return describeNativeComponentFrame(ctor, true); + } + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } + } + function shouldConstruct(Component2) { + var prototype = Component2.prototype; + return !!(prototype && prototype.isReactComponent); + } + function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + if (type == null) { + return ""; + } + if (typeof type === "function") { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + if (typeof type === "string") { + return describeBuiltInComponentFrame(type); + } + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame("Suspense"); + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame("SuspenseList"); + } + if (typeof type === "object") { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + case REACT_MEMO_TYPE: + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) { + } + } + } + } + return ""; + } + function describeFiber(fiber) { + var owner = fiber._debugOwner ? fiber._debugOwner.type : null; + var source = fiber._debugSource; + switch (fiber.tag) { + case HostComponent: + return describeBuiltInComponentFrame(fiber.type); + case LazyComponent: + return describeBuiltInComponentFrame("Lazy"); + case SuspenseComponent: + return describeBuiltInComponentFrame("Suspense"); + case SuspenseListComponent: + return describeBuiltInComponentFrame("SuspenseList"); + case FunctionComponent: + case IndeterminateComponent: + case SimpleMemoComponent: + return describeFunctionComponentFrame(fiber.type); + case ForwardRef: + return describeFunctionComponentFrame(fiber.type.render); + case ClassComponent: + return describeClassComponentFrame(fiber.type); + default: + return ""; + } + } + function getStackByFiberInDevAndProd(workInProgress2) { + try { + var info = ""; + var node = workInProgress2; + do { + info += describeFiber(node); + node = node.return; + } while (node); + return info; + } catch (x) { + return "\nError generating stack: " + x.message + "\n" + x.stack; + } + } + function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + if (displayName) { + return displayName; + } + var functionName = innerType.displayName || innerType.name || ""; + return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; + } + function getContextName(type) { + return type.displayName || "Context"; + } + function getComponentNameFromType(type) { + if (type == null) { + return null; + } + { + if (typeof type.tag === "number") { + error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); + } + } + if (typeof type === "function") { + return type.displayName || type.name || null; + } + if (typeof type === "string") { + return type; + } + switch (type) { + case REACT_FRAGMENT_TYPE: + return "Fragment"; + case REACT_PORTAL_TYPE: + return "Portal"; + case REACT_PROFILER_TYPE: + return "Profiler"; + case REACT_STRICT_MODE_TYPE: + return "StrictMode"; + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + } + if (typeof type === "object") { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + ".Consumer"; + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + ".Provider"; + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, "ForwardRef"); + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + if (outerName !== null) { + return outerName; + } + return getComponentNameFromType(type.type) || "Memo"; + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } + } + } + return null; + } + function getWrappedName$1(outerType, innerType, wrapperName) { + var functionName = innerType.displayName || innerType.name || ""; + return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName); + } + function getContextName$1(type) { + return type.displayName || "Context"; + } + function getComponentNameFromFiber(fiber) { + var tag = fiber.tag, type = fiber.type; + switch (tag) { + case CacheComponent: + return "Cache"; + case ContextConsumer: + var context = type; + return getContextName$1(context) + ".Consumer"; + case ContextProvider: + var provider = type; + return getContextName$1(provider._context) + ".Provider"; + case DehydratedFragment: + return "DehydratedFragment"; + case ForwardRef: + return getWrappedName$1(type, type.render, "ForwardRef"); + case Fragment4: + return "Fragment"; + case HostComponent: + return type; + case HostPortal: + return "Portal"; + case HostRoot: + return "Root"; + case HostText: + return "Text"; + case LazyComponent: + return getComponentNameFromType(type); + case Mode: + if (type === REACT_STRICT_MODE_TYPE) { + return "StrictMode"; + } + return "Mode"; + case OffscreenComponent: + return "Offscreen"; + case Profiler: + return "Profiler"; + case ScopeComponent: + return "Scope"; + case SuspenseComponent: + return "Suspense"; + case SuspenseListComponent: + return "SuspenseList"; + case TracingMarkerComponent: + return "TracingMarker"; + case ClassComponent: + case FunctionComponent: + case IncompleteClassComponent: + case IndeterminateComponent: + case MemoComponent: + case SimpleMemoComponent: + if (typeof type === "function") { + return type.displayName || type.name || null; + } + if (typeof type === "string") { + return type; + } + break; + } + return null; + } + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var current = null; + var isRendering = false; + function getCurrentFiberOwnerNameInDevOrNull() { + { + if (current === null) { + return null; + } + var owner = current._debugOwner; + if (owner !== null && typeof owner !== "undefined") { + return getComponentNameFromFiber(owner); + } + } + return null; + } + function getCurrentFiberStackInDev() { + { + if (current === null) { + return ""; + } + return getStackByFiberInDevAndProd(current); + } + } + function resetCurrentFiber() { + { + ReactDebugCurrentFrame.getCurrentStack = null; + current = null; + isRendering = false; + } + } + function setCurrentFiber(fiber) { + { + ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev; + current = fiber; + isRendering = false; + } + } + function getCurrentFiber() { + { + return current; + } + } + function setIsRendering(rendering) { + { + isRendering = rendering; + } + } + function toString(value) { + return "" + value; + } + function getToStringValue(value) { + switch (typeof value) { + case "boolean": + case "number": + case "string": + case "undefined": + return value; + case "object": + { + checkFormFieldValueStringCoercion(value); + } + return value; + default: + return ""; + } + } + var hasReadOnlyValue = { + button: true, + checkbox: true, + image: true, + hidden: true, + radio: true, + reset: true, + submit: true + }; + function checkControlledValueProps(tagName, props) { + { + if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { + error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."); + } + if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { + error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`."); + } + } + } + function isCheckable(elem) { + var type = elem.type; + var nodeName = elem.nodeName; + return nodeName && nodeName.toLowerCase() === "input" && (type === "checkbox" || type === "radio"); + } + function getTracker(node) { + return node._valueTracker; + } + function detachTracker(node) { + node._valueTracker = null; + } + function getValueFromNode(node) { + var value = ""; + if (!node) { + return value; + } + if (isCheckable(node)) { + value = node.checked ? "true" : "false"; + } else { + value = node.value; + } + return value; + } + function trackValueOnNode(node) { + var valueField = isCheckable(node) ? "checked" : "value"; + var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); + { + checkFormFieldValueStringCoercion(node[valueField]); + } + var currentValue = "" + node[valueField]; + if (node.hasOwnProperty(valueField) || typeof descriptor === "undefined" || typeof descriptor.get !== "function" || typeof descriptor.set !== "function") { + return; + } + var get2 = descriptor.get, set2 = descriptor.set; + Object.defineProperty(node, valueField, { + configurable: true, + get: function() { + return get2.call(this); + }, + set: function(value) { + { + checkFormFieldValueStringCoercion(value); + } + currentValue = "" + value; + set2.call(this, value); + } + }); + Object.defineProperty(node, valueField, { + enumerable: descriptor.enumerable + }); + var tracker = { + getValue: function() { + return currentValue; + }, + setValue: function(value) { + { + checkFormFieldValueStringCoercion(value); + } + currentValue = "" + value; + }, + stopTracking: function() { + detachTracker(node); + delete node[valueField]; + } + }; + return tracker; + } + function track(node) { + if (getTracker(node)) { + return; + } + node._valueTracker = trackValueOnNode(node); + } + function updateValueIfChanged(node) { + if (!node) { + return false; + } + var tracker = getTracker(node); + if (!tracker) { + return true; + } + var lastValue = tracker.getValue(); + var nextValue = getValueFromNode(node); + if (nextValue !== lastValue) { + tracker.setValue(nextValue); + return true; + } + return false; + } + function getActiveElement(doc) { + doc = doc || (typeof document !== "undefined" ? document : void 0); + if (typeof doc === "undefined") { + return null; + } + try { + return doc.activeElement || doc.body; + } catch (e2) { + return doc.body; + } + } + var didWarnValueDefaultValue = false; + var didWarnCheckedDefaultChecked = false; + var didWarnControlledToUncontrolled = false; + var didWarnUncontrolledToControlled = false; + function isControlled(props) { + var usesChecked = props.type === "checkbox" || props.type === "radio"; + return usesChecked ? props.checked != null : props.value != null; + } + function getHostProps(element, props) { + var node = element; + var checked = props.checked; + var hostProps = assign({}, props, { + defaultChecked: void 0, + defaultValue: void 0, + value: void 0, + checked: checked != null ? checked : node._wrapperState.initialChecked + }); + return hostProps; + } + function initWrapperState(element, props) { + { + checkControlledValueProps("input", props); + if (props.checked !== void 0 && props.defaultChecked !== void 0 && !didWarnCheckedDefaultChecked) { + error("%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type); + didWarnCheckedDefaultChecked = true; + } + if (props.value !== void 0 && props.defaultValue !== void 0 && !didWarnValueDefaultValue) { + error("%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type); + didWarnValueDefaultValue = true; + } + } + var node = element; + var defaultValue = props.defaultValue == null ? "" : props.defaultValue; + node._wrapperState = { + initialChecked: props.checked != null ? props.checked : props.defaultChecked, + initialValue: getToStringValue(props.value != null ? props.value : defaultValue), + controlled: isControlled(props) + }; + } + function updateChecked(element, props) { + var node = element; + var checked = props.checked; + if (checked != null) { + setValueForProperty(node, "checked", checked, false); + } + } + function updateWrapper(element, props) { + var node = element; + { + var controlled = isControlled(props); + if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { + error("A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"); + didWarnUncontrolledToControlled = true; + } + if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { + error("A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"); + didWarnControlledToUncontrolled = true; + } + } + updateChecked(element, props); + var value = getToStringValue(props.value); + var type = props.type; + if (value != null) { + if (type === "number") { + if (value === 0 && node.value === "" || // We explicitly want to coerce to number here if possible. + // eslint-disable-next-line + node.value != value) { + node.value = toString(value); + } + } else if (node.value !== toString(value)) { + node.value = toString(value); + } + } else if (type === "submit" || type === "reset") { + node.removeAttribute("value"); + return; + } + { + if (props.hasOwnProperty("value")) { + setDefaultValue(node, props.type, value); + } else if (props.hasOwnProperty("defaultValue")) { + setDefaultValue(node, props.type, getToStringValue(props.defaultValue)); + } + } + { + if (props.checked == null && props.defaultChecked != null) { + node.defaultChecked = !!props.defaultChecked; + } + } + } + function postMountWrapper(element, props, isHydrating2) { + var node = element; + if (props.hasOwnProperty("value") || props.hasOwnProperty("defaultValue")) { + var type = props.type; + var isButton = type === "submit" || type === "reset"; + if (isButton && (props.value === void 0 || props.value === null)) { + return; + } + var initialValue = toString(node._wrapperState.initialValue); + if (!isHydrating2) { + { + if (initialValue !== node.value) { + node.value = initialValue; + } + } + } + { + node.defaultValue = initialValue; + } + } + var name = node.name; + if (name !== "") { + node.name = ""; + } + { + node.defaultChecked = !node.defaultChecked; + node.defaultChecked = !!node._wrapperState.initialChecked; + } + if (name !== "") { + node.name = name; + } + } + function restoreControlledState(element, props) { + var node = element; + updateWrapper(node, props); + updateNamedCousins(node, props); + } + function updateNamedCousins(rootNode, props) { + var name = props.name; + if (props.type === "radio" && name != null) { + var queryRoot = rootNode; + while (queryRoot.parentNode) { + queryRoot = queryRoot.parentNode; + } + { + checkAttributeStringCoercion(name, "name"); + } + var group = queryRoot.querySelectorAll("input[name=" + JSON.stringify("" + name) + '][type="radio"]'); + for (var i2 = 0; i2 < group.length; i2++) { + var otherNode = group[i2]; + if (otherNode === rootNode || otherNode.form !== rootNode.form) { + continue; + } + var otherProps = getFiberCurrentPropsFromNode(otherNode); + if (!otherProps) { + throw new Error("ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."); + } + updateValueIfChanged(otherNode); + updateWrapper(otherNode, otherProps); + } + } + } + function setDefaultValue(node, type, value) { + if ( + // Focused number inputs synchronize on blur. See ChangeEventPlugin.js + type !== "number" || getActiveElement(node.ownerDocument) !== node + ) { + if (value == null) { + node.defaultValue = toString(node._wrapperState.initialValue); + } else if (node.defaultValue !== toString(value)) { + node.defaultValue = toString(value); + } + } + } + var didWarnSelectedSetOnOption = false; + var didWarnInvalidChild = false; + var didWarnInvalidInnerHTML = false; + function validateProps(element, props) { + { + if (props.value == null) { + if (typeof props.children === "object" && props.children !== null) { + React9.Children.forEach(props.children, function(child) { + if (child == null) { + return; + } + if (typeof child === "string" || typeof child === "number") { + return; + } + if (!didWarnInvalidChild) { + didWarnInvalidChild = true; + error("Cannot infer the option value of complex children. Pass a `value` prop or use a plain string as children to