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/base64-js/index.js var require_base64_js = __commonJS({ "node_modules/base64-js/index.js"(exports) { "use strict"; exports.byteLength = byteLength; exports.toByteArray = toByteArray; exports.fromByteArray = fromByteArray; var lookup = []; var revLookup = []; var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; for (i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i]; revLookup[code.charCodeAt(i)] = i; } var i; var len; revLookup["-".charCodeAt(0)] = 62; revLookup["_".charCodeAt(0)] = 63; function getLens(b64) { var len2 = b64.length; if (len2 % 4 > 0) { throw new Error("Invalid string. Length must be a multiple of 4"); } var validLen = b64.indexOf("="); if (validLen === -1) validLen = len2; var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; return [validLen, placeHoldersLen]; } function byteLength(b64) { var lens = getLens(b64); var validLen = lens[0]; var placeHoldersLen = lens[1]; return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; } function _byteLength(b64, validLen, placeHoldersLen) { return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; } function toByteArray(b64) { var tmp; var lens = getLens(b64); var validLen = lens[0]; var placeHoldersLen = lens[1]; var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); var curByte = 0; var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; var i2; for (i2 = 0; i2 < len2; i2 += 4) { tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)]; arr[curByte++] = tmp >> 16 & 255; arr[curByte++] = tmp >> 8 & 255; arr[curByte++] = tmp & 255; } if (placeHoldersLen === 2) { tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4; arr[curByte++] = tmp & 255; } if (placeHoldersLen === 1) { tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2; arr[curByte++] = tmp >> 8 & 255; arr[curByte++] = tmp & 255; } return arr; } function tripletToBase64(num) { return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; } function encodeChunk(uint8, start, end) { var tmp; var output = []; for (var i2 = start; i2 < end; i2 += 3) { tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255); output.push(tripletToBase64(tmp)); } return output.join(""); } function fromByteArray(uint8) { var tmp; var len2 = uint8.length; var extraBytes = len2 % 3; var parts = []; var maxChunkLength = 16383; for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) { parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength)); } if (extraBytes === 1) { tmp = uint8[len2 - 1]; parts.push( lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==" ); } else if (extraBytes === 2) { tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; parts.push( lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=" ); } return parts.join(""); } } }); // node_modules/ieee754/index.js var require_ieee754 = __commonJS({ "node_modules/ieee754/index.js"(exports) { exports.read = function(buffer, offset, isLE, mLen, nBytes) { var e, m; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var nBits = -7; var i = isLE ? nBytes - 1 : 0; var d = isLE ? -1 : 1; var s = buffer[offset + i]; i += d; e = s & (1 << -nBits) - 1; s >>= -nBits; nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) { } m = e & (1 << -nBits) - 1; e >>= -nBits; nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) { } if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : (s ? -1 : 1) * Infinity; } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { var e, m, c; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; var i = isLE ? 0 : nBytes - 1; var d = isLE ? 1 : -1; var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) { } e = e << mLen | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) { } buffer[offset + i - d] |= s * 128; }; } }); // node_modules/@remix-pwa/cache/node_modules/buffer/index.js var require_buffer = __commonJS({ "node_modules/@remix-pwa/cache/node_modules/buffer/index.js"(exports) { "use strict"; var base64 = require_base64_js(); var ieee754 = require_ieee754(); var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; exports.Buffer = Buffer3; exports.SlowBuffer = SlowBuffer; exports.INSPECT_MAX_BYTES = 50; var K_MAX_LENGTH = 2147483647; exports.kMaxLength = K_MAX_LENGTH; Buffer3.TYPED_ARRAY_SUPPORT = typedArraySupport(); if (!Buffer3.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") { console.error( "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support." ); } function typedArraySupport() { try { const arr = new Uint8Array(1); const proto = { foo: function() { return 42; } }; Object.setPrototypeOf(proto, Uint8Array.prototype); Object.setPrototypeOf(arr, proto); return arr.foo() === 42; } catch (e) { return false; } } Object.defineProperty(Buffer3.prototype, "parent", { enumerable: true, get: function() { if (!Buffer3.isBuffer(this)) return void 0; return this.buffer; } }); Object.defineProperty(Buffer3.prototype, "offset", { enumerable: true, get: function() { if (!Buffer3.isBuffer(this)) return void 0; return this.byteOffset; } }); function createBuffer(length) { if (length > K_MAX_LENGTH) { throw new RangeError('The value "' + length + '" is invalid for option "size"'); } const buf = new Uint8Array(length); Object.setPrototypeOf(buf, Buffer3.prototype); return buf; } function Buffer3(arg, encodingOrOffset, length) { if (typeof arg === "number") { if (typeof encodingOrOffset === "string") { throw new TypeError( 'The "string" argument must be of type string. Received type number' ); } return allocUnsafe(arg); } return from(arg, encodingOrOffset, length); } Buffer3.poolSize = 8192; function from(value, encodingOrOffset, length) { if (typeof value === "string") { return fromString(value, encodingOrOffset); } if (ArrayBuffer.isView(value)) { return fromArrayView(value); } if (value == null) { throw new TypeError( "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value ); } if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { return fromArrayBuffer(value, encodingOrOffset, length); } if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { return fromArrayBuffer(value, encodingOrOffset, length); } if (typeof value === "number") { throw new TypeError( 'The "value" argument must not be of type number. Received type number' ); } const valueOf = value.valueOf && value.valueOf(); if (valueOf != null && valueOf !== value) { return Buffer3.from(valueOf, encodingOrOffset, length); } const b2 = fromObject(value); if (b2) return b2; if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { return Buffer3.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length); } throw new TypeError( "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value ); } Buffer3.from = function(value, encodingOrOffset, length) { return from(value, encodingOrOffset, length); }; Object.setPrototypeOf(Buffer3.prototype, Uint8Array.prototype); Object.setPrototypeOf(Buffer3, Uint8Array); function assertSize(size) { if (typeof size !== "number") { throw new TypeError('"size" argument must be of type number'); } else if (size < 0) { throw new RangeError('The value "' + size + '" is invalid for option "size"'); } } function alloc(size, fill, encoding) { assertSize(size); if (size <= 0) { return createBuffer(size); } if (fill !== void 0) { return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); } return createBuffer(size); } Buffer3.alloc = function(size, fill, encoding) { return alloc(size, fill, encoding); }; function allocUnsafe(size) { assertSize(size); return createBuffer(size < 0 ? 0 : checked(size) | 0); } Buffer3.allocUnsafe = function(size) { return allocUnsafe(size); }; Buffer3.allocUnsafeSlow = function(size) { return allocUnsafe(size); }; function fromString(string, encoding) { if (typeof encoding !== "string" || encoding === "") { encoding = "utf8"; } if (!Buffer3.isEncoding(encoding)) { throw new TypeError("Unknown encoding: " + encoding); } const length = byteLength(string, encoding) | 0; let buf = createBuffer(length); const actual = buf.write(string, encoding); if (actual !== length) { buf = buf.slice(0, actual); } return buf; } function fromArrayLike(array) { const length = array.length < 0 ? 0 : checked(array.length) | 0; const buf = createBuffer(length); for (let i = 0; i < length; i += 1) { buf[i] = array[i] & 255; } return buf; } function fromArrayView(arrayView) { if (isInstance(arrayView, Uint8Array)) { const copy = new Uint8Array(arrayView); return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); } return fromArrayLike(arrayView); } function fromArrayBuffer(array, byteOffset, length) { if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('"offset" is outside of buffer bounds'); } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('"length" is outside of buffer bounds'); } let buf; if (byteOffset === void 0 && length === void 0) { buf = new Uint8Array(array); } else if (length === void 0) { buf = new Uint8Array(array, byteOffset); } else { buf = new Uint8Array(array, byteOffset, length); } Object.setPrototypeOf(buf, Buffer3.prototype); return buf; } function fromObject(obj) { if (Buffer3.isBuffer(obj)) { const len = checked(obj.length) | 0; const buf = createBuffer(len); if (buf.length === 0) { return buf; } obj.copy(buf, 0, 0, len); return buf; } if (obj.length !== void 0) { if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { return createBuffer(0); } return fromArrayLike(obj); } if (obj.type === "Buffer" && Array.isArray(obj.data)) { return fromArrayLike(obj.data); } } function checked(length) { if (length >= K_MAX_LENGTH) { throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); } return length | 0; } function SlowBuffer(length) { if (+length != length) { length = 0; } return Buffer3.alloc(+length); } Buffer3.isBuffer = function isBuffer(b2) { return b2 != null && b2._isBuffer === true && b2 !== Buffer3.prototype; }; Buffer3.compare = function compare(a, b2) { if (isInstance(a, Uint8Array)) a = Buffer3.from(a, a.offset, a.byteLength); if (isInstance(b2, Uint8Array)) b2 = Buffer3.from(b2, b2.offset, b2.byteLength); if (!Buffer3.isBuffer(a) || !Buffer3.isBuffer(b2)) { throw new TypeError( 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' ); } if (a === b2) return 0; let x = a.length; let y2 = b2.length; for (let i = 0, len = Math.min(x, y2); i < len; ++i) { if (a[i] !== b2[i]) { x = a[i]; y2 = b2[i]; break; } } if (x < y2) return -1; if (y2 < x) return 1; return 0; }; Buffer3.isEncoding = function isEncoding(encoding) { switch (String(encoding).toLowerCase()) { case "hex": case "utf8": case "utf-8": case "ascii": case "latin1": case "binary": case "base64": case "ucs2": case "ucs-2": case "utf16le": case "utf-16le": return true; default: return false; } }; Buffer3.concat = function concat(list, length) { if (!Array.isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers'); } if (list.length === 0) { return Buffer3.alloc(0); } let i; if (length === void 0) { length = 0; for (i = 0; i < list.length; ++i) { length += list[i].length; } } const buffer = Buffer3.allocUnsafe(length); let pos = 0; for (i = 0; i < list.length; ++i) { let buf = list[i]; if (isInstance(buf, Uint8Array)) { if (pos + buf.length > buffer.length) { if (!Buffer3.isBuffer(buf)) buf = Buffer3.from(buf); buf.copy(buffer, pos); } else { Uint8Array.prototype.set.call( buffer, buf, pos ); } } else if (!Buffer3.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers'); } else { buf.copy(buffer, pos); } pos += buf.length; } return buffer; }; function byteLength(string, encoding) { if (Buffer3.isBuffer(string)) { return string.length; } if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { return string.byteLength; } if (typeof string !== "string") { throw new TypeError( 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string ); } const len = string.length; const mustMatch = arguments.length > 2 && arguments[2] === true; if (!mustMatch && len === 0) return 0; let loweredCase = false; for (; ; ) { switch (encoding) { case "ascii": case "latin1": case "binary": return len; case "utf8": case "utf-8": return utf8ToBytes(string).length; case "ucs2": case "ucs-2": case "utf16le": case "utf-16le": return len * 2; case "hex": return len >>> 1; case "base64": return base64ToBytes(string).length; default: if (loweredCase) { return mustMatch ? -1 : utf8ToBytes(string).length; } encoding = ("" + encoding).toLowerCase(); loweredCase = true; } } } Buffer3.byteLength = byteLength; function slowToString(encoding, start, end) { let loweredCase = false; if (start === void 0 || start < 0) { start = 0; } if (start > this.length) { return ""; } if (end === void 0 || end > this.length) { end = this.length; } if (end <= 0) { return ""; } end >>>= 0; start >>>= 0; if (end <= start) { return ""; } if (!encoding) encoding = "utf8"; while (true) { switch (encoding) { case "hex": return hexSlice(this, start, end); case "utf8": case "utf-8": return utf8Slice(this, start, end); case "ascii": return asciiSlice(this, start, end); case "latin1": case "binary": return latin1Slice(this, start, end); case "base64": return base64Slice(this, start, end); case "ucs2": case "ucs-2": case "utf16le": case "utf-16le": return utf16leSlice(this, start, end); default: if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); encoding = (encoding + "").toLowerCase(); loweredCase = true; } } } Buffer3.prototype._isBuffer = true; function swap(b2, n, m) { const i = b2[n]; b2[n] = b2[m]; b2[m] = i; } Buffer3.prototype.swap16 = function swap16() { const len = this.length; if (len % 2 !== 0) { throw new RangeError("Buffer size must be a multiple of 16-bits"); } for (let i = 0; i < len; i += 2) { swap(this, i, i + 1); } return this; }; Buffer3.prototype.swap32 = function swap32() { const len = this.length; if (len % 4 !== 0) { throw new RangeError("Buffer size must be a multiple of 32-bits"); } for (let i = 0; i < len; i += 4) { swap(this, i, i + 3); swap(this, i + 1, i + 2); } return this; }; Buffer3.prototype.swap64 = function swap64() { const len = this.length; if (len % 8 !== 0) { throw new RangeError("Buffer size must be a multiple of 64-bits"); } for (let i = 0; i < len; i += 8) { swap(this, i, i + 7); swap(this, i + 1, i + 6); swap(this, i + 2, i + 5); swap(this, i + 3, i + 4); } return this; }; Buffer3.prototype.toString = function toString() { const length = this.length; if (length === 0) return ""; if (arguments.length === 0) return utf8Slice(this, 0, length); return slowToString.apply(this, arguments); }; Buffer3.prototype.toLocaleString = Buffer3.prototype.toString; Buffer3.prototype.equals = function equals(b2) { if (!Buffer3.isBuffer(b2)) throw new TypeError("Argument must be a Buffer"); if (this === b2) return true; return Buffer3.compare(this, b2) === 0; }; Buffer3.prototype.inspect = function inspect() { let str = ""; const max = exports.INSPECT_MAX_BYTES; str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); if (this.length > max) str += " ... "; return ""; }; if (customInspectSymbol) { Buffer3.prototype[customInspectSymbol] = Buffer3.prototype.inspect; } Buffer3.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { if (isInstance(target, Uint8Array)) { target = Buffer3.from(target, target.offset, target.byteLength); } if (!Buffer3.isBuffer(target)) { throw new TypeError( 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target ); } if (start === void 0) { start = 0; } if (end === void 0) { end = target ? target.length : 0; } if (thisStart === void 0) { thisStart = 0; } if (thisEnd === void 0) { thisEnd = this.length; } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError("out of range index"); } if (thisStart >= thisEnd && start >= end) { return 0; } if (thisStart >= thisEnd) { return -1; } if (start >= end) { return 1; } start >>>= 0; end >>>= 0; thisStart >>>= 0; thisEnd >>>= 0; if (this === target) return 0; let x = thisEnd - thisStart; let y2 = end - start; const len = Math.min(x, y2); const thisCopy = this.slice(thisStart, thisEnd); const targetCopy = target.slice(start, end); for (let i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i]; y2 = targetCopy[i]; break; } } if (x < y2) return -1; if (y2 < x) return 1; return 0; }; function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { if (buffer.length === 0) return -1; if (typeof byteOffset === "string") { encoding = byteOffset; byteOffset = 0; } else if (byteOffset > 2147483647) { byteOffset = 2147483647; } else if (byteOffset < -2147483648) { byteOffset = -2147483648; } byteOffset = +byteOffset; if (numberIsNaN(byteOffset)) { byteOffset = dir ? 0 : buffer.length - 1; } if (byteOffset < 0) byteOffset = buffer.length + byteOffset; if (byteOffset >= buffer.length) { if (dir) return -1; else byteOffset = buffer.length - 1; } else if (byteOffset < 0) { if (dir) byteOffset = 0; else return -1; } if (typeof val === "string") { val = Buffer3.from(val, encoding); } if (Buffer3.isBuffer(val)) { if (val.length === 0) { return -1; } return arrayIndexOf(buffer, val, byteOffset, encoding, dir); } else if (typeof val === "number") { val = val & 255; if (typeof Uint8Array.prototype.indexOf === "function") { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); } } return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); } throw new TypeError("val must be string, number or Buffer"); } function arrayIndexOf(arr, val, byteOffset, encoding, dir) { let indexSize = 1; let arrLength = arr.length; let valLength = val.length; if (encoding !== void 0) { encoding = String(encoding).toLowerCase(); if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { if (arr.length < 2 || val.length < 2) { return -1; } indexSize = 2; arrLength /= 2; valLength /= 2; byteOffset /= 2; } } function read(buf, i2) { if (indexSize === 1) { return buf[i2]; } else { return buf.readUInt16BE(i2 * indexSize); } } let i; if (dir) { let foundIndex = -1; for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i; if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; } else { if (foundIndex !== -1) i -= i - foundIndex; foundIndex = -1; } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; for (i = byteOffset; i >= 0; i--) { let found = true; for (let j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false; break; } } if (found) return i; } } return -1; } Buffer3.prototype.includes = function includes(val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1; }; Buffer3.prototype.indexOf = function indexOf(val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true); }; Buffer3.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false); }; function hexWrite(buf, string, offset, length) { offset = Number(offset) || 0; const remaining = buf.length - offset; if (!length) { length = remaining; } else { length = Number(length); if (length > remaining) { length = remaining; } } const strLen = string.length; if (length > strLen / 2) { length = strLen / 2; } let i; for (i = 0; i < length; ++i) { const parsed = parseInt(string.substr(i * 2, 2), 16); if (numberIsNaN(parsed)) return i; buf[offset + i] = parsed; } return i; } function utf8Write(buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); } function asciiWrite(buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length); } function base64Write(buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length); } function ucs2Write(buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); } Buffer3.prototype.write = function write(string, offset, length, encoding) { if (offset === void 0) { encoding = "utf8"; length = this.length; offset = 0; } else if (length === void 0 && typeof offset === "string") { encoding = offset; length = this.length; offset = 0; } else if (isFinite(offset)) { offset = offset >>> 0; if (isFinite(length)) { length = length >>> 0; if (encoding === void 0) encoding = "utf8"; } else { encoding = length; length = void 0; } } else { throw new Error( "Buffer.write(string, encoding, offset[, length]) is no longer supported" ); } const remaining = this.length - offset; if (length === void 0 || length > remaining) length = remaining; if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { throw new RangeError("Attempt to write outside buffer bounds"); } if (!encoding) encoding = "utf8"; let loweredCase = false; for (; ; ) { switch (encoding) { case "hex": return hexWrite(this, string, offset, length); case "utf8": case "utf-8": return utf8Write(this, string, offset, length); case "ascii": case "latin1": case "binary": return asciiWrite(this, string, offset, length); case "base64": return base64Write(this, string, offset, length); case "ucs2": case "ucs-2": case "utf16le": case "utf-16le": return ucs2Write(this, string, offset, length); default: if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); encoding = ("" + encoding).toLowerCase(); loweredCase = true; } } }; Buffer3.prototype.toJSON = function toJSON2() { return { type: "Buffer", data: Array.prototype.slice.call(this._arr || this, 0) }; }; function base64Slice(buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf); } else { return base64.fromByteArray(buf.slice(start, end)); } } function utf8Slice(buf, start, end) { end = Math.min(buf.length, end); const res = []; let i = start; while (i < end) { const firstByte = buf[i]; let codePoint = null; let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; if (i + bytesPerSequence <= end) { let secondByte, thirdByte, fourthByte, tempCodePoint; switch (bytesPerSequence) { case 1: if (firstByte < 128) { codePoint = firstByte; } break; case 2: secondByte = buf[i + 1]; if ((secondByte & 192) === 128) { tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; if (tempCodePoint > 127) { codePoint = tempCodePoint; } } break; case 3: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { codePoint = tempCodePoint; } } break; case 4: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; fourthByte = buf[i + 3]; if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; if (tempCodePoint > 65535 && tempCodePoint < 1114112) { codePoint = tempCodePoint; } } } } if (codePoint === null) { codePoint = 65533; bytesPerSequence = 1; } else if (codePoint > 65535) { codePoint -= 65536; res.push(codePoint >>> 10 & 1023 | 55296); codePoint = 56320 | codePoint & 1023; } res.push(codePoint); i += bytesPerSequence; } return decodeCodePointsArray(res); } var MAX_ARGUMENTS_LENGTH = 4096; function decodeCodePointsArray(codePoints) { const len = codePoints.length; if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints); } let res = ""; let i = 0; while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ); } return res; } function asciiSlice(buf, start, end) { let ret = ""; end = Math.min(buf.length, end); for (let i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 127); } return ret; } function latin1Slice(buf, start, end) { let ret = ""; end = Math.min(buf.length, end); for (let i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]); } return ret; } function hexSlice(buf, start, end) { const len = buf.length; if (!start || start < 0) start = 0; if (!end || end < 0 || end > len) end = len; let out = ""; for (let i = start; i < end; ++i) { out += hexSliceLookupTable[buf[i]]; } return out; } function utf16leSlice(buf, start, end) { const bytes = buf.slice(start, end); let res = ""; for (let i = 0; i < bytes.length - 1; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); } return res; } Buffer3.prototype.slice = function slice(start, end) { const len = this.length; start = ~~start; end = end === void 0 ? len : ~~end; if (start < 0) { start += len; if (start < 0) start = 0; } else if (start > len) { start = len; } if (end < 0) { end += len; if (end < 0) end = 0; } else if (end > len) { end = len; } if (end < start) end = start; const newBuf = this.subarray(start, end); Object.setPrototypeOf(newBuf, Buffer3.prototype); return newBuf; }; function checkOffset(offset, ext, length) { if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint"); if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length"); } Buffer3.prototype.readUintLE = Buffer3.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) { offset = offset >>> 0; byteLength2 = byteLength2 >>> 0; if (!noAssert) checkOffset(offset, byteLength2, this.length); let val = this[offset]; let mul = 1; let i = 0; while (++i < byteLength2 && (mul *= 256)) { val += this[offset + i] * mul; } return val; }; Buffer3.prototype.readUintBE = Buffer3.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) { offset = offset >>> 0; byteLength2 = byteLength2 >>> 0; if (!noAssert) { checkOffset(offset, byteLength2, this.length); } let val = this[offset + --byteLength2]; let mul = 1; while (byteLength2 > 0 && (mul *= 256)) { val += this[offset + --byteLength2] * mul; } return val; }; Buffer3.prototype.readUint8 = Buffer3.prototype.readUInt8 = function readUInt8(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 1, this.length); return this[offset]; }; Buffer3.prototype.readUint16LE = Buffer3.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | this[offset + 1] << 8; }; Buffer3.prototype.readUint16BE = Buffer3.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] << 8 | this[offset + 1]; }; Buffer3.prototype.readUint32LE = Buffer3.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; }; Buffer3.prototype.readUint32BE = Buffer3.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); }; Buffer3.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) { offset = offset >>> 0; validateNumber(offset, "offset"); const first = this[offset]; const last = this[offset + 7]; if (first === void 0 || last === void 0) { boundsError(offset, this.length - 8); } const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24; const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24; return BigInt(lo) + (BigInt(hi) << BigInt(32)); }); Buffer3.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) { offset = offset >>> 0; validateNumber(offset, "offset"); const first = this[offset]; const last = this[offset + 7]; if (first === void 0 || last === void 0) { boundsError(offset, this.length - 8); } const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last; return (BigInt(hi) << BigInt(32)) + BigInt(lo); }); Buffer3.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) { offset = offset >>> 0; byteLength2 = byteLength2 >>> 0; if (!noAssert) checkOffset(offset, byteLength2, this.length); let val = this[offset]; let mul = 1; let i = 0; while (++i < byteLength2 && (mul *= 256)) { val += this[offset + i] * mul; } mul *= 128; if (val >= mul) val -= Math.pow(2, 8 * byteLength2); return val; }; Buffer3.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) { offset = offset >>> 0; byteLength2 = byteLength2 >>> 0; if (!noAssert) checkOffset(offset, byteLength2, this.length); let i = byteLength2; let mul = 1; let val = this[offset + --i]; while (i > 0 && (mul *= 256)) { val += this[offset + --i] * mul; } mul *= 128; if (val >= mul) val -= Math.pow(2, 8 * byteLength2); return val; }; Buffer3.prototype.readInt8 = function readInt8(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 128)) return this[offset]; return (255 - this[offset] + 1) * -1; }; Buffer3.prototype.readInt16LE = function readInt16LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); const val = this[offset] | this[offset + 1] << 8; return val & 32768 ? val | 4294901760 : val; }; Buffer3.prototype.readInt16BE = function readInt16BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 2, this.length); const val = this[offset + 1] | this[offset] << 8; return val & 32768 ? val | 4294901760 : val; }; Buffer3.prototype.readInt32LE = function readInt32LE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; }; Buffer3.prototype.readInt32BE = function readInt32BE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; }; Buffer3.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) { offset = offset >>> 0; validateNumber(offset, "offset"); const first = this[offset]; const last = this[offset + 7]; if (first === void 0 || last === void 0) { boundsError(offset, this.length - 8); } const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24); return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24); }); Buffer3.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) { offset = offset >>> 0; validateNumber(offset, "offset"); const first = this[offset]; const last = this[offset + 7]; if (first === void 0 || last === void 0) { boundsError(offset, this.length - 8); } const val = (first << 24) + // Overflow this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last); }); Buffer3.prototype.readFloatLE = function readFloatLE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return ieee754.read(this, offset, true, 23, 4); }; Buffer3.prototype.readFloatBE = function readFloatBE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 4, this.length); return ieee754.read(this, offset, false, 23, 4); }; Buffer3.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 8, this.length); return ieee754.read(this, offset, true, 52, 8); }; Buffer3.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { offset = offset >>> 0; if (!noAssert) checkOffset(offset, 8, this.length); return ieee754.read(this, offset, false, 52, 8); }; function checkInt(buf, value, offset, ext, max, min) { if (!Buffer3.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); if (offset + ext > buf.length) throw new RangeError("Index out of range"); } Buffer3.prototype.writeUintLE = Buffer3.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) { value = +value; offset = offset >>> 0; byteLength2 = byteLength2 >>> 0; if (!noAssert) { const maxBytes = Math.pow(2, 8 * byteLength2) - 1; checkInt(this, value, offset, byteLength2, maxBytes, 0); } let mul = 1; let i = 0; this[offset] = value & 255; while (++i < byteLength2 && (mul *= 256)) { this[offset + i] = value / mul & 255; } return offset + byteLength2; }; Buffer3.prototype.writeUintBE = Buffer3.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) { value = +value; offset = offset >>> 0; byteLength2 = byteLength2 >>> 0; if (!noAssert) { const maxBytes = Math.pow(2, 8 * byteLength2) - 1; checkInt(this, value, offset, byteLength2, maxBytes, 0); } let i = byteLength2 - 1; let mul = 1; this[offset + i] = value & 255; while (--i >= 0 && (mul *= 256)) { this[offset + i] = value / mul & 255; } return offset + byteLength2; }; Buffer3.prototype.writeUint8 = Buffer3.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 1, 255, 0); this[offset] = value & 255; return offset + 1; }; Buffer3.prototype.writeUint16LE = Buffer3.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 65535, 0); this[offset] = value & 255; this[offset + 1] = value >>> 8; return offset + 2; }; Buffer3.prototype.writeUint16BE = Buffer3.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 65535, 0); this[offset] = value >>> 8; this[offset + 1] = value & 255; return offset + 2; }; Buffer3.prototype.writeUint32LE = Buffer3.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0); this[offset + 3] = value >>> 24; this[offset + 2] = value >>> 16; this[offset + 1] = value >>> 8; this[offset] = value & 255; return offset + 4; }; Buffer3.prototype.writeUint32BE = Buffer3.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0); this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 255; return offset + 4; }; function wrtBigUInt64LE(buf, value, offset, min, max) { checkIntBI(value, min, max, buf, offset, 7); let lo = Number(value & BigInt(4294967295)); buf[offset++] = lo; lo = lo >> 8; buf[offset++] = lo; lo = lo >> 8; buf[offset++] = lo; lo = lo >> 8; buf[offset++] = lo; let hi = Number(value >> BigInt(32) & BigInt(4294967295)); buf[offset++] = hi; hi = hi >> 8; buf[offset++] = hi; hi = hi >> 8; buf[offset++] = hi; hi = hi >> 8; buf[offset++] = hi; return offset; } function wrtBigUInt64BE(buf, value, offset, min, max) { checkIntBI(value, min, max, buf, offset, 7); let lo = Number(value & BigInt(4294967295)); buf[offset + 7] = lo; lo = lo >> 8; buf[offset + 6] = lo; lo = lo >> 8; buf[offset + 5] = lo; lo = lo >> 8; buf[offset + 4] = lo; let hi = Number(value >> BigInt(32) & BigInt(4294967295)); buf[offset + 3] = hi; hi = hi >> 8; buf[offset + 2] = hi; hi = hi >> 8; buf[offset + 1] = hi; hi = hi >> 8; buf[offset] = hi; return offset + 8; } Buffer3.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) { return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); }); Buffer3.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) { return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); }); Buffer3.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { const limit = Math.pow(2, 8 * byteLength2 - 1); checkInt(this, value, offset, byteLength2, limit - 1, -limit); } let i = 0; let mul = 1; let sub = 0; this[offset] = value & 255; while (++i < byteLength2 && (mul *= 256)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1; } this[offset + i] = (value / mul >> 0) - sub & 255; } return offset + byteLength2; }; Buffer3.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { const limit = Math.pow(2, 8 * byteLength2 - 1); checkInt(this, value, offset, byteLength2, limit - 1, -limit); } let i = byteLength2 - 1; let mul = 1; let sub = 0; this[offset + i] = value & 255; while (--i >= 0 && (mul *= 256)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1; } this[offset + i] = (value / mul >> 0) - sub & 255; } return offset + byteLength2; }; Buffer3.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 1, 127, -128); if (value < 0) value = 255 + value + 1; this[offset] = value & 255; return offset + 1; }; Buffer3.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768); this[offset] = value & 255; this[offset + 1] = value >>> 8; return offset + 2; }; Buffer3.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768); this[offset] = value >>> 8; this[offset + 1] = value & 255; return offset + 2; }; Buffer3.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648); this[offset] = value & 255; this[offset + 1] = value >>> 8; this[offset + 2] = value >>> 16; this[offset + 3] = value >>> 24; return offset + 4; }; Buffer3.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648); if (value < 0) value = 4294967295 + value + 1; this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 255; return offset + 4; }; Buffer3.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) { return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); }); Buffer3.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) { return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); }); function checkIEEE754(buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError("Index out of range"); if (offset < 0) throw new RangeError("Index out of range"); } function writeFloat(buf, value, offset, littleEndian, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22); } ieee754.write(buf, value, offset, littleEndian, 23, 4); return offset + 4; } Buffer3.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert); }; Buffer3.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert); }; function writeDouble(buf, value, offset, littleEndian, noAssert) { value = +value; offset = offset >>> 0; if (!noAssert) { checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292); } ieee754.write(buf, value, offset, littleEndian, 52, 8); return offset + 8; } Buffer3.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert); }; Buffer3.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert); }; Buffer3.prototype.copy = function copy(target, targetStart, start, end) { if (!Buffer3.isBuffer(target)) throw new TypeError("argument should be a Buffer"); if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; if (!targetStart) targetStart = 0; if (end > 0 && end < start) end = start; if (end === start) return 0; if (target.length === 0 || this.length === 0) return 0; if (targetStart < 0) { throw new RangeError("targetStart out of bounds"); } if (start < 0 || start >= this.length) throw new RangeError("Index out of range"); if (end < 0) throw new RangeError("sourceEnd out of bounds"); if (end > this.length) end = this.length; if (target.length - targetStart < end - start) { end = target.length - targetStart + start; } const len = end - start; if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { this.copyWithin(targetStart, start, end); } else { Uint8Array.prototype.set.call( target, this.subarray(start, end), targetStart ); } return len; }; Buffer3.prototype.fill = function fill(val, start, end, encoding) { if (typeof val === "string") { if (typeof start === "string") { encoding = start; start = 0; end = this.length; } else if (typeof end === "string") { encoding = end; end = this.length; } if (encoding !== void 0 && typeof encoding !== "string") { throw new TypeError("encoding must be a string"); } if (typeof encoding === "string" && !Buffer3.isEncoding(encoding)) { throw new TypeError("Unknown encoding: " + encoding); } if (val.length === 1) { const code = val.charCodeAt(0); if (encoding === "utf8" && code < 128 || encoding === "latin1") { val = code; } } } else if (typeof val === "number") { val = val & 255; } else if (typeof val === "boolean") { val = Number(val); } if (start < 0 || this.length < start || this.length < end) { throw new RangeError("Out of range index"); } if (end <= start) { return this; } start = start >>> 0; end = end === void 0 ? this.length : end >>> 0; if (!val) val = 0; let i; if (typeof val === "number") { for (i = start; i < end; ++i) { this[i] = val; } } else { const bytes = Buffer3.isBuffer(val) ? val : Buffer3.from(val, encoding); const len = bytes.length; if (len === 0) { throw new TypeError('The value "' + val + '" is invalid for argument "value"'); } for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; } } return this; }; var errors = {}; function E(sym, getMessage, Base) { errors[sym] = class NodeError extends Base { constructor() { super(); Object.defineProperty(this, "message", { value: getMessage.apply(this, arguments), writable: true, configurable: true }); this.name = `${this.name} [${sym}]`; this.stack; delete this.name; } get code() { return sym; } set code(value) { Object.defineProperty(this, "code", { configurable: true, enumerable: true, value, writable: true }); } toString() { return `${this.name} [${sym}]: ${this.message}`; } }; } E( "ERR_BUFFER_OUT_OF_BOUNDS", function(name) { if (name) { return `${name} is outside of buffer bounds`; } return "Attempt to access memory outside buffer bounds"; }, RangeError ); E( "ERR_INVALID_ARG_TYPE", function(name, actual) { return `The "${name}" argument must be of type number. Received type ${typeof actual}`; }, TypeError ); E( "ERR_OUT_OF_RANGE", function(str, range, input) { let msg = `The value of "${str}" is out of range.`; let received = input; if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { received = addNumericalSeparator(String(input)); } else if (typeof input === "bigint") { received = String(input); if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { received = addNumericalSeparator(received); } received += "n"; } msg += ` It must be ${range}. Received ${received}`; return msg; }, RangeError ); function addNumericalSeparator(val) { let res = ""; let i = val.length; const start = val[0] === "-" ? 1 : 0; for (; i >= start + 4; i -= 3) { res = `_${val.slice(i - 3, i)}${res}`; } return `${val.slice(0, i)}${res}`; } function checkBounds(buf, offset, byteLength2) { validateNumber(offset, "offset"); if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) { boundsError(offset, buf.length - (byteLength2 + 1)); } } function checkIntBI(value, min, max, buf, offset, byteLength2) { if (value > max || value < min) { const n = typeof min === "bigint" ? "n" : ""; let range; if (byteLength2 > 3) { if (min === 0 || min === BigInt(0)) { range = `>= 0${n} and < 2${n} ** ${(byteLength2 + 1) * 8}${n}`; } else { range = `>= -(2${n} ** ${(byteLength2 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n}`; } } else { range = `>= ${min}${n} and <= ${max}${n}`; } throw new errors.ERR_OUT_OF_RANGE("value", range, value); } checkBounds(buf, offset, byteLength2); } function validateNumber(value, name) { if (typeof value !== "number") { throw new errors.ERR_INVALID_ARG_TYPE(name, "number", value); } } function boundsError(value, length, type) { if (Math.floor(value) !== value) { validateNumber(value, type); throw new errors.ERR_OUT_OF_RANGE(type || "offset", "an integer", value); } if (length < 0) { throw new errors.ERR_BUFFER_OUT_OF_BOUNDS(); } throw new errors.ERR_OUT_OF_RANGE( type || "offset", `>= ${type ? 1 : 0} and <= ${length}`, value ); } var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; function base64clean(str) { str = str.split("=")[0]; str = str.trim().replace(INVALID_BASE64_RE, ""); if (str.length < 2) return ""; while (str.length % 4 !== 0) { str = str + "="; } return str; } function utf8ToBytes(string, units) { units = units || Infinity; let codePoint; const length = string.length; let leadSurrogate = null; const bytes = []; for (let i = 0; i < length; ++i) { codePoint = string.charCodeAt(i); if (codePoint > 55295 && codePoint < 57344) { if (!leadSurrogate) { if (codePoint > 56319) { if ((units -= 3) > -1) bytes.push(239, 191, 189); continue; } else if (i + 1 === length) { if ((units -= 3) > -1) bytes.push(239, 191, 189); continue; } leadSurrogate = codePoint; continue; } if (codePoint < 56320) { if ((units -= 3) > -1) bytes.push(239, 191, 189); leadSurrogate = codePoint; continue; } codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; } else if (leadSurrogate) { if ((units -= 3) > -1) bytes.push(239, 191, 189); } leadSurrogate = null; if (codePoint < 128) { if ((units -= 1) < 0) break; bytes.push(codePoint); } else if (codePoint < 2048) { if ((units -= 2) < 0) break; bytes.push( codePoint >> 6 | 192, codePoint & 63 | 128 ); } else if (codePoint < 65536) { if ((units -= 3) < 0) break; bytes.push( codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128 ); } else if (codePoint < 1114112) { if ((units -= 4) < 0) break; bytes.push( codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128 ); } else { throw new Error("Invalid code point"); } } return bytes; } function asciiToBytes(str) { const byteArray = []; for (let i = 0; i < str.length; ++i) { byteArray.push(str.charCodeAt(i) & 255); } return byteArray; } function utf16leToBytes(str, units) { let c, hi, lo; const byteArray = []; for (let i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break; c = str.charCodeAt(i); hi = c >> 8; lo = c % 256; byteArray.push(lo); byteArray.push(hi); } return byteArray; } function base64ToBytes(str) { return base64.toByteArray(base64clean(str)); } function blitBuffer(src, dst, offset, length) { let i; for (i = 0; i < length; ++i) { if (i + offset >= dst.length || i >= src.length) break; dst[i + offset] = src[i]; } return i; } function isInstance(obj, type) { return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; } function numberIsNaN(obj) { return obj !== obj; } var hexSliceLookupTable = function() { const alphabet = "0123456789abcdef"; const table = new Array(256); for (let i = 0; i < 16; ++i) { const i16 = i * 16; for (let j = 0; j < 16; ++j) { table[i16 + j] = alphabet[i] + alphabet[j]; } } return table; }(); function defineBigIntMethod(fn) { return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn; } function BufferBigIntNotDefined() { throw new Error("BigInt not supported"); } } }); // routes-module:root.jsx?worker var require_root = __commonJS({ "routes-module:root.jsx?worker"(exports, module) { module.exports = {}; } }); // routes-module:routes/manifest[.]webmanifest.ts?worker var require_manifest_webmanifest = __commonJS({ "routes-module:routes/manifest[.]webmanifest.ts?worker"(exports, module) { module.exports = {}; } }); // node_modules/@remix-run/router/dist/router.js var router_exports = {}; __export(router_exports, { AbortedDeferredError: () => AbortedDeferredError, Action: () => Action, IDLE_BLOCKER: () => IDLE_BLOCKER, IDLE_FETCHER: () => IDLE_FETCHER, IDLE_NAVIGATION: () => IDLE_NAVIGATION, UNSAFE_DEFERRED_SYMBOL: () => UNSAFE_DEFERRED_SYMBOL, UNSAFE_DeferredData: () => DeferredData, UNSAFE_ErrorResponseImpl: () => ErrorResponseImpl, UNSAFE_convertRouteMatchToUiMatch: () => convertRouteMatchToUiMatch, UNSAFE_convertRoutesToDataRoutes: () => convertRoutesToDataRoutes, UNSAFE_getResolveToMatches: () => getResolveToMatches, UNSAFE_invariant: () => invariant, UNSAFE_warning: () => warning, createBrowserHistory: () => createBrowserHistory, createHashHistory: () => createHashHistory, createMemoryHistory: () => createMemoryHistory, createPath: () => createPath, createRouter: () => createRouter, createStaticHandler: () => createStaticHandler, defer: () => defer, generatePath: () => generatePath, getStaticContextFromError: () => getStaticContextFromError, getToPathname: () => getToPathname, isDeferredData: () => isDeferredData, isRouteErrorResponse: () => isRouteErrorResponse, joinPaths: () => joinPaths, json: () => json, matchPath: () => matchPath, matchRoutes: () => matchRoutes, normalizePathname: () => normalizePathname, parsePath: () => parsePath, redirect: () => redirect, redirectDocument: () => redirectDocument, resolvePath: () => resolvePath, resolveTo: () => resolveTo, stripBasename: () => stripBasename }); function _extends() { _extends = Object.assign ? Object.assign.bind() : function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function createMemoryHistory(options) { if (options === void 0) { options = {}; } let { initialEntries = ["/"], initialIndex, v5Compat = false } = options; let entries; entries = initialEntries.map((entry2, index2) => createMemoryLocation(entry2, typeof entry2 === "string" ? null : entry2.state, index2 === 0 ? "default" : void 0)); let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex); let action = Action.Pop; let listener = null; function clampIndex(n) { return Math.min(Math.max(n, 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 : createPath(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" ? parsePath(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 : createPath(to); } return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options); } function createHashHistory(options) { if (options === void 0) { options = {}; } function createHashLocation(window2, globalHistory) { let { pathname = "/", search = "", hash = "" } = parsePath(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 : createPath(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 invariant(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 (e) { } } } 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 = _extends({ pathname: typeof current === "string" ? current : current.pathname, search: "", hash: "" }, typeof to === "string" ? parsePath(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 createPath(_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 parsePath(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(_extends({}, 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 replace(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 : createPath(to); invariant(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, go(n) { return globalHistory.go(n); } }; return history; } function isIndexRoute(route) { return route.index === true; } function convertRoutesToDataRoutes(routes2, mapRouteProperties, parentPath, manifest) { if (parentPath === void 0) { parentPath = []; } if (manifest === void 0) { manifest = {}; } return routes2.map((route, index) => { let treePath = [...parentPath, index]; let id = typeof route.id === "string" ? route.id : treePath.join("-"); invariant(route.index !== true || !route.children, "Cannot specify children on an index route"); invariant(!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 = _extends({}, route, mapRouteProperties(route), { id }); manifest[id] = indexRoute; return indexRoute; } else { let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), { id, children: void 0 }); manifest[id] = pathOrLayoutRoute; if (route.children) { pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest); } return pathOrLayoutRoute; } }); } function matchRoutes(routes2, locationArg, basename) { if (basename === void 0) { basename = "/"; } let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg; let pathname = stripBasename(location.pathname || "/", basename); if (pathname == null) { return null; } let branches = flattenRoutes(routes2); rankRouteBranches(branches); let matches = null; for (let i = 0; matches == null && i < branches.length; ++i) { matches = matchRouteBranch( branches[i], // Incoming pathnames are generally encoded from either window.location // or from router.navigate, but we want to match against the unencoded // paths in the route definitions. Memory router locations won't be // encoded here but there also shouldn't be anything to decode so this // should be a safe operation. This avoids needing matchRoutes to be // history-aware. safelyDecodeURI(pathname) ); } 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(routes2, 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("/")) { invariant(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) { invariant( // 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 }); }; routes2.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((a, b2) => a.score !== b2.score ? b2.score - a.score : compareIndexes(a.routesMeta.map((meta) => meta.childrenIndex), b2.routesMeta.map((meta) => meta.childrenIndex))); } 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(a, b2) { let siblings = a.length === b2.length && a.slice(0, -1).every((n, i) => n === b2[i]); 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. a[a.length - 1] - b2[b2.length - 1] ) : ( // Otherwise, it doesn't really make sense to rank non-siblings by index, // so they sort equally. 0 ); } function matchRouteBranch(branch, pathname) { let { routesMeta } = branch; let matchedParams = {}; let matchedPathname = "/"; let matches = []; for (let i = 0; i < routesMeta.length; ++i) { let meta = routesMeta[i]; let end = i === routesMeta.length - 1; let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/"; let match = matchPath({ path: meta.relativePath, caseSensitive: meta.caseSensitive, end }, remainingPathname); if (!match) return null; Object.assign(matchedParams, match.params); let route = meta.route; 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 generatePath(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]; invariant(optional === "?" || param != null, 'Missing ":' + key + '" param'); return stringify(param); } return segment.replace(/\?$/g, ""); }).filter((segment) => !!segment); return prefix + segments.join("/"); } function matchPath(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] = safelyDecodeURIComponent(value || "", paramName); } 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 safelyDecodeURI(value) { try { return decodeURI(value); } 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 safelyDecodeURIComponent(value, paramName) { try { return decodeURIComponent(value); } catch (error) { warning(false, 'The value for the URL param "' + paramName + '" will not be decoded because' + (' the string "' + value + '" 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 resolvePath(to, fromPathname) { if (fromPathname === void 0) { fromPathname = "/"; } let { pathname: toPathname, search = "", hash = "" } = typeof to === "string" ? parsePath(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 === matches.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 = parsePath(toArg); } else { to = _extends({}, toArg); invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to)); invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to)); invariant(!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 = resolvePath(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" ? parsePath(to).pathname : to.pathname; } 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; } function isRouteErrorResponse(error) { return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error; } 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; invariant(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 future = _extends({ v7_fetcherPersist: false, v7_normalizeFormMethod: false, v7_partialHydration: false, v7_prependBasename: false, v7_relativeSplatPath: false }, init.future); let unlistenHistory = null; let subscribers = /* @__PURE__ */ new Set(); let savedScrollPositions = null; let getScrollRestorationKey = null; let getScrollPosition = null; let initialScrollRestored = init.hydrationData != null; let initialMatches = matchRoutes(dataRoutes, init.history.location, basename); let initialErrors = null; if (initialMatches == null) { let error = getInternalRouterError(404, { pathname: init.history.location.pathname }); let { matches, route } = getShortCircuitMatches(dataRoutes); initialMatches = matches; initialErrors = { [route.id]: error }; } let initialized; let hasLazyRoutes = initialMatches.some((m) => m.route.lazy); let hasLoaders = initialMatches.some((m) => m.route.loader); if (hasLazyRoutes) { initialized = false; } else if (!hasLoaders) { initialized = true; } else if (future.v7_partialHydration) { let loaderData = init.hydrationData ? init.hydrationData.loaderData : null; let errors = init.hydrationData ? init.hydrationData.errors : null; initialized = initialMatches.every((m) => m.route.loader && m.route.loader.hydrate !== true && (loaderData && loaderData[m.route.id] !== void 0 || errors && errors[m.route.id] !== void 0)); } 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 = []; 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 ignoreNextHistoryUpdate = false; function initialize() { unlistenHistory = init.history.listen((_ref) => { let { action: historyAction, location, delta } = _ref; if (ignoreNextHistoryUpdate) { ignoreNextHistoryUpdate = false; 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) { ignoreNextHistoryUpdate = true; init.history.go(delta * -1); updateBlocker(blockerKey, { state: "blocked", location, proceed() { updateBlocker(blockerKey, { state: "proceeding", proceed: void 0, reset: void 0, location }); 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 = _extends({}, 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(_extends({}, newState, { 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 = []; cancelledFetcherLoads = []; } 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 = _extends({}, 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 }); } 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 = matchRoutes(routesToUse, location, basename); let flushSync = (opts && opts.flushSync) === true; if (!matches) { let error = getInternalRouterError(404, { pathname: location.pathname }); let { matches: notFoundMatches, route } = getShortCircuitMatches(routesToUse); cancelActiveDeferreds(); 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 pendingActionData; let pendingError; if (opts && opts.pendingError) { pendingError = { [findNearestBoundary(matches).route.id]: opts.pendingError }; } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) { let actionOutput = await handleAction2(request, location, opts.submission, matches, { replace: opts.replace, flushSync }); if (actionOutput.shortCircuited) { return; } pendingActionData = actionOutput.pendingActionData; pendingError = actionOutput.pendingActionError; loadingNavigation = getLoadingNavigation(location, opts.submission); flushSync = false; request = new Request(request.url, { signal: request.signal }); } let { shortCircuited, loaderData, errors } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionData, pendingError); if (shortCircuited) { return; } pendingNavigationController = null; completeNavigation(location, _extends({ matches }, pendingActionData ? { actionData: pendingActionData } : {}, { loaderData, errors })); } async function handleAction2(request, location, submission, matches, opts) { if (opts === void 0) { opts = {}; } interruptActiveLoads(); let navigation = getSubmittingNavigation(location, submission); updateState({ navigation }, { flushSync: opts.flushSync === true }); 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 { result = await callLoaderOrAction("action", request, actionMatch, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath); if (request.signal.aborted) { return { shortCircuited: true }; } } if (isRedirectResult(result)) { let replace; if (opts && opts.replace != null) { replace = opts.replace; } else { replace = result.location === state.location.pathname + state.location.search; } await startRedirectNavigation(state, result, { submission, replace }); return { shortCircuited: true }; } if (isErrorResult(result)) { let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); if ((opts && opts.replace) !== true) { pendingAction = Action.Push; } return { // Send back an empty object we can use to clear out any prior actionData pendingActionData: {}, pendingActionError: { [boundaryMatch.route.id]: result.error } }; } if (isDeferredResult(result)) { throw getInternalRouterError(400, { type: "defer-action" }); } return { pendingActionData: { [actionMatch.route.id]: result.data } }; } async function handleLoaders(request, location, matches, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionData, pendingError) { let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission); let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation); let routesToUse = inFlightDataRoutes || dataRoutes; let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionData, pendingError); 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, _extends({ matches, loaderData: {}, // Commit pending error if we're short circuiting errors: pendingError || null }, pendingActionData ? { actionData: pendingActionData } : {}, updatedFetchers2 ? { fetchers: new Map(state.fetchers) } : {}), { flushSync }); return { shortCircuited: true }; } if (!isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration)) { 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); }); let actionData = pendingActionData || state.actionData; updateState(_extends({ navigation: loadingNavigation }, actionData ? Object.keys(actionData).length === 0 ? { actionData: null } : { actionData } : {}, revalidatingFetchers.length > 0 ? { fetchers: new Map(state.fetchers) } : {}), { 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((f2) => abortFetcher(f2.key)); if (pendingNavigationController) { pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations); } let { results, loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData(state.matches, 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 redirect4 = findRedirect(results); if (redirect4) { if (redirect4.idx >= matchesToLoad.length) { let fetcherKey = revalidatingFetchers[redirect4.idx - matchesToLoad.length].key; fetchRedirectIds.add(fetcherKey); } await startRedirectNavigation(state, redirect4.result, { replace }); return { shortCircuited: true }; } let { loaderData, errors } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds); activeDeferreds.forEach((deferredData, routeId) => { deferredData.subscribe((aborted) => { if (aborted || deferredData.done) { activeDeferreds.delete(routeId); } }); }); let updatedFetchers = markFetchRedirectsDone(); let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId); let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0; return _extends({ loaderData, errors }, shouldUpdateFetchers ? { fetchers: 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 = matchRoutes(routesToUse, normalizedPath, basename); 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, flushSync, submission); return; } fetchLoadMatches.set(key, { routeId, path }); handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission); } async function handleFetcherAction(key, routeId, path, match, requestMatches, flushSync, submission) { interruptActiveLoads(); fetchLoadMatches.delete(key); if (!match.route.action && !match.route.lazy) { let error = getInternalRouterError(405, { method: submission.formMethod, pathname: path, routeId }); setFetcherError(key, routeId, error, { flushSync }); 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); fetchControllers.set(key, abortController); let originatingLoadId = incrementingLoadId; let actionResult = await callLoaderOrAction("action", fetchRequest, match, requestMatches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath); 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(state, actionResult, { 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" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches; invariant(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, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, { [match.route.id]: actionResult.data }, void 0 // No need to send through errors since we short circuit above ); 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 { results, loaderResults, fetcherResults } = await callLoadersAndMaybeResolveData(state.matches, 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 redirect4 = findRedirect(results); if (redirect4) { if (redirect4.idx >= matchesToLoad.length) { let fetcherKey = revalidatingFetchers[redirect4.idx - matchesToLoad.length].key; fetchRedirectIds.add(fetcherKey); } return startRedirectNavigation(state, redirect4.result); } let { loaderData, errors } = processLoaderData(state, 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) { invariant(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, 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); fetchControllers.set(key, abortController); let originatingLoadId = incrementingLoadId; let result = await callLoaderOrAction("loader", fetchRequest, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath); 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(state, result); return; } } if (isErrorResult(result)) { setFetcherError(key, routeId, result.error); return; } invariant(!isDeferredResult(result), "Unhandled fetcher deferred data"); updateFetcherState(key, getDoneFetcher(result.data)); } async function startRedirectNavigation(state2, redirect4, _temp2) { let { submission, fetcherSubmission, replace } = _temp2 === void 0 ? {} : _temp2; if (redirect4.revalidate) { isRevalidationRequired = true; } let redirectLocation = createLocation(state2.location, redirect4.location, { _isRedirect: true }); invariant(redirectLocation, "Expected a location on the redirect navigation"); if (isBrowser) { let isDocumentReload = false; if (redirect4.reloadDocument) { isDocumentReload = true; } else if (ABSOLUTE_URL_REGEX.test(redirect4.location)) { const url = init.history.createURL(redirect4.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 (replace) { routerWindow.location.replace(redirect4.location); } else { routerWindow.location.assign(redirect4.location); } return; } } pendingNavigationController = null; let redirectHistoryAction = replace === true ? Action.Replace : Action.Push; let { formMethod, formAction, formEncType } = state2.navigation; if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) { submission = getSubmissionFromNavigation(state2.navigation); } let activeSubmission = submission || fetcherSubmission; if (redirectPreserveMethodStatusCodes.has(redirect4.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) { await startNavigation(redirectHistoryAction, redirectLocation, { submission: _extends({}, activeSubmission, { formAction: redirect4.location }), // Preserve this flag across redirects preventScrollReset: pendingPreventScrollReset }); } else { let overrideNavigation = getLoadingNavigation(redirectLocation, submission); await startNavigation(redirectHistoryAction, redirectLocation, { overrideNavigation, // Send fetcher submissions through for shouldRevalidate fetcherSubmission, // Preserve this flag across redirects preventScrollReset: pendingPreventScrollReset }); } } async function callLoadersAndMaybeResolveData(currentMatches, matches, matchesToLoad, fetchersToLoad, request) { let results = await Promise.all([...matchesToLoad.map((match) => callLoaderOrAction("loader", request, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath)), ...fetchersToLoad.map((f2) => { if (f2.matches && f2.match && f2.controller) { return callLoaderOrAction("loader", createClientSideRequest(init.history, f2.path, f2.controller.signal), f2.match, f2.matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath); } else { let error = { type: ResultType.error, error: getInternalRouterError(404, { pathname: f2.path }) }; return error; } })]); let loaderResults = results.slice(0, matchesToLoad.length); let fetcherResults = results.slice(matchesToLoad.length); await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, loaderResults.map(() => request.signal), false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map((f2) => f2.match), fetcherResults, fetchersToLoad.map((f2) => f2.controller ? f2.controller.signal : null), true)]); return { results, loaderResults, fetcherResults }; } function interruptActiveLoads() { isRevalidationRequired = true; cancelledDeferredRoutes.push(...cancelActiveDeferreds()); fetchLoadMatches.forEach((_, key) => { if (fetchControllers.has(key)) { cancelledFetcherLoads.push(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); 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); invariant(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); invariant(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); invariant(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; invariant(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(_ref2) { let { currentLocation, nextLocation, historyAction } = _ref2; 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 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 _internalSetRoutes(newRoutes) { manifest = {}; inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, void 0, manifest); } 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, _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; } function createStaticHandler(routes2, opts) { invariant(routes2.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 = _extends({ v7_relativeSplatPath: false, v7_throwAbortReason: false }, opts ? opts.future : null); let dataRoutes = convertRoutesToDataRoutes(routes2, mapRouteProperties, void 0, manifest); async function query(request, _temp3) { let { requestContext } = _temp3 === void 0 ? {} : _temp3; let url = new URL(request.url); let method = request.method; let location = createLocation("", createPath(url), null, "default"); let matches = matchRoutes(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); if (isResponse(result)) { return result; } return _extends({ location, basename }, result); } async function queryRoute(request, _temp4) { let { routeId, requestContext } = _temp4 === void 0 ? {} : _temp4; let url = new URL(request.url); let method = request.method; let location = createLocation("", createPath(url), null, "default"); let matches = matchRoutes(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, 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 data = Object.values(result.loaderData)[0]; if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) { data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id]; } return data; } return void 0; } async function queryImpl(request, location, matches, requestContext, routeMatch) { invariant(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, routeMatch != null); return result2; } let result = await loadRouteData(request, matches, requestContext, routeMatch); return isResponse(result) ? result : _extends({}, result, { actionData: null, actionHeaders: {} }); } catch (e) { if (isQueryRouteResponse(e)) { if (e.type === ResultType.error) { throw e.response; } return e.response; } if (isRedirectResponse(e)) { return e; } throw e; } } async function submit(request, matches, actionMatch, requestContext, 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 { result = await callLoaderOrAction("action", request, actionMatch, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath, { isStaticRequest: true, isRouteRequest, requestContext }); if (request.signal.aborted) { throwStaticHandlerAbortedError(request, isRouteRequest, future); } } if (isRedirectResult(result)) { throw new Response(null, { status: result.status, headers: { Location: result.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 }; } if (isErrorResult(result)) { let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); let context2 = await loadRouteData(request, matches, requestContext, void 0, { [boundaryMatch.route.id]: result.error }); return _extends({}, context2, { statusCode: isRouteErrorResponse(result.error) ? result.error.status : 500, actionData: null, actionHeaders: _extends({}, result.headers ? { [actionMatch.route.id]: result.headers } : {}) }); } let loaderRequest = new Request(request.url, { headers: request.headers, redirect: request.redirect, signal: request.signal }); let context = await loadRouteData(loaderRequest, matches, requestContext); return _extends({}, context, result.statusCode ? { statusCode: result.statusCode } : {}, { actionData: { [actionMatch.route.id]: result.data }, actionHeaders: _extends({}, result.headers ? { [actionMatch.route.id]: result.headers } : {}) }); } async function loadRouteData(request, matches, requestContext, routeMatch, pendingActionError) { 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] : getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]); 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: pendingActionError || null, statusCode: 200, loaderHeaders: {}, activeDeferreds: null }; } let results = await Promise.all([...matchesToLoad.map((match) => callLoaderOrAction("loader", request, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath, { isStaticRequest: true, isRouteRequest, requestContext }))]); if (request.signal.aborted) { throwStaticHandlerAbortedError(request, isRouteRequest, future); } let activeDeferreds = /* @__PURE__ */ new Map(); let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError, activeDeferreds); 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 _extends({}, context, { matches, activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null }); } return { dataRoutes, query, queryRoute }; } function getStaticContextFromError(routes2, context, error) { let newContext = _extends({}, context, { statusCode: isRouteErrorResponse(error) ? error.status : 500, errors: { [context._deepestRenderedBoundaryId || routes2[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 createPath(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, _ref3) => { let [name, value] = _ref3; 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 json5 = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body; return { path, submission: { formMethod, formAction, formEncType: opts.formEncType, formData: void 0, json: json5, text: void 0 } }; } catch (e) { return getInvalidBodyError(); } } } invariant(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 (e) { 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 = parsePath(path); if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) { searchParams.append("index", ""); } parsedPath.search = "?" + searchParams; return { path: createPath(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, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionData, pendingError) { let actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : void 0; let currentUrl = history.createURL(state.location); let nextUrl = history.createURL(location); let boundaryId = pendingError ? Object.keys(pendingError)[0] : void 0; let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId); let navigationMatches = boundaryMatches.filter((match, index) => { let { route } = match; if (route.lazy) { return true; } if (route.loader == null) { return false; } if (isInitialLoad) { if (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, _extends({ currentUrl, currentParams: currentRouteMatch.params, nextUrl, nextParams: nextRouteMatch.params }, submission, { actionResult, defaultShouldRevalidate: ( // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate isRevalidationRequired || // Clicked the same link, resubmitted a GET form currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search || // Search params affect all loaders currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch) ) })); }); let revalidatingFetchers = []; fetchLoadMatches.forEach((f2, key) => { if (isInitialLoad || !matches.some((m) => m.route.id === f2.routeId) || deletedFetchers.has(key)) { return; } let fetcherMatches = matchRoutes(routesToUse, f2.path, basename); if (!fetcherMatches) { revalidatingFetchers.push({ key, routeId: f2.routeId, path: f2.path, matches: null, match: null, controller: null }); return; } let fetcher = state.fetchers.get(key); let fetcherMatch = getTargetMatch(fetcherMatches, f2.path); let shouldRevalidate = false; if (fetchRedirectIds.has(key)) { shouldRevalidate = false; } else if (cancelledFetcherLoads.includes(key)) { shouldRevalidate = true; } else if (fetcher && fetcher.state !== "idle" && fetcher.data === void 0) { shouldRevalidate = isRevalidationRequired; } else { shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({ currentUrl, currentParams: state.matches[state.matches.length - 1].params, nextUrl, nextParams: matches[matches.length - 1].params }, submission, { actionResult, defaultShouldRevalidate: isRevalidationRequired })); } if (shouldRevalidate) { revalidatingFetchers.push({ key, routeId: f2.routeId, path: f2.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 loadLazyRouteModule(route, mapRouteProperties, manifest) { if (!route.lazy) { return; } let lazyRoute = await route.lazy(); if (!route.lazy) { return; } let routeToUpdate = manifest[route.id]; invariant(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, _extends({}, mapRouteProperties(routeToUpdate), { lazy: void 0 })); } async function callLoaderOrAction(type, request, match, matches, manifest, mapRouteProperties, basename, v7_relativeSplatPath, opts) { if (opts === void 0) { opts = {}; } let resultType; let result; let onReject; let runHandler = (handler2) => { let reject; let abortPromise = new Promise((_, r) => reject = r); onReject = () => reject(); request.signal.addEventListener("abort", onReject); return Promise.race([handler2({ request, params: match.params, context: opts.requestContext }), abortPromise]); }; try { let handler2 = match.route[type]; if (match.route.lazy) { if (handler2) { let handlerError; let values = 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(handler2).catch((e) => { handlerError = e; }), loadLazyRouteModule(match.route, mapRouteProperties, manifest) ]); if (handlerError) { throw handlerError; } result = values[0]; } else { await loadLazyRouteModule(match.route, mapRouteProperties, manifest); handler2 = match.route[type]; if (handler2) { result = await runHandler(handler2); } 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, data: void 0 }; } } } else if (!handler2) { let url = new URL(request.url); let pathname = url.pathname + url.search; throw getInternalRouterError(404, { pathname }); } else { result = await runHandler(handler2); } invariant(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 (e) { resultType = ResultType.error; result = e; } finally { if (onReject) { request.signal.removeEventListener("abort", onReject); } } if (isResponse(result)) { let status = result.status; if (redirectStatusCodes.has(status)) { let location = result.headers.get("Location"); invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header"); if (!ABSOLUTE_URL_REGEX.test(location)) { location = normalizeTo(new URL(request.url), matches.slice(0, matches.indexOf(match) + 1), basename, true, location, v7_relativeSplatPath); } else if (!opts.isStaticRequest) { let currentUrl = new URL(request.url); let url = location.startsWith("//") ? new URL(currentUrl.protocol + location) : new URL(location); let isSameBasename = stripBasename(url.pathname, basename) != null; if (url.origin === currentUrl.origin && isSameBasename) { location = url.pathname + url.search + url.hash; } } if (opts.isStaticRequest) { result.headers.set("Location", location); throw result; } return { type: ResultType.redirect, status, location, revalidate: result.headers.get("X-Remix-Revalidate") !== null, reloadDocument: result.headers.get("X-Remix-Reload-Document") !== null }; } if (opts.isRouteRequest) { let queryRouteResponse = { type: resultType === ResultType.error ? ResultType.error : ResultType.data, response: result }; throw queryRouteResponse; } let data; try { let contentType = result.headers.get("Content-Type"); if (contentType && /\bapplication\/json\b/.test(contentType)) { if (result.body == null) { data = null; } else { data = await result.json(); } } else { data = await result.text(); } } catch (e) { return { type: ResultType.error, error: e }; } if (resultType === ResultType.error) { return { type: resultType, error: new ErrorResponseImpl(status, result.statusText, data), headers: result.headers }; } return { type: ResultType.data, data, statusCode: result.status, headers: result.headers }; } if (resultType === ResultType.error) { return { type: resultType, error: result }; } if (isDeferredData(result)) { var _result$init, _result$init2; return { type: ResultType.deferred, deferredData: result, statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status, headers: ((_result$init2 = result.init) == null ? void 0 : _result$init2.headers) && new Headers(result.init.headers) }; } return { type: ResultType.data, data: result }; } 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, matchesToLoad, results, pendingError, activeDeferreds) { let loaderData = {}; let errors = null; let statusCode; let foundError = false; let loaderHeaders = {}; results.forEach((result, index) => { let id = matchesToLoad[index].route.id; invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData"); if (isErrorResult(result)) { let boundaryMatch = findNearestBoundary(matches, id); let error = result.error; if (pendingError) { error = Object.values(pendingError)[0]; pendingError = void 0; } errors = errors || {}; if (errors[boundaryMatch.route.id] == null) { errors[boundaryMatch.route.id] = error; } loaderData[id] = void 0; if (!foundError) { foundError = true; statusCode = isRouteErrorResponse(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; } else { loaderData[id] = result.data; } if (result.statusCode != null && result.statusCode !== 200 && !foundError) { statusCode = result.statusCode; } if (result.headers) { loaderHeaders[id] = result.headers; } } }); if (pendingError) { errors = pendingError; loaderData[Object.keys(pendingError)[0]] = void 0; } return { loaderData, errors, statusCode: statusCode || 200, loaderHeaders }; } function processLoaderData(state, matches, matchesToLoad, results, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds) { let { loaderData, errors } = processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds); for (let index = 0; index < revalidatingFetchers.length; index++) { let { key, match, controller } = revalidatingFetchers[index]; invariant(fetcherResults !== void 0 && fetcherResults[index] !== void 0, "Did not find corresponding fetcher result"); let result = fetcherResults[index]; if (controller && controller.signal.aborted) { continue; } else if (isErrorResult(result)) { let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id); if (!(errors && errors[boundaryMatch.route.id])) { errors = _extends({}, errors, { [boundaryMatch.route.id]: result.error }); } state.fetchers.delete(key); } else if (isRedirectResult(result)) { invariant(false, "Unhandled fetcher revalidation redirect"); } else if (isDeferredResult(result)) { invariant(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 = _extends({}, 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 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(routes2) { let route = routes2.length === 1 ? routes2[0] : routes2.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 } = _temp5 === void 0 ? {} : _temp5; let statusText = "Unknown Server Error"; let errorMessage = "Unknown @remix-run/router error"; if (status === 400) { statusText = "Bad Request"; 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) { for (let i = results.length - 1; i >= 0; i--) { let result = results[i]; if (isRedirectResult(result)) { return { result, idx: i }; } } } function stripHashFromPath(path) { let parsedPath = typeof path === "string" ? parsePath(path) : path; return createPath(_extends({}, parsedPath, { hash: "" })); } function isHashChangeOnly(a, b2) { if (a.pathname !== b2.pathname || a.search !== b2.search) { return false; } if (a.hash === "") { return b2.hash !== ""; } else if (a.hash === b2.hash) { return true; } else if (b2.hash !== "") { return true; } return false; } 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 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 isQueryRouteResponse(obj) { return obj && isResponse(obj.response) && (obj.type === ResultType.data || obj.type === ResultType.error); } function isValidMethod(method) { return validRequestMethods.has(method.toLowerCase()); } function isMutationMethod(method) { return validMutationMethods.has(method.toLowerCase()); } async function resolveDeferredResults(currentMatches, matchesToLoad, results, signals, isFetcher, currentLoaderData) { for (let index = 0; index < results.length; index++) { let result = results[index]; let match = matchesToLoad[index]; 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) && (isFetcher || isRevalidatingLoader)) { let signal = signals[index]; invariant(signal, "Expected an AbortSignal for revalidating fetcher deferred result"); await resolveDeferredData(result, signal, isFetcher).then((result2) => { if (result2) { results[index] = result2 || results[index]; } }); } } } 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 (e) { return { type: ResultType.error, error: e }; } } 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" ? parsePath(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: json5 } = 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 (json5 !== void 0) { return { formMethod, formAction, formEncType, formData: void 0, json: json5, 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, data) { 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 }; 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 }; 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(data) { let fetcher = { state: "idle", formMethod: void 0, formAction: void 0, formEncType: void 0, formData: void 0, json: void 0, text: void 0, data }; return fetcher; } function restoreAppliedTransitions(_window, transitions) { try { let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY); if (sessionPositions) { let json5 = JSON.parse(sessionPositions); for (let [k2, v] of Object.entries(json5 || {})) { if (v && Array.isArray(v)) { transitions.set(k2, new Set(v || [])); } } } } catch (e) { } } function persistAppliedTransitions(_window, transitions) { if (transitions.size > 0) { let json5 = {}; for (let [k2, v] of transitions) { json5[k2] = [...v]; } try { _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json5)); } catch (error) { warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ")."); } } } var Action, PopStateEventType, ResultType, immutableRouteKeys, paramRe, dynamicSegmentValue, indexRouteValue, emptySegmentValue, staticSegmentValue, splatPenalty, isSplat, joinPaths, normalizePathname, normalizeSearch, normalizeHash, json, AbortedDeferredError, DeferredData, defer, redirect, redirectDocument, ErrorResponseImpl, validMutationMethodsArr, validMutationMethods, validRequestMethodsArr, validRequestMethods, redirectStatusCodes, redirectPreserveMethodStatusCodes, IDLE_NAVIGATION, IDLE_FETCHER, IDLE_BLOCKER, ABSOLUTE_URL_REGEX, defaultMapRouteProperties, TRANSITIONS_STORAGE_KEY, UNSAFE_DEFERRED_SYMBOL; var init_router = __esm({ "node_modules/@remix-run/router/dist/router.js"() { (function(Action2) { Action2["Pop"] = "POP"; Action2["Push"] = "PUSH"; Action2["Replace"] = "REPLACE"; })(Action || (Action = {})); PopStateEventType = "popstate"; (function(ResultType2) { ResultType2["data"] = "data"; ResultType2["deferred"] = "deferred"; ResultType2["redirect"] = "redirect"; ResultType2["error"] = "error"; })(ResultType || (ResultType = {})); immutableRouteKeys = /* @__PURE__ */ new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]); paramRe = /^:[\w-]+$/; dynamicSegmentValue = 3; indexRouteValue = 2; emptySegmentValue = 1; staticSegmentValue = 10; splatPenalty = -2; isSplat = (s) => s === "*"; joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/"); normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/"); normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search; normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash; json = function json2(data, 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(data), _extends({}, responseInit, { headers })); }; AbortedDeferredError = class extends Error { }; DeferredData = class { constructor(data, responseInit) { this.pendingKeysSet = /* @__PURE__ */ new Set(); this.subscribers = /* @__PURE__ */ new Set(); this.deferredKeys = []; invariant(data && typeof data === "object" && !Array.isArray(data), "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(data).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((data) => this.onSettle(promise, key, void 0, data), (error) => this.onSettle(promise, key, error)); promise.catch(() => { }); Object.defineProperty(promise, "_tracked", { get: () => true }); return promise; } onSettle(promise, key, error, data) { 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 && data === 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 (data === void 0) { Object.defineProperty(promise, "_error", { get: () => error }); this.emit(false, key); return Promise.reject(error); } Object.defineProperty(promise, "_data", { get: () => data }); this.emit(false, key); return data; } 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() { invariant(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); } }; defer = function defer2(data, init) { if (init === void 0) { init = {}; } let responseInit = typeof init === "number" ? { status: init } : init; return new DeferredData(data, responseInit); }; redirect = function redirect2(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, _extends({}, responseInit, { headers })); }; redirectDocument = (url, init) => { let response = redirect(url, init); response.headers.set("X-Remix-Reload-Document", "true"); return response; }; ErrorResponseImpl = class { constructor(status, statusText, data, internal) { if (internal === void 0) { internal = false; } this.status = status; this.statusText = statusText || ""; this.internal = internal; if (data instanceof Error) { this.data = data.toString(); this.error = data; } else { this.data = data; } } }; validMutationMethodsArr = ["post", "put", "patch", "delete"]; validMutationMethods = new Set(validMutationMethodsArr); validRequestMethodsArr = ["get", ...validMutationMethodsArr]; validRequestMethods = new Set(validRequestMethodsArr); redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]); redirectPreserveMethodStatusCodes = /* @__PURE__ */ new Set([307, 308]); 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 }; 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 }; IDLE_BLOCKER = { state: "unblocked", proceed: void 0, reset: void 0, location: void 0 }; ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; defaultMapRouteProperties = (route) => ({ hasErrorBoundary: Boolean(route.hasErrorBoundary) }); TRANSITIONS_STORAGE_KEY = "remix-router-transitions"; UNSAFE_DEFERRED_SYMBOL = Symbol("deferred"); } }); // node_modules/@remix-run/server-runtime/dist/mode.js var require_mode = __commonJS({ "node_modules/@remix-run/server-runtime/dist/mode.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ServerMode2 = /* @__PURE__ */ function(ServerMode3) { ServerMode3["Development"] = "development"; ServerMode3["Production"] = "production"; ServerMode3["Test"] = "test"; return ServerMode3; }({}); function isServerMode(value) { return value === ServerMode2.Development || value === ServerMode2.Production || value === ServerMode2.Test; } exports.ServerMode = ServerMode2; exports.isServerMode = isServerMode; } }); // node_modules/@remix-run/server-runtime/dist/errors.js var require_errors = __commonJS({ "node_modules/@remix-run/server-runtime/dist/errors.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var router = (init_router(), __toCommonJS(router_exports)); 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/@remix-run/server-runtime/dist/responses.js var require_responses = __commonJS({ "node_modules/@remix-run/server-runtime/dist/responses.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var router = (init_router(), __toCommonJS(router_exports)); var errors = require_errors(); var json5 = (data, init = {}) => { return router.json(data, init); }; var defer3 = (data, init = {}) => { return router.defer(data, init); }; var redirect4 = (url, init = 302) => { return router.redirect(url, init); }; var redirectDocument2 = (url, init = 302) => { return router.redirectDocument(url, init); }; function isDeferredData3(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 isResponse3(value) { return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined"; } var redirectStatusCodes2 = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]); function isRedirectStatusCode2(statusCode) { return redirectStatusCodes2.has(statusCode); } function isRedirectResponse3(response) { return isRedirectStatusCode2(response.status); } function isTrackedPromise2(value) { return value != null && typeof value.then === "function" && value._tracked === true; } var DEFERRED_VALUE_PLACEHOLDER_PREFIX = "__deferred_promise:"; function createDeferredReadableStream2(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 (isTrackedPromise2(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 = createDeferredReadableStream2; exports.defer = defer3; exports.isDeferredData = isDeferredData3; exports.isRedirectResponse = isRedirectResponse3; exports.isRedirectStatusCode = isRedirectStatusCode2; exports.isResponse = isResponse3; exports.json = json5; exports.redirect = redirect4; exports.redirectDocument = redirectDocument2; } }); // app/entry.worker.ts var entry_worker_exports = {}; __export(entry_worker_exports, { defaultFetchHandler: () => defaultFetchHandler }); // node_modules/cachified/dist/index.mjs var k = Symbol(); var w = Symbol(); var f = Symbol(); // node_modules/@remix-pwa/cache/dist/src/cache.js var B = __toESM(require_buffer(), 1); // node_modules/@remix-pwa/cache/dist/src/utils.js function mergeHeaders(...headers) { const merged = new Headers(); for (const header of headers) { if (!header) continue; for (const [key, value] of new Headers(header).entries()) { merged.set(key, value); } } return merged; } function omit(key, obj) { const { [key]: omitted, ...rest } = obj; return rest; } // node_modules/@remix-pwa/cache/dist/src/cache.js var Strategy; (function(Strategy2) { Strategy2["CacheFirst"] = "cache-first"; Strategy2["NetworkFirst"] = "network-first"; Strategy2["CacheOnly"] = "cache-only"; Strategy2["NetworkOnly"] = "network-only"; Strategy2["StaleWhileRevalidate"] = "stale-while-revalidate"; })(Strategy || (Strategy = {})); var RemixCache = class { /** * Create a new `RemixCache` instance. Don't invoke this directly! Use `RemixCacheStorage.open()` instead. * @constructor * @param {object} options - Options for the RemixCache instance. */ constructor(options) { this._ttl = Infinity; this._strategy = Strategy.NetworkFirst; this._maxItems = 100; this.set = false; this.name = options.name; this._maxItems = options.maxItems || 100; this._strategy = options.strategy || Strategy.NetworkFirst; this._ttl = options.ttl || Infinity; if (this._strategy === Strategy.NetworkOnly) { this._ttl = -1; } if (options.maxItems || options.ttl || options.strategy) { this.set = true; } else { this.set = false; } } async _openCache() { return await caches.open(`rp-${this.name}`); } async _getOrDeleteIfExpired(key, metadata) { if (metadata.expiresAt === "Infinity") { return false; } if (Number(metadata.expiresAt) <= Date.now()) { return await this.delete(key); } return false; } async _lruCleanup() { const isOverflowing = await this.length() >= this._maxItems; if (isOverflowing) { const cache = await this._openCache(); const keys = await cache.keys(); const values = await Promise.all(keys.map((key) => cache.match(key))); const keyVal = keys.map((key, i) => ({ key, val: values[i] })); const comparableArrayPromise = keyVal.map(async (val) => { const { metadata } = await val.val.clone().json(); return { metadata, url: val.key.url }; }); const comparableArray = await Promise.all(comparableArrayPromise); const sortedArr = comparableArray.sort((a, b2) => { return Number(a.metadata.accessedAt) - Number(b2.metadata.accessedAt); }); const toBeDeletdItems = sortedArr.slice(0, sortedArr.length - this._maxItems + 1); for (const deleted of toBeDeletdItems) { await this.delete(deleted.url); } } } async _getResponseValue(request, response) { const { metadata, value } = await response.clone().json(); const deleted = await this._getOrDeleteIfExpired(request, metadata); const headers = new Headers(response.clone().headers); if (!this.set) { this.set = true; this._ttl = metadata.cacheTtl; this._maxItems = metadata.cacheMaxItems; this._strategy = metadata.cacheStrategy; } const newHeader = new Headers(headers); newHeader.set("X-Remix-PWA-TTL", metadata.expiresAt.toString()); newHeader.set("X-Remix-PWA-AccessTime", Date.now().toString()); newHeader.set("Content-Type", headers.get("X-Remix-PWA-Original-Content-Type") || "application/json"); const contentType = headers.get("X-Remix-PWA-Original-Content-Type") ?? ""; newHeader.delete("X-Remix-PWA-Original-Content-Type"); const responseOptions = { status: response.status, statusText: response.statusText, headers: newHeader, body: "null" }; if (contentType.includes("application/json")) { responseOptions.body = JSON.stringify(value); } else if (contentType.includes("text")) { responseOptions.body = value; } else { const buffer = B.Buffer.from(value, "base64"); responseOptions.body = new Uint8Array(buffer); } if (!deleted) { const res = new Response(responseOptions.body, omit("body", responseOptions)); await this.put(request, res.clone(), void 0); return res; } return void 0; } /** * Delete an entry from the cache. * Takes in the same parameters as `Cache.delete`. * @param {RequestInfo | URL} request - The request to delete. * @param {CacheQueryOptions} [options] - Options for the delete operation. * @returns {Promise} Returns `true` if an entry was deleted, otherwise `false`. * * @example * ```js * const cache = await initCache({ name: 'my-cache' }); * * await cache.put('/hello-world', new Response('Hello World!')); * await cache.delete('/hello-world'); * ``` * * @see https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete */ async delete(request, options) { return this._openCache().then((cache) => cache.delete(request, options)); } /** * Returns a Promise that resolves to the length of the Cache object. * * @returns {Promise} The number of entries in the cache. */ async length() { const keys = await this.keys(); return keys.length; } /** * Returns a `Promise` that resolves to an array of Cache keys. * * @returns {Promise} An array of Cache keys. */ async keys() { const cache = await this._openCache(); return await cache.keys(); } /** * Return a `Promise` that resolves to an entry in the cache object. Accepts the * same parameters as `Cache.match`. * * @param {RequestInfo | URL} request - The request to match. * @param {CacheQueryOptions} [options] - Options for the match operation. * * @returns {Promise} A `Promise` that resolves to the response, or `undefined` if not found. */ async match(request, options) { const cache = await this._openCache(); if (request instanceof URL || typeof request === "string") { request = new Request(request); } const response = await cache.match(request.clone(), options); if (!response) { return void 0; } return await this._getResponseValue(request, response.clone()); } /** * Add an entry to the cache. * Takes in the same parameters as `Cache.put`. * * @param {RequestInfo | URL} request - The request to add. * @param {Response} response - The response to add. * @param {number | undefined} ttl - The time-to-live of the cache entry in ms. Defaults to cache ttl. * @returns {Promise} A `Promise` that resolves when the entry is added to the cache. * * @example * ```js * const cache = await initCache({ name: 'my-cache' }); * * await cache.put('/hello-world', new Response('Hello World!')); * ``` * * @see https://developer.mozilla.org/en-US/docs/Web/API/Cache/put */ async put(request, response, ttl = void 0) { const cache = await this._openCache(); if (request instanceof URL || typeof request === "string") { request = new Request(request); } if (this._ttl <= 0 || ttl && ttl <= 0) return; if (response === null || response.status === 204 || response.statusText.toLowerCase() === "no content") { await this.delete(request); return; } const contentType = response.headers.get("Content-Type"); let data; if (contentType && contentType.includes("application/json")) { data = await response.clone().json(); } else if (contentType && contentType.includes("text")) { data = await response.clone().text(); } else { const buffer = await response.clone().arrayBuffer(); data = B.Buffer.from(buffer).toString("base64"); } if (!this.set) { this.set = true; const keys = await cache.keys(); const firstVal = await cache.match(keys[0]); if (firstVal) { const { metadata } = await firstVal.clone().json(); this._ttl = metadata.cacheTtl; this._maxItems = metadata.cacheMaxItems; this._strategy = metadata.cacheStrategy; } else { this._ttl = Infinity; this._maxItems = 100; this._strategy = Strategy.NetworkFirst; } } const resHeaders = response.headers; const expiresAt = resHeaders.get("X-Remix-PWA-TTL") || Date.now() + (ttl ?? this._ttl); const accessedAt = resHeaders.get("X-Remix-PWA-AccessTime") || Date.now().toString(); const newHeaders = new Headers(); newHeaders.set("Content-Type", "application/json"); newHeaders.set("X-Remix-PWA-AccessTime", accessedAt); newHeaders.set("X-Remix-PWA-Original-Content-Type", contentType || "text/plain"); newHeaders.set("X-Remix-PWA-TTL", expiresAt.toString()); const toBeCachedRes = new Response(JSON.stringify({ metadata: { accessedAt, // JSON can't store `Infinity`, so we store it as a string expiresAt: expiresAt.toString(), cacheTtl: this._ttl.toString(), cacheMaxItems: this._maxItems, cacheStrategy: this._strategy }, value: data }), { status: response.status, statusText: response.statusText, headers: mergeHeaders(resHeaders, newHeaders) }); Object.defineProperty(toBeCachedRes, "url", { value: response.url }); Object.defineProperty(toBeCachedRes, "type", { value: response.type }); Object.defineProperty(toBeCachedRes, "ok", { value: response.ok }); Object.defineProperty(toBeCachedRes, "redirected", { value: response.redirected }); try { await this._lruCleanup(); return await cache.put(request, toBeCachedRes.clone()); } catch (error) { if (true) console.error("Failed to put to cache:", error); } } async add(request) { return ( /* await - should this be awaited? */ fetch(request).then((res) => { if (!res.ok) { throw new Error("Failed to fetch"); } return this.put(request, res.clone()); }) ); } get ttl() { return this._ttl; } get strategy() { return this._strategy; } }; // node_modules/@remix-pwa/cache/dist/src/storage.js var RemixCacheStorage = class { // eslint-disable-next-line no-useless-constructor constructor() { } /** * Initialize the Remix PWA Cache Storage. This will create a special cache for each * existing cache in the browser or create a new map if none exist. * * Use in your service worker installation script. Make sure to call this before * initializing any `RemixCache` instance. * * @example * ```js * import { RemixCacheStorage } from '@remix-run/cache'; * * self.addEventListener('install', (event) => { * event.waitUntil(Promise.all[ * RemixCacheStorage.init(), * // other stuff * ]); * }); * ``` */ // static async init() { // if (typeof caches === 'undefined') { // throw new Error('Cache API is not available in this environment.'); // } // if (this._instances.size > 0) { // return; // } // const cachesNames = await caches.keys(); // for (const name of cachesNames) { // if (name.startsWith('rp-')) { // this._instances.set(name, new RemixCache({ name })); // } // } // } /** * Create a custom cache that you can use across your application. * Use this instead of initialising `RemixCache` directly. */ static createCache(opts) { const { name } = opts; if (this._instances.has(name)) { return this._instances.get(name); } const newCache = new RemixCache(opts); this._instances.set(`${name}`, newCache); caches.open(`rp-${name}`); return newCache; } /** * Check wether a cache with the given name exists. * * @param name */ static has(name) { return this._instances.has(name); } static async _get(name) { const cache = this._instances.get(name); if (!cache && await caches.has(`rp-${name}`)) { this._instances.set(name, new RemixCache({ name })); await this._instances.get(name)?.keys().then((keys) => { if (keys.length > 0) { caches.match(keys[0]); } }); } return this._instances.get(name); } /** * Get a cache by name. Returns `undefined` if no cache with the given name exists. * Use `has` to check if a cache exists. Or `open` to create one automatically if non exists. * * @param name * @returns {RemixCache | undefined} * * @example * ```js * import { Storage } from '@remix-run/cache'; * * const cache = Storage.get('my-cache'); * ``` */ static async get(name) { return await this._get(name); } /** * Get a cache by name. If no cache with the given name exists, create one. * * @param name Name of the cache - **must be unique** * @param opts Options to pass to the `RemixCache` constructor if the cache is getting created * @returns {RemixCache} * * @example * ```js * import { Storage } from '@remix-run/cache'; * * const cache = Storage.open('my-cache'); * ``` */ static open(name, opts) { const cache = this._instances.get(name); if (!cache) { return this.createCache({ name, ...opts }); } return cache; } /** * Delete a cache by name. * * @param name */ static delete(name) { const cache = this._instances.get(name); if (cache) { caches.delete(`rp-${name}`); this._instances.delete(name); } } /** * Delete all caches. */ static clear() { caches.keys().then((keys) => keys.forEach((key) => key.startsWith("rp-") ? caches.delete(key) : null)); this._instances = /* @__PURE__ */ new Map(); } /** * Get all caches. **Don't use this except you know what you are doing!** * * Which, frankly speaking, you probably don't. So shoo away! */ static get instances() { return this._instances; } /** * Get the number of caches. * * Return the length of the `RemixCacheStorage` store. */ static get _length() { return this._instances.size; } /** * Check if a request is stored as the key of a response in all caches. * * Experimental. Use at your own risk! * * @param {RequestInfo | URL} request The request to check. * @param {CacheQueryOptions} [options] Options to pass to the `Cache.match` method. * @returns {Promise} A promise that resolves to the response if found, otherwise `undefined`. */ static _match(request, options) { return caches.match(request, options); } }; RemixCacheStorage._instances = /* @__PURE__ */ new Map(); var Storage = RemixCacheStorage; // node_modules/@remix-pwa/strategy/dist/src/utils.js var isHttpRequest = (request) => { if (request instanceof Request) { return request.url.startsWith("http"); } return request.toString().startsWith("http"); }; // node_modules/@remix-pwa/strategy/dist/src/cacheFirst.js var cacheFirst = ({ cache: cacheName, cacheOptions, cacheQueryOptions, fetchDidFail = void 0 }) => { return async (request) => { if (!isHttpRequest(request)) { return new Response("Not a HTTP request", { status: 403 }); } let remixCache; if (typeof cacheName === "string") { remixCache = Storage.open(cacheName, cacheOptions); } else { remixCache = cacheName; } const response = await remixCache.match(request, cacheQueryOptions); if (!response) { try { const networkResponse = await fetch(request); remixCache.put(request, networkResponse.clone()); return networkResponse; } catch (err) { if (fetchDidFail) { await Promise.all(fetchDidFail.map((cb) => cb())); } throw err; } } return response; }; }; // node_modules/@remix-pwa/strategy/dist/src/networkFirst.js var networkFirst = ({ cache: cacheName, cacheOptions, cacheQueryOptions, fetchDidFail = void 0, fetchDidSucceed = void 0, networkTimeoutSeconds = 10 }) => { return async (request) => { if (!isHttpRequest(request)) { return new Response("Not a HTTP request", { status: 403 }); } let remixCache; if (typeof cacheName === "string") { remixCache = Storage.open(cacheName, cacheOptions); } else { remixCache = cacheName; } try { const timeoutPromise = networkTimeoutSeconds !== Infinity ? new Promise((_resolve, reject) => { setTimeout(() => { reject(new Error(`Network timed out after ${networkTimeoutSeconds} seconds`)); }, networkTimeoutSeconds * 1e3); }) : null; const response = timeoutPromise ? await Promise.race([fetch(request), timeoutPromise]) : await fetch(request); if (response) { if (fetchDidSucceed) { await Promise.all(fetchDidSucceed.map((cb) => cb())); } await remixCache.put(request, response.clone()); return response.clone(); } } catch (error) { if (fetchDidFail) { await Promise.all(fetchDidFail.map((cb) => cb())); } const cachedResponse = await remixCache.match(request, cacheQueryOptions); if (cachedResponse) { return cachedResponse.clone(); } return new Response(JSON.stringify({ message: "Network Error" }), { status: 500 }); } throw new Error("Failed to fetch. Network timed out."); }; }; // node_modules/@remix-pwa/sw/dist/src/private/logger.js var methodToColorMap = { debug: `#7f8c8d`, log: `#2ecc71`, info: `#3498db`, warn: `#f39c12`, error: `#c0392b`, groupCollapsed: `#3498db`, groupEnd: null // No colored prefix on groupEnd }; var logger = false ? (() => { const api = {}; const loggerMethods = Object.keys(methodToColorMap); for (const key of loggerMethods) { const method = key; api[method] = () => { }; } return api; })() : (() => { let inGroup = false; const print = function(method, args) { if (self.__DISABLE_PWA_DEV_LOGS) { return; } if (method === "debug" && self.__DISABLE_PWA_DEBUG_LOGS) { return; } if (method === "info" && self.__DISABLE_PWA_INFO_LOGS) { return; } if (method === "warn" && self.__DISABLE_PWA_WARN_LOGS) { return; } if (method === "error" && self.__DISABLE_PWA_ERROR_LOGS) { return; } if (method === "groupCollapsed") { if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { console[method](...args); return; } } const styles = [ `background: ${methodToColorMap[method]}`, `border-radius: 0.5em`, `color: white`, `font-weight: bold`, `padding: 2px 0.5em` ]; const logPrefix = inGroup ? [] : ["%cremix-pwa", styles.join(";")]; console[method](...logPrefix, ...args); if (method === "groupCollapsed") { inGroup = true; } if (method === "groupEnd") { inGroup = false; } }; const api = {}; const loggerMethods = Object.keys(methodToColorMap); for (const key of loggerMethods) { const method = key; api[method] = (...args) => { print(method, args); }; } return api; })(); // node_modules/@remix-pwa/sw/dist/src/utils/worker.js function isMethod(request, methods) { return methods.includes(request.method.toLowerCase()); } function isAssetRequest(request, assetUrls = ["/build/", "/icons"]) { return isMethod(request, ["get"]) && assetUrls.some((publicPath) => request.url.includes(publicPath)); } function isLoaderRequest(request) { const url = new URL(request.url); return isMethod(request, ["get"]) && url.searchParams.get("_data"); } var matchRequest = (request, assetUrls = ["/build/", "/icons"]) => { if (isAssetRequest(request, assetUrls)) { return "asset"; } else if (isLoaderRequest(request)) { return "loader"; } else { return null; } }; // node_modules/@remix-pwa/sw/dist/src/message/message.js var MessageHandler = class { /** * The plugins array is used to run plugins before and after the message handler. * They are passed in when the handler is initialised. */ plugins; /** * The state object is used to pass data between plugins. */ state; constructor({ plugins, state } = {}) { this.plugins = plugins || []; this.state = state || {}; } /** * The method that handles the message event. * * Takes in the MessageEvent as a mandatory argument as well as an optional * object that can be used to pass further information/data. */ async handle(event, state = {}) { await this._handleMessage(event, state); } /** * Runs the plugins that are passed in when the handler is initialised. */ async runPlugins(hook, env) { for (const plugin of this.plugins) { if (plugin[hook]) { plugin[hook](env); } } } }; // node_modules/@remix-pwa/sw/dist/src/message/remixNavigationHandler.js var RemixNavigationHandler = class extends MessageHandler { dataCacheName; documentCacheName; constructor({ dataCache: dataCache2, documentCache: documentCache2, plugins, state }) { super({ plugins, state }); this.dataCacheName = dataCache2; this.documentCacheName = documentCache2; this._handleMessage = this._handleMessage.bind(this); } async _handleMessage(event) { const { data } = event; let dataCache2, documentCache2; dataCache2 = this.dataCacheName; documentCache2 = this.documentCacheName; this.runPlugins("messageDidReceive", { event }); const cachePromises = /* @__PURE__ */ new Map(); if (data.type === "REMIX_NAVIGATION") { const { isMount, location, manifest, matches } = data; const documentUrl = location.pathname + location.search + location.hash; if (typeof dataCache2 === "string") { dataCache2 = Storage.open(dataCache2); } if (typeof documentCache2 === "string") { documentCache2 = Storage.open(documentCache2); } const existingDocument = await Storage._match(documentUrl); if (!existingDocument || !isMount) { const response = await fetch(documentUrl); cachePromises.set(documentUrl, documentCache2.put(documentUrl, response).catch((error) => { if (true) logger.error(`Failed to cache document for ${documentUrl}:`, error); })); } if (isMount) { for (const match of matches) { if (manifest.routes[match.id].hasLoader) { const params = new URLSearchParams(location.search); params.set("_data", match.id); let search = params.toString(); search = search ? `?${search}` : ""; const url = location.pathname + search + location.hash; if (!cachePromises.has(url)) { if (true) logger.debug("Caching data for:", url); const response = await fetch(url); cachePromises.set(url, dataCache2.put(url, response).catch((error) => { if (true) logger.error(`Failed to cache data for ${url}:`, error); })); } } } } } await Promise.all(cachePromises.values()); } }; // app/entry.worker.ts var PAGES = "page-cache"; var DATA = "data-cache"; var ASSETS = "assets-cache"; var dataCache = Storage.open(DATA, { ttl: 60 * 60 * 24 * 7 * 1e3 // 7 days }); var documentCache = Storage.open(PAGES); var assetCache = Storage.open(ASSETS); self.addEventListener("install", (event) => { logger.log("Service worker installed"); event.waitUntil(self.skipWaiting()); }); self.addEventListener("activate", (event) => { logger.log("Service worker activated"); event.waitUntil(self.clients.claim()); }); var dataHandler = networkFirst({ cache: dataCache }); var assetsHandler = cacheFirst({ cache: assetCache, cacheQueryOptions: { ignoreSearch: true, ignoreVary: true } }); var defaultFetchHandler = ({ context, request }) => { const type = matchRequest(request); if (type === "asset") { return assetsHandler(context.event.request); } if (type === "loader") { return dataHandler(context.event.request); } return context.fetchFromServer(); }; var handler = new RemixNavigationHandler({ dataCache, documentCache }); self.addEventListener("message", (event) => { event.waitUntil(handler.handle(event)); }); // entry-module:@remix-pwa/build/magic var route0 = __toESM(require_root()); var route1 = __toESM(require_manifest_webmanifest()); // assets-module:@remix-pwa/dev?assets var assets = ["/build/root-A55XQRCR.js", "/build/manifest-1A1450D4.js", "/build/entry.client-QYHX7HDK.js", "/build/__remix_entry_dev-OJT2RCOT.js", "/build/routes/manifest[.]webmanifest-J3KYYY3Q.js", "/build/_shared/runtime-GC7QIU56.js", "/build/_shared/remix_hmr-H6NO35BI.js", "/build/_shared/react-dom-BEFB7ICU.js", "/build/_shared/react-3OYUNTOK.js", "/build/_shared/jsx-runtime-7NXSP56X.js", "/build/_shared/jsx-dev-runtime-RDH4Y5YT.js", "/build/_shared/esm-53CCV4U4.js", "/build/_shared/client-DFZR44C7.js", "/build/_shared/chunk-ZWGWGGVF.js", "/build/_shared/chunk-XU7DNSPJ.js", "/build/_shared/chunk-UWV35TSL.js", "/build/_shared/chunk-PNG5AS42.js", "/build/_shared/chunk-OJSEL2DI.js", "/build/_shared/chunk-KFYUZA3E.js", "/build/_shared/chunk-GIAAE3CH.js", "/build/_shared/chunk-BOXFZXVX.js"]; // entry-module:@remix-pwa/build/magic var routes = { "root": { id: "root", parentId: void 0, path: "", index: void 0, caseSensitive: void 0, module: route0 }, "routes/manifest[.]webmanifest": { id: "routes/manifest[.]webmanifest", parentId: "root", path: "manifest.webmanifest", index: void 0, caseSensitive: void 0, module: route1 } }; var entry = { module: entry_worker_exports }; // node_modules/@remix-pwa/worker-runtime/dist/src/utils/handle-request.js init_router(); var import_mode = __toESM(require_mode(), 1); var import_responses2 = __toESM(require_responses(), 1); // node_modules/@remix-pwa/worker-runtime/dist/src/utils/request.js init_router(); function clone(_object) { const init = {}; for (const property in _object) { init[property] = _object[property]; } return init; } function getURLParameters(request, path = "") { const url = new URL(request.url); const match = matchPath(path, url.pathname); return { ...Object.fromEntries(new URL(request.url).searchParams.entries()), ...match?.params }; } function stripIndexParameter(request) { const url = new URL(request.url); const indexValues = url.searchParams.getAll("index"); const indexValuesToKeep = []; url.searchParams.delete("index"); for (const indexValue of indexValues) { if (indexValue) { indexValuesToKeep.push(indexValue); } } for (const toKeep of indexValuesToKeep) { url.searchParams.append("index", toKeep); } return new Request(url.href, { ...clone(request), duplex: "half" }); } function stripDataParameter(request) { const url = new URL(request.url); url.searchParams.delete("_data"); return new Request(url.href, { ...clone(request), duplex: "half" }); } function createArgumentsFrom({ event, loadContext, path }) { const request = stripDataParameter(stripIndexParameter(event.request.clone())); const parameters = getURLParameters(request, path); return { request, params: parameters, context: loadContext }; } function isMethod2(request, methods) { return methods.includes(request.method.toLowerCase()); } function isActionRequest(request) { const url = new URL(request.url); return isMethod2(request, ["post", "delete", "put", "patch"]) && url.searchParams.get("_data"); } function isLoaderRequest2(request) { const url = new URL(request.url); return isMethod2(request, ["get"]) && url.searchParams.get("_data"); } // node_modules/@remix-pwa/worker-runtime/dist/src/utils/response.js var import_responses = __toESM(require_responses(), 1); function errorResponseToJson(errorResponse) { return (0, import_responses.json)(errorResponse.error || { message: "Unexpected Server Error" }, { status: errorResponse.status, statusText: errorResponse.statusText, headers: { "X-Remix-Error": "yes" } }); } function isRemixResponse(response) { return Array.from(response.headers.keys()).some((key) => key.toLowerCase().startsWith("x-remix-")); } // node_modules/@remix-pwa/worker-runtime/dist/src/utils/handle-request.js async function handleRequest({ defaultHandler: defaultHandler2, errorHandler, event, loadContext, routes: routes2 }) { const url = new URL(event.request.url); const routeId = url.searchParams.get("_data"); const route = routeId ? routes2[routeId] : void 0; const _arguments = { request: event.request, params: getURLParameters(event.request, route?.path), context: loadContext }; try { if (isLoaderRequest2(event.request) && route?.module.workerLoader) { return await handleLoader({ event, loader: route.module.workerLoader, routeId: route.id, routePath: route.path, loadContext }).then(responseHandler); } if (isActionRequest(event.request) && route?.module?.workerAction) { return await handleAction({ event, action: route.module.workerAction, routeId: route.id, routePath: route.path, loadContext }).then(responseHandler); } } catch (error) { const handler2 = (error2) => errorHandler(error2, _arguments); return _errorHandler({ error, handler: handler2 }); } return defaultHandler2(_arguments); } async function handleLoader({ event, loadContext, loader, routeId, routePath }) { const _arguments = createArgumentsFrom({ event, loadContext, path: routePath }); const result = await loader(_arguments); if (result === void 0) { throw new Error(`You defined a loader for route "${routeId}" but didn't return anything from your \`worker loader\` function. Please return a value or \`null\`.`); } if ((0, import_responses2.isDeferredData)(result)) { if (result.init && (0, import_responses2.isRedirectStatusCode)(result.init.status || 200)) { return (0, import_responses2.redirect)(new Headers(result.init.headers).get("Location"), result.init); } const body = (0, import_responses2.createDeferredReadableStream)(result, event.request.signal, import_mode.ServerMode.Production); const init = result.init || {}; const headers = new Headers(init.headers); headers.set("Content-Type", "text/remix-deferred"); init.headers = headers; return new Response(body, init); } return (0, import_responses2.isResponse)(result) ? result : (0, import_responses2.json)(result); } async function handleAction({ action, event, loadContext, routeId, routePath }) { const _arguments = createArgumentsFrom({ event, loadContext, path: routePath }); const result = await action(_arguments); if (result === void 0) { throw new Error(`You defined an action for route "${routeId}" but didn't return anything from your \`worker action\` function. Please return a value or \`null\`.`); } return (0, import_responses2.isResponse)(result) ? result : (0, import_responses2.json)(result); } function _errorHandler({ error, handler: handleError }) { if ((0, import_responses2.isResponse)(error)) { error.headers.set("X-Remix-Catch", "yes"); return error; } if (isRouteErrorResponse(error)) { error.error && handleError(error.error); return errorResponseToJson(error); } const errorInstance = error instanceof Error ? error : new Error("Unexpected Server Error"); handleError(errorInstance); return (0, import_responses2.json)({ message: errorInstance.message }, { status: 500, headers: { "X-Remix-Error": "yes" } }); } function responseHandler(response) { if ((0, import_responses2.isRedirectResponse)(response)) { const headers = new Headers(response.headers); headers.set("X-Remix-Redirect", headers.get("Location")); headers.set("X-Remix-Status", String(response.status)); headers.delete("Location"); if (response.headers.get("Set-Cookie") !== null) { headers.set("X-Remix-Revalidate", "yes"); } return new Response(null, { status: 204, headers }); } !isRemixResponse(response) && response.headers.set("X-Remix-Response", "yes"); return response; } // node_modules/@remix-pwa/worker-runtime/dist/src/service-worker.internal.js var _self = self; function createContext(event) { const context = entry.module.getLoadContext?.(event) || {}; return { event, fetchFromServer: () => fetch(event.request.clone()), // NOTE: we want the user to override the above properties if needed. ...context }; } var defaultHandler = entry.module.defaultFetchHandler || ((event) => fetch(event.request.clone())); var defaultErrorHandler = entry.module.errorHandler || ((error, { request }) => { if (!request.signal.aborted) { console.error(error); } }); _self.__workerManifest = { assets, routes }; _self.addEventListener( "fetch", /** * The main fetch event listener callback. */ (event) => { const response = handleRequest({ event, routes, defaultHandler, errorHandler: defaultErrorHandler, loadContext: createContext(event) }); return event.respondWith(response); } ); /*! Bundled license information: ieee754/index.js: (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *) buffer/index.js: (*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT *) @remix-run/router/dist/router.js: (** * @remix-run/router v1.15.0 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT *) @remix-run/server-runtime/dist/mode.js: (** * @remix-run/server-runtime v2.6.0 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT *) @remix-run/server-runtime/dist/errors.js: (** * @remix-run/server-runtime v2.6.0 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT *) @remix-run/server-runtime/dist/responses.js: (** * @remix-run/server-runtime v2.6.0 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT *) */